@mux/mux-player 3.13.1-canary.0 → 3.13.1-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/mux-player.js +2 -2
- package/dist/mux-player.mjs +2 -2
- package/dist/tsconfig.tsbuildinfo +1 -1
- package/package.json +1 -1
package/dist/mux-player.js
CHANGED
|
@@ -53,9 +53,9 @@ Schedule: ${l.map(p=>Ci(p))} pos: ${this.timelinePos}`),u.length&&this.log(`Remo
|
|
|
53
53
|
`),d=[],u=e?wk(e.baseTime,e.timescale):0,c="00:00.000",h=0,f=0,m,p=!0;o.oncue=function(g){let v=t[s],T=t.ccOffset,y=(h-u)/9e4;if(v!=null&&v.new&&(f!==void 0?T=t.ccOffset=v.start:eC(t,s,y)),y){if(!e){m=new Error("Missing initPTS for VTT MPEGTS");return}T=y-t.presentationOffset}let b=g.endTime-g.startTime,A=ai((g.startTime+T-f)*9e4,r*9e4)/9e4;g.startTime=Math.max(A,0),g.endTime=Math.max(A+b,0);let R=g.text.trim();g.text=decodeURIComponent(encodeURIComponent(R)),g.id||(g.id=hg(g.startTime,g.endTime,R)),g.endTime>0&&d.push(g)},o.onparsingerror=function(g){m=g},o.onflush=function(){if(m){a(m);return}n(d)},l.forEach(g=>{if(p)if(Sm(g,"X-TIMESTAMP-MAP=")){p=!1,g.slice(16).split(",").forEach(v=>{Sm(v,"LOCAL:")?c=v.slice(6):Sm(v,"MPEGTS:")&&(h=parseInt(v.slice(7)))});try{f=JD(c)/1e3}catch(v){m=v}return}else g===""&&(p=!1);o.parse(g+`
|
|
54
54
|
`)}),o.flush()}var Im="stpp.ttml.im1t",fb=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,mb=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,iC={left:"start",center:"center",right:"end",start:"start",end:"end"};function Gy(i,e,t,s){let r=be(new Uint8Array(i),["mdat"]);if(r.length===0){s(new Error("Could not parse IMSC1 mdat"));return}let n=r.map(o=>li(o)),a=Ck(e.baseTime,1,e.timescale);try{n.forEach(o=>t(sC(o,a)))}catch(o){s(o)}}function sC(i,e){let r=new DOMParser().parseFromString(i,"text/xml").getElementsByTagName("tt")[0];if(!r)throw new Error("Invalid ttml");let n={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:0},a=Object.keys(n).reduce((c,h)=>(c[h]=r.getAttribute(`ttp:${h}`)||n[h],c),{}),o=r.getAttribute("xml:space")!=="preserve",l=Ky(Lm(r,"styling","style")),d=Ky(Lm(r,"layout","region")),u=Lm(r,"body","[begin]");return[].map.call(u,c=>{let h=pb(c,o);if(!h||!c.hasAttribute("begin"))return null;let f=xm(c.getAttribute("begin"),a),m=xm(c.getAttribute("dur"),a),p=xm(c.getAttribute("end"),a);if(f===null)throw Vy(c);if(p===null){if(m===null)throw Vy(c);p=f+m}let g=new cg(f-e,p-e,h);g.id=hg(g.startTime,g.endTime,g.text);let v=d[c.getAttribute("region")],T=l[c.getAttribute("style")],y=rC(v,T,l),{textAlign:b}=y;if(b){let A=iC[b];A&&(g.lineAlign=A),g.align=b}return $e(g,y),g}).filter(c=>c!==null)}function Lm(i,e,t){let s=i.getElementsByTagName(e)[0];return s?[].slice.call(s.querySelectorAll(t)):[]}function Ky(i){return i.reduce((e,t)=>{let s=t.getAttribute("xml:id");return s&&(e[s]=t),e},{})}function pb(i,e){return[].slice.call(i.childNodes).reduce((t,s,r)=>{var n;return s.nodeName==="br"&&r?t+`
|
|
55
55
|
`:(n=s.childNodes)!=null&&n.length?pb(s,e):e?t+s.textContent.trim().replace(/\s+/g," "):t+s.textContent},"")}function rC(i,e,t){let s="http://www.w3.org/ns/ttml#styling",r=null,n=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],a=i!=null&&i.hasAttribute("style")?i.getAttribute("style"):null;return a&&t.hasOwnProperty(a)&&(r=t[a]),n.reduce((o,l)=>{let d=Rm(e,s,l)||Rm(i,s,l)||Rm(r,s,l);return d&&(o[l]=d),o},{})}function Rm(i,e,t){return i&&i.hasAttributeNS(e,t)?i.getAttributeNS(e,t):null}function Vy(i){return new Error(`Could not parse ttml timestamp ${i}`)}function xm(i,e){if(!i)return null;let t=ub(i);return t===null&&(fb.test(i)?t=nC(i,e):mb.test(i)&&(t=aC(i,e))),t}function nC(i,e){let t=fb.exec(i),s=(t[4]|0)+(t[5]|0)/e.subFrameRate;return(t[1]|0)*3600+(t[2]|0)*60+(t[3]|0)+s/e.frameRate}function aC(i,e){let t=mb.exec(i),s=Number(t[1]);switch(t[2]){case"h":return s*3600;case"m":return s*60;case"ms":return s*1e3;case"f":return s/e.frameRate;case"t":return s/e.tickRate}return s}var Jn=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,s){(this.startTime===null||this.startTime>e)&&(this.startTime=e),this.endTime=t,this.screen=s,this.timelineController.createCaptionsTrack(this.trackName)}reset(){this.cueRanges=[],this.startTime=null}},Bp=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=qy(),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(E.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(E.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(E.FRAG_LOADING,this.onFragLoading,this),e.on(E.FRAG_LOADED,this.onFragLoaded,this),e.on(E.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.on(E.FRAG_DECRYPTED,this.onFragDecrypted,this),e.on(E.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(E.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.on(E.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){let{hls:e}=this;e.off(E.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(E.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(E.FRAG_LOADING,this.onFragLoading,this),e.off(E.FRAG_LOADED,this.onFragLoaded,this),e.off(E.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.off(E.FRAG_DECRYPTED,this.onFragDecrypted,this),e.off(E.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(E.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.off(E.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.media=null,this.cea608Parser1=this.cea608Parser2=void 0}initCea608Parsers(){let e=new Jn(this,"textTrack1"),t=new Jn(this,"textTrack2"),s=new Jn(this,"textTrack3"),r=new Jn(this,"textTrack4");this.cea608Parser1=new wu(1,e,t),this.cea608Parser2=new wu(3,s,r)}addCues(e,t,s,r,n){let a=!1;for(let o=n.length;o--;){let l=n[o],d=oC(l[0],l[1],t,s);if(d>=0&&(l[0]=Math.min(l[0],t),l[1]=Math.max(l[1],s),a=!0,d/(s-t)>.5))return}if(a||n.push([t,s]),this.config.renderTextTracksNatively){let o=this.captionsTracks[e];this.Cues.newCue(o,t,s,r)}else{let o=this.Cues.newCue(null,t,s,r);this.hls.trigger(E.CUES_PARSED,{type:"captions",cues:o,track:e})}}onInitPtsFound(e,{frag:t,id:s,initPTS:r,timescale:n,trackId:a}){let{unparsedVttFrags:o}=this;s===J.MAIN&&(this.initPTS[t.cc]={baseTime:r,timescale:n,trackId:a}),o.length&&(this.unparsedVttFrags=[],o.forEach(l=>{this.initPTS[l.frag.cc]?this.onFragLoaded(E.FRAG_LOADED,l):this.hls.trigger(E.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:l.frag,error:new Error("Subtitle discontinuity domain does not match main")})}))}getExistingTrack(e,t){let{media:s}=this;if(s)for(let r=0;r<s.textTracks.length;r++){let n=s.textTracks[r];if(Wy(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:s,media:r}=this,{label:n,languageCode:a}=t[e],o=this.getExistingTrack(n,a);if(o)s[e]=o,Zn(s[e]),ab(s[e],r);else{let l=this.createTextTrack("captions",n,a);l&&(l[e]=!0,s[e]=l)}}createNonNativeTrack(e){if(this.nonNativeCaptionsTracks[e])return;let t=this.captionsProperties[e];if(!t)return;let s=t.label,r={_id:e,label:s,kind:"captions",default:t.media?!!t.media.default:!1,closedCaptions:t.media};this.nonNativeCaptionsTracks[e]=r,this.hls.trigger(E.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[r]})}createTextTrack(e,t,s){let r=this.media;if(r)return r.addTextTrack(e,t,s)}onMediaAttaching(e,t){this.media=t.media,t.mediaSource||this._cleanTracks()}onMediaDetaching(e,t){let s=!!t.transferMedia;if(this.media=null,s)return;let{captionsTracks:r}=this;Object.keys(r).forEach(n=>{Zn(r[n]),delete r[n]}),this.nonNativeCaptionsTracks={}}onManifestLoading(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=qy(),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 s=0;s<t.length;s++)Zn(t[s])}onSubtitleTracksUpdated(e,t){let s=t.subtitleTracks||[],r=s.some(n=>n.textCodec===Im);if(this.config.enableWebVTT||r&&this.config.enableIMSC1){if(jT(this.tracks,s)){this.tracks=s;return}if(this.textTracks=[],this.tracks=s,this.config.renderTextTracksNatively){let a=this.media,o=a?ou(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]&&Wy(o[h],l)){c=o[h],o[h]=null;break}c&&(u=c)}if(u)Zn(u);else{let c=gb(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(E.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:a})}}}onManifestLoaded(e,t){this.config.enableCEA708Captions&&t.captions&&t.captions.forEach(s=>{let r=/(?:CC|SERVICE)([1-4])/.exec(s.instreamId);if(!r)return;let n=`textTrack${r[1]}`,a=this.captionsProperties[n];a&&(a.label=s.name,s.lang&&(a.languageCode=s.lang),a.media=s)})}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===J.MAIN){var s,r;let{cea608Parser1:n,cea608Parser2:a,lastSn:o}=this,{cc:l,sn:d}=t.frag,u=(s=(r=t.part)==null?void 0:r.index)!=null?s:-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:s,payload:r}=t;if(s.type===J.SUBTITLE)if(r.byteLength){let n=s.decryptdata,a="stats"in t;if(n==null||!n.encrypted||a){let o=this.tracks[s.level],l=this.vttCCs;l[s.cc]||(l[s.cc]={start:s.start,prevCC:this.prevCC,new:!0},this.prevCC=s.cc),o&&o.textCodec===Im?this._parseIMSC1(s,r):this._parseVTTs(t)}}else this.hls.trigger(E.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:s,error:new Error("Empty subtitle payload")})}_parseIMSC1(e,t){let s=this.hls;Gy(t,this.initPTS[e.cc],r=>{this._appendCues(r,e.level),s.trigger(E.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:e})},r=>{s.logger.log(`Failed to parse IMSC1: ${r}`),s.trigger(E.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e,error:r})})}_parseVTTs(e){var t;let{frag:s,payload:r}=e,{initPTS:n,unparsedVttFrags:a}=this,o=n.length-1;if(!n[s.cc]&&o===-1){a.push(e);return}let l=this.hls,d=(t=s.initSegment)!=null&&t.data?pi(s.initSegment.data,new Uint8Array(r)).buffer:r;tC(d,this.initPTS[s.cc],this.vttCCs,s.cc,s.start,u=>{this._appendCues(u,s.level),l.trigger(E.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:s})},u=>{let c=u.message==="Missing initPTS for VTT MPEGTS";c?a.push(e):this._fallbackToIMSC1(s,r),l.logger.log(`Failed to parse VTT cue: ${u}`),!(c&&o>s.cc)&&l.trigger(E.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:s,error:u})})}_fallbackToIMSC1(e,t){let s=this.tracks[e.level];s.textCodec||Gy(t,this.initPTS[e.cc],()=>{s.textCodec=Im,this._parseIMSC1(e,t)},()=>{s.textCodec="wvtt"})}_appendCues(e,t){let s=this.hls;if(this.config.renderTextTracksNatively){let r=this.textTracks[t];if(!r||r.mode==="disabled")return;e.forEach(n=>ob(r,n))}else{let r=this.tracks[t];if(!r)return;let n=r.default?"default":"subtitles"+t;s.trigger(E.CUES_PARSED,{type:"subtitles",cues:e,track:n})}}onFragDecrypted(e,t){let{frag:s}=t;s.type===J.SUBTITLE&&this.onFragLoaded(E.FRAG_LOADED,t)}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(e,t){if(!this.enabled||!this.config.enableCEA708Captions)return;let{frag:s,samples:r}=t;if(!(s.type===J.MAIN&&this.closedCaptionsForLevel(s)==="NONE"))for(let n=0;n<r.length;n++){let a=r[n].bytes;if(a){this.cea608Parser1||this.initCea608Parsers();let o=this.extractCea608Data(a);this.cea608Parser1.addData(r[n].pts,o[0]),this.cea608Parser2.addData(r[n].pts,o[1])}}}onBufferFlushing(e,{startOffset:t,endOffset:s,endOffsetSubtitles:r,type:n}){let{media:a}=this;if(!(!a||a.currentTime<s)){if(!n||n==="video"){let{captionsTracks:o}=this;Object.keys(o).forEach(l=>Ap(o[l],t,s))}if(this.config.renderTextTracksNatively&&t===0&&r!==void 0){let{textTracks:o}=this;Object.keys(o).forEach(l=>Ap(o[l],t,r))}}}extractCea608Data(e){let t=[[],[]],s=e[0]&31,r=2;for(let n=0;n<s;n++){let a=e[r++],o=127&e[r++],l=127&e[r++];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 gb(i){return i.characteristics&&/transcribes-spoken-dialog/gi.test(i.characteristics)&&/describes-music-and-sound/gi.test(i.characteristics)?"captions":"subtitles"}function Wy(i,e){return!!i&&i.kind===gb(e)&&hp(e,i)}function oC(i,e,t,s){return Math.min(e,s)-Math.max(i,t)}function qy(){return{ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}}}var lC=/\s/,dC={newCue(i,e,t,s){let r=[],n,a,o,l,d,u=self.VTTCue||self.TextTrackCue;for(let h=0;h<s.rows.length;h++)if(n=s.rows[h],o=!0,l=0,d="",!n.isEmpty()){var c;for(let p=0;p<n.chars.length;p++)lC.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=hb(d.trim()),m=hg(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),r.push(a))}return i&&r.length&&(r.sort((h,f)=>h.line==="auto"||f.line==="auto"?0:h.line>8&&f.line>8?f.line-h.line:h.line-f.line),r.forEach(h=>ob(i,h))),r}};function uC(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch{}return!1}var cC=/(\d+)-(\d+)\/(\d+)/,Mu=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||pC,this.controller=new self.AbortController,this.stats=new Fo}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,s){let r=this.stats;if(r.loading.start)throw new Error("Loader can only be used once.");r.loading.start=self.performance.now();let n=hC(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=s,this.request=this.fetchSetup(e,n),self.clearTimeout(this.requestTimeout),t.timeout=l&&Q(l)?l:d,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(r,e,this.response))},t.timeout),(Yo(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(),r.loading.start);if(self.clearTimeout(this.requestTimeout),t.timeout=d,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(r,e,this.response))},d-(f-r.loading.start)),!c.ok){let{status:p,statusText:g}=c;throw new $p(g||"fetch, bad network response",p,c)}r.loading.first=f,r.total=mC(c.headers)||r.total;let m=(h=this.callbacks)==null?void 0:h.onProgress;return m&&Q(t.highWaterMark)?this.loadProgressively(c,r,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),r.loading.end=Math.max(self.performance.now(),r.loading.first);let p=c[o];p&&(r.loaded=r.total=p);let g={url:m.url,data:c,code:m.status},v=(h=this.callbacks)==null?void 0:h.onProgress;v&&!Q(t.highWaterMark)&&v(r,e,c,m),(f=this.callbacks)==null||f.onSuccess(g,r,e,m)}).catch(c=>{var h;if(self.clearTimeout(this.requestTimeout),r.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,r)})}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,s,r=0,n){let a=new _u,o=e.body.getReader(),l=()=>o.read().then(d=>{if(d.done)return a.dataLength&&n(t,s,a.flush().buffer,e),Promise.resolve(new ArrayBuffer(0));let u=d.value,c=u.length;return t.loaded+=c,c<r||a.dataLength?(a.push(u),a.dataLength>=r&&n(t,s,a.flush().buffer,e)):n(t,s,u.buffer,e),l()}).catch(()=>Promise.reject());return l()}};function hC(i,e){let t={method:"GET",mode:"cors",credentials:"same-origin",signal:e,headers:new self.Headers($e({},i.headers))};return i.rangeEnd&&t.headers.set("Range","bytes="+i.rangeStart+"-"+String(i.rangeEnd-1)),t}function fC(i){let e=cC.exec(i);if(e)return parseInt(e[2])-parseInt(e[1])+1}function mC(i){let e=i.get("Content-Range");if(e){let s=fC(e);if(Q(s))return s}let t=i.get("Content-Length");if(t)return parseInt(t)}function pC(i,e){return new self.Request(i.url,e)}var $p=class extends Error{constructor(e,t,s){super(e),this.code=void 0,this.details=void 0,this.code=t,this.details=s}},gC=/^age:\s*[\d.]+\s*$/im,Pu=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 Fo,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,s){if(this.stats.loading.start)throw new Error("Loader can only be used once.");this.stats.loading.start=self.performance.now(),this.context=e,this.config=t,this.callbacks=s,this.loadInternal()}loadInternal(){let{config:e,context:t}=this;if(!e||!t)return;let s=this.loader=new self.XMLHttpRequest,r=this.stats;r.loading.first=0,r.loaded=0,r.aborted=!1;let n=this.xhrSetup;n?Promise.resolve().then(()=>{if(!(this.loader!==s||this.stats.aborted))return n(s,t.url)}).catch(a=>{if(!(this.loader!==s||this.stats.aborted))return s.open("GET",t.url,!0),n(s,t.url)}).then(()=>{this.loader!==s||this.stats.aborted||this.openAndSendXhr(s,t,e)}).catch(a=>{var o;(o=this.callbacks)==null||o.onError({code:s.status,text:a.message},t,s,r)}):this.openAndSendXhr(s,t,e)}openAndSendXhr(e,t,s){e.readyState||e.open("GET",t.url,!0);let r=t.headers,{maxTimeToFirstByteMs:n,maxLoadTimeMs:a}=s.loadPolicy;if(r)for(let o in r)e.setRequestHeader(o,r[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),s.timeout=n&&Q(n)?n:a,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),s.timeout),e.send()}readystatechange(){let{context:e,loader:t,stats:s}=this;if(!e||!t)return;let r=t.readyState,n=this.config;if(!s.aborted&&r>=2&&(s.loading.first===0&&(s.loading.first=Math.max(self.performance.now(),s.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-(s.loading.first-s.loading.start)))),r===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;s.loading.end=Math.max(self.performance.now(),s.loading.first);let p=t.responseType==="arraybuffer"?m.byteLength:m.length;s.loaded=s.total=p,s.bwEstimate=s.total*8e3/(s.loading.end-s.loading.first);let g=(a=this.callbacks)==null?void 0:a.onProgress;g&&g(s,e,m,t);let v={url:t.responseURL,data:m,code:d};(o=this.callbacks)==null||o.onSuccess(v,s,e,t);return}}let c=n.loadPolicy.errorRetry,h=s.retry,f={url:e.url,data:void 0,code:d};if(gu(c,h,!1,f))this.retry(c);else{var l;Be.error(`${d} while loading ${e.url}`),(l=this.callbacks)==null||l.onError({code:d,text:t.statusText},e,t,s)}}}loadtimeout(){if(!this.config)return;let e=this.config.loadPolicy.timeoutRetry,t=this.stats.retry;if(gu(e,t,!0))this.retry(e);else{var s;Be.warn(`timeout while loading ${(s=this.context)==null?void 0:s.url}`);let r=this.callbacks;r&&(this.abortInternal(),r.onTimeout(this.stats,this.context,this.loader))}}retry(e){let{context:t,stats:s}=this;this.retryDelay=eg(e,s.retry),s.retry++,Be.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${t==null?void 0:t.url}, retrying ${s.retry}/${e.maxNumRetry} in ${this.retryDelay}ms`),this.abortInternal(),this.loader=null,self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(this.loadInternal.bind(this),this.retryDelay)}loadprogress(e){let t=this.stats;t.loaded=e.loaded,e.lengthComputable&&(t.total=e.total)}getCacheAge(){let e=null;if(this.loader&&gC.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}},vC={maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null},EC=Fe(Fe({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:Pu,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:Fm,bufferController:gp,capLevelController:Qo,errorController:$m,fpsController:_p,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:TT,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:vC},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},yC()),{},{subtitleStreamController:Dp,subtitleTrackController:Sp,timelineController:Bp,audioStreamController:cp,audioTrackController:fp,emeController:xu,cmcdController:Tp,contentSteeringController:bp,interstitialsController:kp});function yC(){return{cueHandler:dC,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 TC(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 s=Hp(i),r=["manifest","level","frag"],n=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return r.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=s[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}": ${qe(e[o])}`)}),Fe(Fe({},s),e)}function Hp(i){return i&&typeof i=="object"?Array.isArray(i)?i.map(Hp):Object.keys(i).reduce((e,t)=>(e[t]=Hp(i[t]),e),{}):i}function bC(i,e){let t=i.loader;t!==Mu&&t!==Pu?(e.log("[config]: Custom loader detected, cannot enable progressive streaming"),i.progressive=!1):uC()&&(i.loader=Mu,i.progressive=!0,i.enableSoftwareAES=!0,e.log("[config]: Progressive streaming enabled, using FetchLoader"))}var lu=2,_C=.1,AC=.05,SC=100,Gp=class extends vu{constructor(e,t){super("gap-controller",e.logger),this.hls=void 0,this.fragmentTracker=void 0,this.media=null,this.mediaSource=void 0,this.nudgeRetry=0,this.stallReported=!1,this.stalled=null,this.moved=!1,this.seeking=!1,this.buffered={},this.lastCurrentTime=0,this.ended=0,this.waiting=0,this.onMediaPlaying=()=>{this.ended=0,this.waiting=0},this.onMediaWaiting=()=>{var s;(s=this.media)!=null&&s.seeking||(this.waiting=self.performance.now(),this.tick())},this.onMediaEnded=()=>{if(this.hls){var s;this.ended=((s=this.media)==null?void 0:s.currentTime)||1,this.hls.trigger(E.MEDIA_ENDED,{stalled:!1})}},this.hls=e,this.fragmentTracker=t,this.registerListeners()}registerListeners(){let{hls:e}=this;e&&(e.on(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(E.BUFFER_APPENDED,this.onBufferAppended,this))}unregisterListeners(){let{hls:e}=this;e&&(e.off(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(E.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(SC),this.mediaSource=t.mediaSource;let s=this.media=t.media;Ht(s,"playing",this.onMediaPlaying),Ht(s,"waiting",this.onMediaWaiting),Ht(s,"ended",this.onMediaEnded)}onMediaDetaching(e,t){this.clearInterval();let{media:s}=this;s&&(zt(s,"playing",this.onMediaPlaying),zt(s,"waiting",this.onMediaWaiting),zt(s,"ended",this.onMediaEnded),this.media=null),this.mediaSource=void 0}onBufferAppended(e,t){this.buffered=t.timeRanges}get hasBuffered(){return Object.keys(this.buffered).length>0}tick(){var e;if(!((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 s,r;let n=(s=this.hls)==null?void 0:s.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(E.MEDIA_ENDED,{stalled:!1}));return}if(!Ee.getBuffered(a).length){this.nudgeRetry=0;return}let c=Ee.bufferInfo(a,e,0),h=c.nextStart||0,f=this.fragmentTracker;if(o&&f&&this.hls){let R=Yy(this.hls.inFlightFragments,e),I=c.len>lu,x=!h||R||h-e>lu&&!f.getPartialFragment(e);if(I||x)return;this.moved=!1}let m=(r=this.hls)==null?void 0:r.latestLevelDetails;if(!this.moved&&this.stalled!==null&&f){if(!(c.len>0)&&!h)return;let I=Math.max(h,c.start||0)-e,D=!!(m!=null&&m.live)?m.targetduration*2:lu,S=eu(e,f);if(I>0&&(I<=D||S)){a.paused||this._trySkipBufferHole(S);return}}let p=n.detectStallWithCurrentTimeMs,g=self.performance.now(),v=this.waiting,T=this.stalled;if(T===null)if(v>0&&g-v<p)T=this.stalled=v;else{this.stalled=g;return}let y=g-T;if(!o&&(y>=p||v)&&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(E.MEDIA_ENDED,{stalled:!0});return}if(this._reportStall(c),!this.media||!this.hls)return}let A=Ee.bufferInfo(a,e,n.maxBufferHole);this._tryFixBufferStall(A,y,e)}stallResolved(e){let t=this.stalled;if(t&&this.hls&&(this.stalled=null,this.stallReported)){let s=self.performance.now()-t;this.log(`playback not stuck anymore @${e}, after ${Math.round(s)}ms`),this.stallReported=!1,this.waiting=0,this.hls.trigger(E.STALL_RESOLVED,{})}}nudgeOnVideoHole(e,t){var s;let r=this.buffered.video;if(this.hls&&this.media&&this.fragmentTracker&&(s=this.buffered.audio)!=null&&s.length&&r&&r.length>1&&e>r.end(0)){let n=Ee.bufferedInfo(Ee.timeRangesToArray(this.buffered.audio),e,0);if(n.len>1&&t>=n.start){let a=Ee.timeRangesToArray(r),o=Ee.bufferedInfo(a,t,0).bufferedIndex;if(o>-1&&o<a.length-1){let l=Ee.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=eu(e,this.fragmentTracker);h&&"fragment"in h?h=h.fragment:h||(h=void 0);let f=Ee.bufferInfo(this.media,e,0);this.hls.trigger(E.ERROR,{type:se.MEDIA_ERROR,details:M.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:c,reason:c.message,frag:h,buffer:f.len,bufferInfo:f})}}}}}_tryFixBufferStall(e,t,s){var r,n;let{fragmentTracker:a,media:o}=this,l=(r=this.hls)==null?void 0:r.config;if(!o||!a||!l)return;let d=(n=this.hls)==null?void 0:n.latestLevelDetails,u=eu(s,a);if((u||d!=null&&d.live&&s<d.fragmentStart)&&(this._trySkipBufferHole(u)||!this.media))return;let c=e.buffered,h=this.adjacentTraversal(e,s);(c&&c.length>1&&e.len>l.maxBufferHole||e.nextStart&&(e.nextStart-s<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 s=this.fragmentTracker,r=e.nextStart;if(s&&r){let n=s.getFragAtPos(t,J.MAIN),a=s.getFragAtPos(r,J.MAIN);if(n&&a)return a.sn-n.sn<2}return!1}_reportStall(e){let{hls:t,media:s,stallReported:r,stalled:n}=this;if(!r&&n!==null&&s&&t){this.stallReported=!0;let a=new Error(`Playback stalling at @${s.currentTime} due to low buffer (${qe(e)})`);this.warn(a.message),t.trigger(E.ERROR,{type:se.MEDIA_ERROR,details:M.BUFFER_STALLED_ERROR,fatal:!1,error:a,buffer:e.len,bufferInfo:e,stalled:{start:n}})}}_trySkipBufferHole(e){var t;let{fragmentTracker:s,media:r}=this,n=(t=this.hls)==null?void 0:t.config;if(!r||!s||!n)return 0;let a=r.currentTime,o=Ee.bufferInfo(r,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&&r.readyState<3,h=l-a;if(h>0&&(u||c)){if(h>n.maxBufferHole){let m=!1;if(a===0){let p=s.getAppendedFrag(0,J.MAIN);p&&l<p.end&&(m=!0)}if(!m&&e){var d;if(!((d=this.hls.loadLevelObj)!=null&&d.details)||Yy(this.hls.inFlightFragments,l))return 0;let g=!1,v=e.end;for(;v<l;){let T=eu(v,s);if(T)v+=T.duration;else{g=!0;break}}if(g)return 0}}let f=Math.max(l+AC,a+_C);if(this.warn(`skipping hole, adjusting currentTime from ${a} to ${f}`),this.moved=!0,r.currentTime=f,!(e!=null&&e.gap)){let m=new Error(`fragment loaded with buffer holes, seeking from ${a} to ${f}`),p={type:se.MEDIA_ERROR,details:M.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:m,reason:m.message,buffer:o.len,bufferInfo:o};e&&("fragment"in e?p.part=e:p.frag=e),this.hls.trigger(E.ERROR,p)}return f}}return 0}_tryNudgeBuffer(e){let{hls:t,media:s,nudgeRetry:r}=this,n=t==null?void 0:t.config;if(!s||!n)return 0;let a=s.currentTime;if(this.nudgeRetry++,r<n.nudgeMaxRetry){let o=a+(r+1)*n.nudgeOffset,l=new Error(`Nudging 'currentTime' from ${a} to ${o}`);this.warn(l.message),s.currentTime=o,t.trigger(E.ERROR,{type:se.MEDIA_ERROR,details:M.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(E.ERROR,{type:se.MEDIA_ERROR,details:M.BUFFER_STALLED_ERROR,error:o,fatal:!0,buffer:e.len,bufferInfo:e})}}};function Yy(i,e){let t=jy(i.main);if(t&&t.start<=e)return t;let s=jy(i.audio);return s&&s.start<=e?s:null}function jy(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}function eu(i,e){return e.getAppendedFrag(i,J.MAIN)||e.getPartialFragment(i)}var IC=.25;function Kp(){if(typeof self!="undefined")return self.VTTCue||self.TextTrackCue}function km(i,e,t,s,r){let n=new i(e,t,"");try{n.value=s,r&&(n.type=r)}catch{n=new i(e,t,qe(r?Fe({type:r},s):s))}return n}var tu=(()=>{let i=Kp();try{i&&new i(0,Number.POSITIVE_INFINITY,"")}catch{return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})(),Vp=class{constructor(e){this.hls=void 0,this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.removeCues=!0,this.assetCue=void 0,this.onEventCueEnter=()=>{this.hls&&this.hls.trigger(E.EVENT_CUE_ENTER,{})},this.hls=e,this._registerListeners()}destroy(){this._unregisterListeners(),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=this.onEventCueEnter=null}_registerListeners(){let{hls:e}=this;e&&(e.on(E.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.on(E.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(E.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(E.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}_unregisterListeners(){let{hls:e}=this;e&&(e.off(E.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.off(E.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(E.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(E.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}onMediaAttaching(e,t){var s;this.media=t.media,((s=t.overrides)==null?void 0:s.cueRemoval)===!1&&(this.removeCues=!1)}onMediaAttached(){var e;let t=(e=this.hls)==null?void 0:e.latestLevelDetails;t&&this.updateDateRangeCues(t)}onMediaDetaching(e,t){this.media=null,!t.transferMedia&&(this.id3Track&&(this.removeCues&&Zn(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 s=e[t];if(s.kind==="metadata"&&s.label==="id3")return ab(s,this.media),s}return this.media.addTextTrack("metadata","id3")}}onFragParsingMetadata(e,t){if(!this.media||!this.hls)return;let{enableEmsgMetadataCues:s,enableID3MetadataCues:r}=this.hls.config;if(!s&&!r)return;let{samples:n}=t;this.id3Track||(this.id3Track=this.createTrack(this.media));let a=Kp();if(a)for(let o=0;o<n.length;o++){let l=n[o].type;if(l===oi.emsg&&!s||!r)continue;let d=UT(n[o].data),u=n[o].pts,c=u+n[o].duration;c>tu&&(c=tu),c-u<=0&&(c=u+IC);for(let f=0;f<d.length;f++){let m=d[f];if(!FT(m)){this.updateId3CueEnds(u,l);let p=km(a,u,c,m,l);p&&this.id3Track.addCue(p)}}}}updateId3CueEnds(e,t){var s;let r=(s=this.id3Track)==null?void 0:s.cues;if(r)for(let n=r.length;n--;){let a=r[n];a.type===t&&a.startTime<e&&a.endTime===tu&&(a.endTime=e)}}onBufferFlushing(e,{startOffset:t,endOffset:s,type:r}){let{id3Track:n,hls:a}=this;if(!a)return;let{config:{enableEmsgMetadataCues:o,enableID3MetadataCues:l}}=a;if(n&&(o||l)){let d;r==="audio"?d=u=>u.type===oi.audioId3&&l:r==="video"?d=u=>u.type===oi.emsg&&o:d=u=>u.type===oi.audioId3&&l||u.type===oi.emsg&&o,Ap(n,t,s,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.hls||!this.media)return;let{assetPlayerId:s,timelineOffset:r,enableDateRangeMetadataCues:n,interstitialsController:a}=this.hls.config;if(!n)return;let o=Kp();if(s&&r&&!a){let{fragmentStart:p,fragmentEnd:g}=e,v=this.assetCue;v?(v.startTime=p,v.endTime=g):o&&(v=this.assetCue=km(o,p,g,{assetPlayerId:this.hls.config.assetPlayerId},"hlsjs.interstitial.asset"),v&&(v.id=s,this.id3Track||(this.id3Track=this.createTrack(this.media)),this.id3Track.addCue(v),v.addEventListener("enter",this.onEventCueEnter)))}if(!e.hasProgramDateTime)return;let{id3Track:l}=this,{dateRanges:d}=e,u=Object.keys(d),c=this.dateRangeCuesAppended;if(l&&t){var h;if((h=l.cues)!=null&&h.length){let p=Object.keys(c).filter(g=>!u.includes(g));for(let g=p.length;g--;){var f;let v=p[g],T=(f=c[v])==null?void 0:f.cues;delete c[v],T&&Object.keys(T).forEach(y=>{let b=T[y];if(b){b.removeEventListener("enter",this.onEventCueEnter);try{l.removeCue(b)}catch{}}})}}else c=this.dateRangeCuesAppended={}}let m=e.fragments[e.fragments.length-1];if(!(u.length===0||!Q(m==null?void 0:m.programDateTime))){this.id3Track||(this.id3Track=this.createTrack(this.media));for(let p=0;p<u.length;p++){let g=u[p],v=d[g],T=v.startTime,y=c[g],b=(y==null?void 0:y.cues)||{},A=(y==null?void 0:y.durationKnown)||!1,R=tu,{duration:I,endDate:x}=v;if(x&&I!==null)R=T+I,A=!0;else if(v.endOnNext&&!A){let S=u.reduce((C,P)=>{if(P!==v.id){let N=d[P];if(N.class===v.class&&N.startDate>v.startDate&&(!C||v.startDate<C.startDate))return N}return C},null);S&&(R=S.startTime,A=!0)}let D=Object.keys(v.attr);for(let S=0;S<D.length;S++){let C=D[S];if(!Dx(C))continue;let P=b[C];if(P)A&&!(y!=null&&y.durationKnown)?P.endTime=R:Math.abs(P.startTime-T)>.01&&(P.startTime=T,P.endTime=R);else if(o){let N=v.attr[C];Cx(C)&&(N=Zy(N));let H=km(o,T,R,{key:C,data:N},oi.dateRange);H&&(H.id=g,this.id3Track.addCue(H),b[C]=H,a&&(C==="X-ASSET-LIST"||C==="X-ASSET-URL")&&H.addEventListener("enter",this.onEventCueEnter))}}c[g]={cues:b,dateRange:v,durationKnown:A}}}}},Wp=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,s=this.levelDetails;if(!t||!s)return;this.currentTime=t.currentTime;let r=this.computeLatency();if(r===null)return;this._latency=r;let{lowLatencyMode:n,maxLiveSyncPlaybackRate:a}=this.config;if(!n||a===1||!s.live)return;let o=this.targetLatency;if(o===null)return;let l=r-o,d=Math.min(this.maxLatency,o+s.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:s,targetduration:r}=e,{liveSyncDuration:n,liveSyncDurationCount:a,lowLatencyMode:o}=this.config,l=this.hls.userConfig,d=o&&s||t;(this._targetLatencyUpdated||l.liveSyncDuration||l.liveSyncDurationCount||d===0)&&(d=n!==void 0?n:a*r);let u=r;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 s=this.levelDetails;if(s===null)return null;let r=s.edge,n=e-t-this.edgeStalled,a=r-s.totalduration,o=r-(this.config.lowLatencyMode&&s.partTarget||s.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 s=e.buffered.length;return(s?e.buffered.end(s-1):t.edge)-this.currentTime}destroy(){this.unregisterListeners(),this.onMediaDetaching(),this.hls=null}registerListeners(){let{hls:e}=this;e&&(e.on(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(E.ERROR,this.onError,this))}unregisterListeners(){let{hls:e}=this;e&&(e.off(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(E.ERROR,this.onError,this))}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener("timeupdate",this.onTimeupdate)}onMediaDetaching(){this.media&&(this.media.removeEventListener("timeupdate",this.onTimeupdate),this.media=null)}onManifestLoading(){this._latency=null,this.stallCount=0}onLevelUpdated(e,{details:t}){t.advanced&&this.onTimeupdate(),!t.live&&this.media&&this.media.removeEventListener("timeupdate",this.onTimeupdate)}onError(e,t){var s;t.details===M.BUFFER_STALLED_ERROR&&(this.stallCount++,this.hls&&(s=this.levelDetails)!=null&&s.live&&this.hls.logger.warn("[latency-controller]: Stall detected, adjusting target latency"))}changeMediaPlaybackRate(e,t){var s,r;e.playbackRate!==t&&((s=this.hls)==null||s.logger.debug(`[latency-controller]: latency=${this.latency.toFixed(3)}, targetLatency=${(r=this.targetLatency)==null?void 0:r.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}},qp=class extends jo{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(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(E.LEVEL_LOADED,this.onLevelLoaded,this),e.on(E.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(E.FRAG_BUFFERED,this.onFragBuffered,this),e.on(E.ERROR,this.onError,this)}_unregisterListeners(){let{hls:e}=this;e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(E.LEVEL_LOADED,this.onLevelLoaded,this),e.off(E.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(E.FRAG_BUFFERED,this.onFragBuffered,this),e.off(E.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 s=this.hls.config.preferManagedMediaSource,r=[],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=cu(h,s)||void 0),f&&(f=u.videoCodec=ex(f));let{width:m,height:p,unknownCodecs:g}=u,v=(g==null?void 0:g.length)||0;if(o||(o=!!(m&&p)),l||(l=!!f),d||(d=!!h),v||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":A,RESOLUTION:R,"VIDEO-RANGE":I}=c,D=`${`${A||"."}-`}${u.bitrate}-${R}-${y}-${T}-${I}-${b}`;if(n[D])if(n[D].uri!==u.url&&!u.attrs["PATHWAY-ID"]){let S=a[D]+=1;u.attrs["PATHWAY-ID"]=new Array(S+1).join(".");let C=this.createLevel(u);n[D]=C,r.push(C)}else n[D].addGroupId("audio",c.AUDIO),n[D].addGroupId("text",c.SUBTITLES);else{let S=this.createLevel(u);n[D]=S,a[D]=1,r.push(S)}}),this.filterAndSortMediaOptions(r,t,o,l,d)}createLevel(e){let t=new tn(e),s=e.supplemental;if(s!=null&&s.videoCodec&&!this.isVideoSupported(s.videoCodec)){let r=new Error(`SUPPLEMENTAL-CODECS not supported "${s.videoCodec}"`);this.log(r.message),t.supportedResult=dT(r,[])}return t}isAudioSupported(e){return Bo(e,"audio",this.hls.config.preferManagedMediaSource)}isVideoSupported(e){return Bo(e,"video",this.hls.config.preferManagedMediaSource)}filterAndSortMediaOptions(e,t,s,r,n){var a;let o=[],l=[],d=e,u=((a=t.stats)==null?void 0:a.parsing)||{};if((s||r)&&n&&(d=d.filter(({videoCodec:T,videoRange:y,width:b,height:A})=>(!!T||!!(b&&A))&&ux(y))),d.length===0){Promise.resolve().then(()=>{if(this.hls){let T="no level with compatible codecs found in manifest",y=T;t.levels.length&&(y=`one or more CODECS in variant not supported: ${qe(t.levels.map(A=>A.attrs.CODECS).filter((A,R,I)=>I.indexOf(A)===R))}`,this.warn(y),T+=` (${y})`);let b=new Error(T);this.hls.trigger(E.ERROR,{type:se.MEDIA_ERROR,details:M.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:t.url,error:b,reason:y})}}),u.end=performance.now();return}t.audioTracks&&(o=t.audioTracks.filter(T=>!T.audioCodec||this.isAudioSupported(T.audioCodec)),zy(o)),t.subtitles&&(l=t.subtitles,zy(l));let c=d.slice(0);d.sort((T,y)=>{if(T.attrs["HDCP-LEVEL"]!==y.attrs["HDCP-LEVEL"])return(T.attrs["HDCP-LEVEL"]||"")>(y.attrs["HDCP-LEVEL"]||"")?1:-1;if(s&&T.height!==y.height)return T.height-y.height;if(T.frameRate!==y.frameRate)return T.frameRate-y.frameRate;if(T.videoRange!==y.videoRange)return hu.indexOf(T.videoRange)-hu.indexOf(y.videoRange);if(T.videoCodec!==y.videoCodec){let b=WE(T.videoCodec),A=WE(y.videoCodec);if(b!==A)return A-b}if(T.uri===y.uri&&T.codecSet!==y.codecSet){let b=uu(T.codecSet),A=uu(y.codecSet);if(b!==A)return A-b}return T.averageBitrate!==y.averageBitrate?T.averageBitrate-y.averageBitrate:0});let h=c[0];if(this.steering&&(d=this.steering.filterParsedLevels(d),d.length!==c.length)){for(let T=0;T<c.length;T++)if(c[T].pathwayId===d[0].pathwayId){h=c[T];break}}this._levels=d;for(let T=0;T<d.length;T++)if(d[T]===h){var f;this._firstLevel=T;let y=h.bitrate,b=this.hls.bandwidthEstimate;if(this.log(`manifest loaded, ${d.length} level(s) found, first bitrate: ${y}`),((f=this.hls.userConfig)==null?void 0:f.abrEwmaDefaultEstimate)===void 0){let A=Math.min(y,this.hls.config.abrEwmaDefaultEstimateMax);A>b&&b===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=A)}break}let m=n&&!r,p=this.hls.config,g=!!(p.audioStreamController&&p.audioTrackController),v={levels:d,audioTracks:o,subtitleTracks:l,sessionData:t.sessionData,sessionKeys:t.sessionKeys,firstLevel:this._firstLevel,stats:t.stats,audio:n,video:r,altAudio:g&&!m&&o.some(T=>!!T.url)};u.end=performance.now(),this.hls.trigger(E.MANIFEST_PARSED,v)}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(E.ERROR,{type:se.OTHER_ERROR,details:M.LEVEL_SWITCH_ERROR,level:e,fatal:c,error:u,reason:u.message}),c)return;e=Math.min(e,t.length-1)}let s=this.currentLevelIndex,r=this.currentLevel,n=r?r.attrs["PATHWAY-ID"]:void 0,a=t[e],o=a.attrs["PATHWAY-ID"];if(this.currentLevelIndex=e,this.currentLevel=a,s===e&&r&&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 ${s}${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(E.LEVEL_SWITCHING,l);let d=a.details;if(!d||d.live){let u=this.switchParams(a.uri,r==null?void 0:r.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(),s=e.filter(r=>t.indexOf(r)!==-1);if(e.length<1){this.warn(`pathwayPriority ${e} should contain at least one pathway from list: ${t}`);return}this.steering.pathwayPriority=s}}onError(e,t){t.fatal||!t.context||t.context.type===Le.LEVEL&&t.context.level===this.level&&this.checkRetry(t)}onFragBuffered(e,{frag:t}){if(t!==void 0&&t.type===J.MAIN){let s=t.elementaryStreams;if(!Object.keys(s).some(n=>!!s[n]))return;let r=this._levels[t.level];r!=null&&r.loadError&&(this.log(`Resetting level error count of ${r.loadError} on frag buffered`),r.loadError=0)}}onLevelLoaded(e,t){var s;let{level:r,details:n}=t,a=t.levelInfo;if(!a){var o;this.warn(`Invalid level index ${r}`),(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(r,t,l)}else(s=t.deliveryDirectives)!=null&&s.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 s=this.getUrlWithDirectives(e.uri,t),r=this.currentLevelIndex,n=e.attrs["PATHWAY-ID"],a=e.details,o=a==null?void 0:a.age;this.log(`Loading level index ${r}${(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||""):""} ${s}`),this.hls.trigger(E.LEVEL_LOADING,{url:s,level:r,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 s=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));xT(s),this._levels=s,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 r=s.length-1;this._firstLevel=Math.min(this._firstLevel,r),this._startLevel&&(this._startLevel=Math.min(this._startLevel,r)),this.hls.trigger(E.LEVELS_UPDATED,{levels:s})}onLevelsUpdated(e,{levels:t}){this._levels=t}checkMaxAutoUpdated(){let{autoLevelCapping:e,maxAutoLevel:t,maxHdcpLevel:s}=this.hls;this._maxAutoLevel!==t&&(this._maxAutoLevel=t,this.hls.trigger(E.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:e,levels:this.levels,maxAutoLevel:t,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:s}))}};function zy(i){let e={};i.forEach(t=>{let s=t.groupId||"";t.id=e[s]=e[s]||0,e[s]++})}function vb(){return self.SourceBuffer||self.WebKitSourceBuffer}function Eb(){if(!nr())return!1;let e=vb();return!e||e.prototype&&typeof e.prototype.appendBuffer=="function"&&typeof e.prototype.remove=="function"}function LC(){if(!Eb())return!1;let i=nr();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($o(e,"video")))||["mp4a.40.2","fLaC"].some(e=>i.isTypeSupported($o(e,"audio"))))}function RC(){var i;let e=vb();return typeof(e==null||(i=e.prototype)==null?void 0:i.changeType)=="function"}var xC=100,Yp=class extends Ko{constructor(e,t,s){super(e,t,s,"stream-controller",J.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 r=this.media,n=r?r.currentTime:null;if(n===null||!Q(n)||(this.log(`Media seeked to ${n.toFixed(3)}`),!this.getBufferedFrag(n)))return;let a=this.getFwdBufferInfoAtPos(r,n,J.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(E.MANIFEST_PARSED,this.onManifestParsed,this),e.on(E.LEVEL_LOADING,this.onLevelLoading,this),e.on(E.LEVEL_LOADED,this.onLevelLoaded,this),e.on(E.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.on(E.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(E.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.on(E.BUFFER_CREATED,this.onBufferCreated,this),e.on(E.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(E.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(E.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){super.unregisterListeners();let{hls:e}=this;e.off(E.MANIFEST_PARSED,this.onManifestParsed,this),e.off(E.LEVEL_LOADED,this.onLevelLoaded,this),e.off(E.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.off(E.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(E.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.off(E.BUFFER_CREATED,this.onBufferCreated,this),e.off(E.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(E.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(E.FRAG_BUFFERED,this.onFragBuffered,this)}onHandlerDestroying(){this.onMediaPlaying=this.onMediaSeeked=null,this.unregisterListeners(),super.onHandlerDestroying()}startLoad(e,t){if(this.levels){let{lastCurrentTime:s,hls:r}=this;if(this.stopLoad(),this.setInterval(xC),this.level=-1,!this.startFragRequested){let n=r.startLevel;n===-1&&(r.config.testBandwidth&&this.levels.length>1?(n=0,this.bitrateTest=!0):n=r.firstAutoLevel),r.nextLoadLevel=n,this.level=r.loadLevel,this._hasEnoughToStart=!!t}s>0&&e===-1&&!t&&(this.log(`Override startPosition with lastCurrentTime @${s.toFixed(3)}`),e=s),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:e,level:t}=this,s=e==null?void 0:e[t],r=s==null?void 0:s.details;if(r&&(!r.live||this.levelLastLoaded===s&&!this.waitForLive(s))){if(this.waitForCdnTuneIn(r))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:this.checkRetryDate();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:s,media:r}=this;if(t===null||!r&&!this.primaryPrefetch&&(this.startFragRequested||!e.config.startFragPrefetch)||this.altAudio&&this.audioOnly)return;let n=this.buffering?e.nextLoadLevel:e.loadLevel;if(!(s!=null&&s[n]))return;let a=s[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(E.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&&at(f)&&this.fragmentTracker.getState(f)!==bt.OK){var m;let g=((m=this.backtrackFragment)!=null?m:f).sn-d.startSN,v=d.fragments[g-1];v&&f.cc===v.cc&&(f=v,this.fragmentTracker.removeFragment(v))}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,v=(g===We.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;v&&this.afterBufferFlushed(v,g,J.MAIN)}f=this.getNextFragmentLoopLoading(f,d,o,J.MAIN,c)}f&&(f.initSegment&&!f.initSegment.data&&!this.bitrateTest&&(f=f.initSegment),this.loadFragment(f,a,h))}loadFragment(e,t,s){let r=this.fragmentTracker.getState(e);r===bt.NOT_LOADED||r===bt.PARTIAL?at(e)?this.bitrateTest?(this.log(`Fragment ${e.sn} of level ${e.level} is being downloaded to test bitrate and will not be buffered`),this._loadBitrateTestFrag(e,t)):super.loadFragment(e,t,s):this._loadInitSegment(e,t):this.clearTrackerIfNeeded(e)}getBufferedFrag(e){return this.fragmentTracker.getBufferedFrag(e,J.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 s,r=this.getAppendedFrag(t.currentTime);r&&r.start>1&&this.flushMainBuffer(0,r.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?s=this.fragCurrent.duration*l.maxBitrate/(1e3*d)+1:s=0}else s=0;let a=this.getBufferedFrag(t.currentTime+s);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 s=t.media;Ht(s,"playing",this.onMediaPlaying),Ht(s,"seeked",this.onMediaSeeked)}onMediaDetaching(e,t){let{media:s}=this;s&&(zt(s,"playing",this.onMediaPlaying),zt(s,"seeked",this.onMediaSeeked)),this.videoBuffer=null,this.fragPlaying=null,super.onMediaDetaching(e,t),!t.transferMedia&&(this._hasEnoughToStart=!1)}onManifestLoading(){super.onManifestLoading(),this.log("Trigger BUFFER_RESET"),this.hls.trigger(E.BUFFER_RESET,void 0),this.couldBacktrack=!1,this.fragLastKbps=0,this.fragPlaying=this.backtrackFragment=null,this.altAudio=0,this.audioOnly=!1}onManifestParsed(e,t){let s=!1,r=!1;for(let n=0;n<t.levels.length;n++){let a=t.levels[n].audioCodec;a&&(s=s||a.indexOf("mp4a.40.2")!==-1,r=r||a.indexOf("mp4a.40.5")!==-1)}this.audioCodecSwitch=s&&r&&!RC(),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:s}=this;if(!s||this.state!==O.IDLE)return;let r=t.levelInfo;(!r.details||r.details.live&&(this.levelLastLoaded!==r||r.details.expired)||this.waitForCdnTuneIn(r.details))&&(this.state=O.WAITING_LEVEL)}onLevelLoaded(e,t){var s;let{levels:r,startFragRequested:n}=this,a=t.level,o=t.details,l=o.totalduration;if(!r){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||(s=d.details)!=null&&s.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(E.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:s}=this;if(!s)return;let r=this.hls.liveSyncPosition,n=this.getLoadPosition(),a=e.fragmentStart,o=e.edge,l=n>=a-t.maxFragLookUpTolerance&&n<=o;if(r!==null&&s.duration>r&&(n<r||!l)){let u=t.liveMaxLatencyDuration!==void 0?t.liveMaxLatencyDuration:t.liveMaxLatencyDurationCount*e.targetduration;if((!l&&s.readyState<4||n<o-u)&&(this._hasEnoughToStart||(this.nextLoadPosition=r),s.readyState))if(this.warn(`Playback: ${n.toFixed(3)} is located too far from the end of live sliding playlist: ${o}, reset currentTime to : ${r.toFixed(3)}`),this.config.liveSyncMode==="buffered"){var d;let c=Ee.bufferInfo(s,r,0);if(!((d=c.buffered)!=null&&d.length)){s.currentTime=r;return}if(c.start<=n){s.currentTime=r;return}let{nextStart:f}=Ee.bufferedInfo(c.buffered,n,0);f&&(s.currentTime=f)}else s.currentTime=r}}_handleFragmentLoadProgress(e){var t;let s=e.frag,{part:r,payload:n}=e,{levels:a}=this;if(!a){this.warn(`Levels were reset while fragment load was in progress. Fragment ${s.sn} of level ${s.level} will not be buffered`);return}let o=a[s.level];if(!o){this.warn(`Level ${s.level} not found on progress`);return}let l=o.details;if(!l){this.warn(`Dropping fragment ${s.sn} of level ${s.level} after level details were reset`),this.fragmentTracker.removeFragment(s);return}let d=o.videoCodec,u=l.PTSKnown||!l.live,c=(t=s.initSegment)==null?void 0:t.data,h=this._getAudioCodec(o),f=this.transmuxer=this.transmuxer||new Lu(this.hls,J.MAIN,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),m=r?r.index:-1,p=m!==-1,g=new Go(s.level,s.sn,s.stats.chunkCount,n.byteLength,m,p),v=this.initPTS[s.cc];f.push(n,c,h,d,s,r,l.totalduration,u,g,v)}onAudioTrackSwitching(e,t){let s=this.hls,r=this.altAudio!==0;if(mu(t.url,s))this.altAudio=1;else{if(this.mediaBuffer!==this.media){this.log("Switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;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(r){this.altAudio=0,this.fragmentTracker.removeAllFragments(),s.once(E.BUFFER_FLUSHED,()=>{this.hls&&this.hls.trigger(E.AUDIO_TRACK_SWITCHED,t)}),s.trigger(E.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null});return}s.trigger(E.AUDIO_TRACK_SWITCHED,t)}}onAudioTrackSwitched(e,t){let s=mu(t.url,this.hls);if(s){let r=this.videoBuffer;r&&this.mediaBuffer!==r&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=r)}this.altAudio=s?2:0,this.tick()}onBufferCreated(e,t){let s=t.tracks,r,n,a=!1;for(let o in s){let l=s[o];if(l.id==="main"){if(n=o,r=l,o==="video"){let d=s[o];d&&(this.videoBuffer=d.buffer)}}else a=!0}a&&r?(this.log(`Alternate track found, use ${n}.buffered to schedule main fragment loading`),this.mediaBuffer=r.buffer):this.mediaBuffer=this.media}onFragBuffered(e,t){let{frag:s,part:r}=t,n=s.type===J.MAIN;if(n){if(this.fragContextChanged(s)){this.warn(`Fragment ${s.sn}${r?" p: "+r.index:""} of level ${s.level} finished buffering, but was aborted. state: ${this.state}`),this.state===O.PARSED&&(this.state=O.IDLE);return}let o=r?r.stats:s.stats;this.fragLastKbps=Math.round(8*o.total/(o.buffering.end-o.loading.first)),at(s)&&(this.fragPrevious=s),this.fragBufferedComplete(s,r)}let a=this.media;a&&(!this._hasEnoughToStart&&Ee.getBuffered(a).length&&(this._hasEnoughToStart=!0,this.seekToStartPos()),n&&this.tick())}get hasEnoughToStart(){return this._hasEnoughToStart}onError(e,t){var s;if(t.fatal){this.state=O.ERROR;return}switch(t.details){case M.FRAG_GAP:case M.FRAG_PARSING_ERROR:case M.FRAG_DECRYPT_ERROR:case M.FRAG_LOAD_ERROR:case M.FRAG_LOAD_TIMEOUT:case M.KEY_LOAD_ERROR:case M.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(J.MAIN,t);break;case M.LEVEL_LOAD_ERROR:case M.LEVEL_LOAD_TIMEOUT:case M.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===O.WAITING_LEVEL&&((s=t.context)==null?void 0:s.type)===Le.LEVEL&&(this.state=O.IDLE);break;case M.BUFFER_ADD_CODEC_ERROR:case M.BUFFER_APPEND_ERROR:if(t.parent!=="main")return;this.reduceLengthAndFlushBuffer(t)&&this.resetLoadingState();break;case M.BUFFER_FULL_ERROR:if(t.parent!=="main")return;this.reduceLengthAndFlushBuffer(t)&&(!this.config.interstitialsController&&this.config.assetPlayerId?this._hasEnoughToStart=!0:this.flushMainBuffer(0,Number.POSITIVE_INFINITY));break;case M.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 s=(t===We.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;s&&(this.afterBufferFlushed(s,t,J.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,s=this.startPosition;if(s>=0&&t<s){if(e.seeking){this.log(`could not seek to ${s}, already seeking at ${t}`);return}let r=this.timelineOffset;r&&s&&(s+=r);let n=this.getLevelDetails(),a=Ee.getBuffered(e),o=a.length?a.start(0):0,l=o-s,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`),s+=l,this.startPosition=s),t<s&&(this.log(`seek to target start position ${s} from current time ${t} buffer start ${o}`),e.currentTime=s)}}_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(s=>{let{hls:r}=this,n=s==null?void 0:s.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(),r.trigger(E.FRAG_LOADED,s),n.bitrateTest=!1}).catch(s=>{this.state===O.STOPPED||this.state===O.ERROR||(this.warn(s),this.resetFragmentLoading(e))})}_handleTransmuxComplete(e){let t=this.playlistType,{hls:s}=this,{remuxResult:r,chunkMeta:n}=e,a=this.getCurrentContext(n);if(!a){this.resetWhenMissingContext(n);return}let{frag:o,part:l,level:d}=a,{video:u,text:c,id3:h,initSegment:f}=r,{details:m}=d,p=this.altAudio?void 0:r.audio;if(this.fragContextChanged(o)){this.fragmentTracker.removeFragment(o);return}if(this.state=O.PARSING,f){let g=f.tracks;if(g){let b=o.initSegment||o;if(this.unhandledEncryptionError(f,o))return;this._bufferInitSegment(d,g,b,n),s.trigger(E.FRAG_PARSING_INIT_SEGMENT,{frag:b,id:t,tracks:g})}let v=f.initPTS,T=f.timescale,y=this.initPTS[o.cc];if(Q(v)&&(!y||y.baseTime!==v||y.timescale!==T)){let b=f.trackId;this.initPTS[o.cc]={baseTime:v,timescale:T,trackId:b},s.trigger(E.INIT_PTS_FOUND,{frag:o,id:t,initPTS:v,timescale:T,trackId:b})}}if(u&&m){p&&u.type==="audiovideo"&&this.logMuxedErr(o);let g=m.fragments[o.sn-1-m.startSN],v=o.sn===m.startSN,T=!g||o.cc>g.cc;if(r.independent!==!1){let{startPTS:y,endPTS:b,startDTS:A,endDTS:R}=u;if(l)l.elementaryStreams[u.type]={startPTS:y,endPTS:b,startDTS:A,endDTS:R};else if(u.firstKeyFrame&&u.independent&&n.id===1&&!T&&(this.couldBacktrack=!0),u.dropped&&u.independent){let I=this.getMainFwdBufferInfo(),x=(I?I.end:this.getLoadPosition())+this.config.maxBufferHole,D=u.firstKeyFramePTS?u.firstKeyFramePTS:y;if(!v&&x<D-this.config.maxBufferHole&&!T){this.backtrack(o);return}else T&&(o.gap=!0);o.setElementaryStreamInfo(u.type,o.start,b,o.start,R,!0)}else v&&y-(m.appliedTimelineOffset||0)>lu&&(o.gap=!0);o.setElementaryStreamInfo(u.type,y,b,A,R),this.backtrackFragment&&(this.backtrackFragment=o),this.bufferFragmentData(u,o,l,n,v||T)}else if(v||T)o.gap=!0;else{this.backtrack(o);return}}if(p){let{startPTS:g,endPTS:v,startDTS:T,endDTS:y}=p;l&&(l.elementaryStreams[We.AUDIO]={startPTS:g,endPTS:v,startDTS:T,endDTS:y}),o.setElementaryStreamInfo(We.AUDIO,g,v,T,y),this.bufferFragmentData(p,o,l,n)}if(m&&h!=null&&h.samples.length){let g={id:t,frag:o,details:m,samples:h.samples};s.trigger(E.FRAG_PARSING_METADATA,g)}if(m&&c){let g={id:t,frag:o,details:m,samples:c.samples};s.trigger(E.FRAG_PARSING_USERDATA,g)}}logMuxedErr(e){this.warn(`${at(e)?"Media":"Init"} segment with muxed audiovideo where only video expected: ${e.url}`)}_bufferInitSegment(e,t,s,r){if(this.state!==O.PARSING)return;this.audioOnly=!!t.audio&&!t.video,this.altAudio&&!this.audioOnly&&(delete t.audio,t.audiovideo&&this.logMuxedErr(s));let{audio:n,video:a,audiovideo:o}=t;if(n){let d=e.audioCodec,u=iu(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=J.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=J.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(E.BUFFER_CODECS,t),!this.hls)return;l.forEach(d=>{let c=t[d].initSegment;c!=null&&c.byteLength&&this.hls.trigger(E.BUFFER_APPENDING,{type:d,data:c,frag:s,part:null,chunkMeta:r,parent:s.type})})}this.tickImmediate()}getMainFwdBufferInfo(){let e=this.mediaBuffer&&this.altAudio===2?this.mediaBuffer:this.media;return this.getFwdBufferInfo(e,J.MAIN)}get maxBufferLength(){let{levels:e,level:t}=this,s=e==null?void 0:e[t];return s?this.getMaxBufferLength(s.maxBitrate):this.config.maxBufferLength}backtrack(e){this.couldBacktrack=!0,this.backtrackFragment=e,this.resetTransmuxer(),this.flushBufferGap(e),this.fragmentTracker.removeFragment(e),this.fragPrevious=null,this.nextLoadPosition=e.start,this.state=O.IDLE}checkFragmentChanged(){let e=this.media,t=null;if(e&&e.readyState>1&&e.seeking===!1){let s=e.currentTime;if(Ee.isBuffered(e,s)?t=this.getAppendedFrag(s):Ee.isBuffered(e,s+.1)&&(t=this.getAppendedFrag(s+.1)),t){this.backtrackFragment=null;let r=this.fragPlaying,n=t.level;(!r||t.sn!==r.sn||r.level!==n)&&(this.fragPlaying=t,this.hls.trigger(E.FRAG_CHANGED,{frag:t}),(!r||r.level!==n)&&this.hls.trigger(E.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 Q(t)?this.getAppendedFrag(t):null}get currentProgramDateTime(){var e;let t=((e=this.media)==null?void 0:e.currentTime)||this.lastCurrentTime;if(Q(t)){let s=this.getLevelDetails(),r=this.currentFrag||(s?sn(null,s.fragments,t):null);if(r){let n=r.programDateTime;if(n!==null){let a=n+(t-r.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}},jp=class extends Qt{constructor(e,t){super("key-loader",t),this.config=void 0,this.keyIdToKeyInfo={},this.emeController=null,this.config=e}abort(e){for(let s in this.keyIdToKeyInfo){let r=this.keyIdToKeyInfo[s].loader;if(r){var t;if(e&&e!==((t=r.context)==null?void 0:t.frag.type))return;r.abort()}}}detach(){for(let e in this.keyIdToKeyInfo){let t=this.keyIdToKeyInfo[e];(t.mediaKeySessionContext||t.decryptdata.isCommonEncryption)&&delete this.keyIdToKeyInfo[e]}}destroy(){this.detach();for(let e in this.keyIdToKeyInfo){let t=this.keyIdToKeyInfo[e].loader;t&&t.destroy()}this.keyIdToKeyInfo={}}createKeyLoadError(e,t=M.KEY_LOAD_ERROR,s,r,n){return new Mi({type:se.NETWORK_ERROR,details:t,fatal:!1,frag:e,response:n,error:s,networkDetails:r})}loadClear(e,t,s){if(this.emeController&&this.config.emeEnabled&&!this.emeController.getSelectedKeySystemFormats().length){if(t.length)for(let r=0,n=t.length;r<n;r++){let a=t[r];if(e.cc<=a.cc&&(!at(e)||!at(a)||e.sn<a.sn)||!s&&r==n-1)return this.emeController.selectKeySystemFormat(a).then(o=>{if(!this.emeController)return;a.setKeyFormat(o);let l=ru(o);if(l)return this.emeController.getKeySystemAccess([l])})}if(this.config.requireKeySystemAccessOnStart){let r=Mo(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 s,r;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 (emeEnabled with controller: ${this.emeController&&this.config.emeEnabled})`);return Promise.reject(this.createKeyLoadError(e,M.KEY_LOAD_ERROR,d))}let a=n.uri;if(!a)return Promise.reject(this.createKeyLoadError(e,M.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${a}"`)));let o=Dm(n),l=this.keyIdToKeyInfo[o];if((s=l)!=null&&s.decryptdata.key)return n.key=l.decryptdata.key,Promise.resolve({frag:e,keyInfo:l});if(this.emeController&&(r=l)!=null&&r.keyLoadPromise)switch(this.emeController.getKeyStatus(l.decryptdata)){case"usable":case"usable-in-future":return l.keyLoadPromise.then(u=>{let{keyInfo:c}=u;return n.key=c.decryptdata.key,{frag:e,keyInfo:c}})}switch(this.log(`${this.keyIdToKeyInfo[o]?"Rel":"L"}oading${n.keyId?" keyId: "+Dt(n.keyId):""} URI: ${n.uri} from ${e.type} ${e.level}`),l=this.keyIdToKeyInfo[o]={decryptdata:n,keyLoadPromise:null,loader:null,mediaKeySessionContext:null},n.method){case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return n.keyFormat==="identity"?this.loadKeyHTTP(l,e):this.loadKeyEME(l,e);case"AES-128":case"AES-256":case"AES-256-CTR":return this.loadKeyHTTP(l,e);default:return Promise.reject(this.createKeyLoadError(e,M.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${n.method}"`)))}}loadKeyEME(e,t){let s={frag:t,keyInfo:e};if(this.emeController&&this.config.emeEnabled){var r;if(!e.decryptdata.keyId&&(r=t.initSegment)!=null&&r.data){let a=GR(t.initSegment.data);if(a.length){let o=a[0];o.some(l=>l!==0)?(this.log(`Using keyId found in init segment ${Dt(o)}`),na.setKeyIdForUri(e.decryptdata.uri,o)):(o=na.addKeyIdForUri(e.decryptdata.uri),this.log(`Generating keyId to patch media ${Dt(o)}`)),e.decryptdata.keyId=o}}if(!e.decryptdata.keyId&&!at(t))return Promise.resolve(s);let n=this.emeController.loadKey(s);return(e.keyLoadPromise=n.then(a=>(e.mediaKeySessionContext=a,s))).catch(a=>{throw e.keyLoadPromise=null,"data"in a&&(a.data.frag=t),a})}return Promise.resolve(s)}loadKeyHTTP(e,t){let s=this.config,r=s.loader,n=new r(s);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=s.keyLoadPolicy.default,u={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},c={onSuccess:(h,f,m,p)=>{let{frag:g,keyInfo:v}=m,T=Dm(v.decryptdata);if(!g.decryptdata||v!==this.keyIdToKeyInfo[T])return o(this.createKeyLoadError(g,M.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),p));v.decryptdata.key=g.decryptdata.key=new Uint8Array(h.data),g.keyLoader=null,v.loader=null,a({frag:g,keyInfo:v})},onError:(h,f,m,p)=>{this.resetLoader(f),o(this.createKeyLoadError(t,M.KEY_LOAD_ERROR,new Error(`HTTP Error ${h.code} loading key ${h.text}`),m,Fe({url:l.url,data:void 0},h)))},onTimeout:(h,f,m)=>{this.resetLoader(f),o(this.createKeyLoadError(t,M.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),m))},onAbort:(h,f,m)=>{this.resetLoader(f),o(this.createKeyLoadError(t,M.INTERNAL_ABORTED,new Error("key loading aborted"),m))}};n.load(l,u,c)})}resetLoader(e){let{frag:t,keyInfo:s,url:r}=e,n=s.loader;t.keyLoader===n&&(t.keyLoader=null,s.loader=null);let a=Dm(s.decryptdata)||r;delete this.keyIdToKeyInfo[a],n&&n.destroy()}};function Dm(i){if(i.keyFormat!==Ct.FAIRPLAY){let e=i.keyId;if(e)return Dt(e)}return i.uri}function Qy(i){let{type:e}=i;switch(e){case Le.AUDIO_TRACK:return J.AUDIO;case Le.SUBTITLE_TRACK:return J.SUBTITLE;default:return J.MAIN}}function Cm(i,e){let t=i.url;return(t===void 0||t.indexOf("data:")===0)&&(t=e.url),t}var zp=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(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.LEVEL_LOADING,this.onLevelLoading,this),e.on(E.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.on(E.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.on(E.LEVELS_UPDATED,this.onLevelsUpdated,this)}unregisterListeners(){let{hls:e}=this;e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.LEVEL_LOADING,this.onLevelLoading,this),e.off(E.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.off(E.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.off(E.LEVELS_UPDATED,this.onLevelsUpdated,this)}createInternalLoader(e){let t=this.hls.config,s=t.pLoader,r=t.loader,n=s||r,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:s}=t;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:Le.MANIFEST,url:s,deliveryDirectives:null,levelOrTrack:null})}onLevelLoading(e,t){let{id:s,level:r,pathwayId:n,url:a,deliveryDirectives:o,levelInfo:l}=t;this.load({id:s,level:r,pathwayId:n,responseType:"text",type:Le.LEVEL,url:a,deliveryDirectives:o,levelOrTrack:l})}onAudioTrackLoading(e,t){let{id:s,groupId:r,url:n,deliveryDirectives:a,track:o}=t;this.load({id:s,groupId:r,level:null,responseType:"text",type:Le.AUDIO_TRACK,url:n,deliveryDirectives:a,levelOrTrack:o})}onSubtitleTrackLoading(e,t){let{id:s,groupId:r,url:n,deliveryDirectives:a,track:o}=t;this.load({id:s,groupId:r,level:null,responseType:"text",type:Le.SUBTITLE_TRACK,url:n,deliveryDirectives:a,levelOrTrack:o})}onLevelsUpdated(e,t){let s=this.loaders[Le.LEVEL];if(s){let r=s.context;r&&!t.levels.some(n=>n===r.levelOrTrack)&&(s.abort(),delete this.loaders[Le.LEVEL])}}load(e){var t;let s=this.hls.config,r=this.getInternalLoader(e);if(r){let d=this.hls.logger,u=r.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}`),r.abort()}let n;if(e.type===Le.MANIFEST?n=s.manifestLoadPolicy.default:n=$e({},s.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),r=this.createInternalLoader(e),Q((t=e.deliveryDirectives)==null?void 0:t.part)){let d;if(e.type===Le.LEVEL&&e.level!==null?d=this.hls.levels[e.level].details:e.type===Le.AUDIO_TRACK&&e.id!==null?d=this.hls.audioTracks[e.id].details:e.type===Le.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=$e({},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;u.parsing.start=performance.now(),Zr.isMediaPlaylist(m)||c.type!==Le.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)}};r.load(e,o,l)}checkAutostartLoad(){if(!this.hls)return;let{config:{autoStartLoad:e,startPosition:t},forceStartLoad:s}=this.hls;(e||s)&&(this.hls.logger.log(`${e?"auto":"force"} startLoad with configured startPosition ${t}`),this.hls.startLoad(t))}handleMasterPlaylist(e,t,s,r){let n=this.hls,a=e.data,o=Cm(e,s),l=Zr.parseMasterPlaylist(a,o);if(l.playlistParsingError){t.parsing.end=performance.now(),this.handleManifestParsingError(e,s,l.playlistParsingError,r,t);return}let{contentSteering:d,levels:u,sessionData:c,sessionKeys:h,startTimeOffset:f,variableList:m}=l;this.variableList=m,u.forEach(T=>{let{unknownCodecs:y}=T;if(y){let{preferManagedMediaSource:b}=this.hls.config,{audioCodec:A,videoCodec:R}=T;for(let I=y.length;I--;){let x=y[I];Bo(x,"audio",b)?(T.audioCodec=A=A?`${A},${x}`:x,ra.audio[A.substring(0,4)]=2,y.splice(I,1)):Bo(x,"video",b)&&(T.videoCodec=R=R?`${R},${x}`:x,ra.video[R.substring(0,4)]=2,y.splice(I,1))}}});let{AUDIO:p=[],SUBTITLES:g,"CLOSED-CAPTIONS":v}=Zr.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 tt({}),bitrate:0,url:""})),n.trigger(E.MANIFEST_LOADED,{levels:u,audioTracks:p,subtitles:g,captions:v,contentSteering:d,url:o,stats:t,networkDetails:r,sessionData:c,sessionKeys:h,startTimeOffset:f,variableList:m})}handleTrackOrLevelPlaylist(e,t,s,r,n){let a=this.hls,{id:o,level:l,type:d}=s,u=Cm(e,s),c=Q(l)?l:Q(o)?o:0,h=Qy(s),f=Zr.parseLevelPlaylist(e.data,u,c,h,0,this.variableList);if(d===Le.MANIFEST){let m={attrs:new tt({}),bitrate:0,details:f,name:"",url:u};f.requestScheduled=t.loading.start+IT(f,0),a.trigger(E.MANIFEST_LOADED,{levels:[m],audioTracks:[],url:u,stats:t,networkDetails:r,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}t.parsing.end=performance.now(),s.levelDetails=f,this.handlePlaylistLoaded(f,e,t,s,r,n)}handleManifestParsingError(e,t,s,r,n){this.hls.trigger(E.ERROR,{type:se.NETWORK_ERROR,details:M.MANIFEST_PARSING_ERROR,fatal:t.type===Le.MANIFEST,url:e.url,err:s,error:s,reason:s.message,response:e,context:t,networkDetails:r,stats:n})}handleNetworkError(e,t,s=!1,r,n){let a=`A network ${s?"timeout":"error"+(r?" (status "+r.code+")":"")} occurred while loading ${e.type}`;e.type===Le.LEVEL?a+=`: ${e.level} id: ${e.id}`:(e.type===Le.AUDIO_TRACK||e.type===Le.SUBTITLE_TRACK)&&(a+=` id: ${e.id} group-id: "${e.groupId}"`);let o=new Error(a);this.hls.logger.warn(`[playlist-loader]: ${a}`);let l=M.UNKNOWN,d=!1,u=this.getInternalLoader(e);switch(e.type){case Le.MANIFEST:l=s?M.MANIFEST_LOAD_TIMEOUT:M.MANIFEST_LOAD_ERROR,d=!0;break;case Le.LEVEL:l=s?M.LEVEL_LOAD_TIMEOUT:M.LEVEL_LOAD_ERROR,d=!1;break;case Le.AUDIO_TRACK:l=s?M.AUDIO_TRACK_LOAD_TIMEOUT:M.AUDIO_TRACK_LOAD_ERROR,d=!1;break;case Le.SUBTITLE_TRACK:l=s?M.SUBTITLE_TRACK_LOAD_TIMEOUT:M.SUBTITLE_LOAD_ERROR,d=!1;break}u&&this.resetInternalLoader(e.type);let c={type:se.NETWORK_ERROR,details:l,fatal:d,url:e.url,loader:u,context:e,error:o,networkDetails:t,stats:n};if(r){let h=(t==null?void 0:t.url)||e.url;c.response=Fe({url:h,data:void 0},r)}this.hls.trigger(E.ERROR,c)}handlePlaylistLoaded(e,t,s,r,n,a){let o=this.hls,{type:l,level:d,levelOrTrack:u,id:c,groupId:h,deliveryDirectives:f}=r,m=Cm(t,r),p=Qy(r),g=typeof r.level=="number"&&p===J.MAIN?d:void 0,v=e.playlistParsingError;if(v){if(this.hls.logger.warn(`${v} ${e.url}`),!o.config.ignorePlaylistParsingErrors){o.trigger(E.ERROR,{type:se.NETWORK_ERROR,details:M.LEVEL_PARSING_ERROR,fatal:!1,url:m,error:v,reason:v.message,response:t,context:r,level:g,parent:p,networkDetails:n,stats:s});return}e.playlistParsingError=null}if(!e.fragments.length){let T=e.playlistParsingError=new Error("No Segments found in Playlist");o.trigger(E.ERROR,{type:se.NETWORK_ERROR,details:M.LEVEL_EMPTY_ERROR,fatal:!1,url:m,error:T,reason:T.message,response:t,context:r,level:g,parent:p,networkDetails:n,stats:s});return}switch(e.live&&a&&(a.getCacheAge&&(e.ageHeader=a.getCacheAge()||0),(!a.getCacheAge||isNaN(e.ageHeader))&&(e.ageHeader=0)),l){case Le.MANIFEST:case Le.LEVEL:if(g){if(!u)g=0;else if(u!==o.levels[g]){let T=o.levels.indexOf(u);T>-1&&(g=T)}}o.trigger(E.LEVEL_LOADED,{details:e,levelInfo:u||o.levels[0],level:g||0,id:c||0,stats:s,networkDetails:n,deliveryDirectives:f,withoutMultiVariant:l===Le.MANIFEST});break;case Le.AUDIO_TRACK:o.trigger(E.AUDIO_TRACK_LOADED,{details:e,track:u,id:c||0,groupId:h||"",stats:s,networkDetails:n,deliveryDirectives:f});break;case Le.SUBTITLE_TRACK:o.trigger(E.SUBTITLE_TRACK_LOADED,{details:e,track:u,id:c||0,groupId:h||"",stats:s,networkDetails:n,deliveryDirectives:f});break}}},Xo=class i{static get version(){return Vo}static isMSESupported(){return Eb()}static isSupported(){return LC()}static getMediaSource(){return nr()}static get Events(){return E}static get MetadataSchema(){return oi}static get ErrorTypes(){return se}static get ErrorDetails(){return M}static get DefaultConfig(){return i.defaultConfig?i.defaultConfig:EC}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 sg,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=CR(e.debug||!1,"Hls instance",e.assetPlayerId),s=this.config=TC(i.DefaultConfig,e,t);this.userConfig=e,s.progressive&&bC(s,t);let{abrController:r,bufferController:n,capLevelController:a,errorController:o,fpsController:l}=s,d=new o(this),u=this.abrController=new r(this),c=new Hm(this),h=s.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),v=new zp(this),T=s.contentSteeringController,y=T?new T(this):null,b=this.levelController=new qp(this,y),A=new Vp(this),R=new jp(this.config,this.logger),I=this.streamController=new Yp(this,c,R),x=this.gapController=new Gp(this,c);p.setStreamController(I),g.setStreamController(I);let D=[v,b,I];f&&D.splice(1,0,f),y&&D.splice(1,0,y),this.networkControllers=D;let S=[u,m,x,p,g,A,c];this.audioTrackController=this.createController(s.audioTrackController,D);let C=s.audioStreamController;C&&D.push(this.audioStreamController=new C(this,c,R)),this.subtitleTrackController=this.createController(s.subtitleTrackController,D);let P=s.subtitleStreamController;P&&D.push(this.subtititleStreamController=new P(this,c,R)),this.createController(s.timelineController,S),R.emeController=this.emeController=this.createController(s.emeController,S),this.cmcdController=this.createController(s.cmcdController,S),this.latencyController=this.createController(Wp,S),this.coreComponents=S,D.push(d);let N=d.onErrorOut;typeof N=="function"&&this.on(E.ERROR,N,d),this.on(E.MANIFEST_LOADED,v.onManifestLoaded,v)}createController(e,t){if(e){let s=new e(this);return t&&t.push(s),s}return null}on(e,t,s=this){this._emitter.on(e,t,s)}once(e,t,s=this){this._emitter.once(e,t,s)}removeAllListeners(e){this._emitter.removeAllListeners(e)}off(e,t,s=this,r){this._emitter.off(e,t,s,r)}listeners(e){return this._emitter.listeners(e)}emit(e,t,s){return this._emitter.emit(e,t,s)}trigger(e,t){if(this.config.debug)return this.emit(e,e,t);try{return this.emit(e,e,t)}catch(s){if(this.logger.error("An internal error happened while handling event "+e+'. Error message: "'+s.message+'". Here is a stacktrace:',s),!this.triggeringException){this.triggeringException=!0;let r=e===E.ERROR;this.trigger(E.ERROR,{type:se.OTHER_ERROR,details:M.INTERNAL_EXCEPTION,fatal:r,event:e,error:s}),this.triggeringException=!1}}return!1}listenerCount(e){return this._emitter.listenerCount(e)}destroy(){this.logger.log("destroy"),this.trigger(E.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(E.ERROR,{type:se.OTHER_ERROR,details:M.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,s=t?e.media:e,r=t?e:{media:s};this._media=s,this.trigger(E.MEDIA_ATTACHING,r)}detachMedia(){this.logger.log("detachMedia"),this.trigger(E.MEDIA_DETACHING,{}),this._media=null}transferMedia(){this._media=null;let e=this.bufferController.transferMedia();return this.trigger(E.MEDIA_DETACHING,{transferMedia:e}),e}loadSource(e){this.stopLoad();let t=this.media,s=this._url,r=this._url=Qp.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.logger.log(`loadSource:${r}`),t&&s&&(s!==r||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(t)),this.trigger(E.MANIFEST_LOADING,{url:e})}get url(){return this._url}get hasEnoughToStart(){return this.streamController.hasEnoughToStart}get startPosition(){return this.streamController.startPositionValue}startLoad(e=-1,t){this.logger.log(`startLoad(${e+(t?", <skip seek to start>":"")})`),this.started=!0,this.resumeBuffering();for(let s=0;s<this.networkControllers.length&&(this.networkControllers[s].startLoad(e,t),!(!this.started||!this.networkControllers));s++);}stopLoad(){this.logger.log("stopLoad"),this.started=!1;for(let e=0;e<this.networkControllers.length&&(this.networkControllers[e].stopLoad(),!(this.started||!this.networkControllers));e++);}get loadingEnabled(){return this.started}get bufferingEnabled(){return this.streamController.bufferingEnabled}resumeBuffering(){this.bufferingEnabled||(this.logger.log("resume buffering"),this.networkControllers.forEach(e=>{e.resumeBuffering&&e.resumeBuffering()}))}pauseBuffering(){this.bufferingEnabled&&(this.logger.log("pause buffering"),this.networkControllers.forEach(e=>{e.pauseBuffering&&e.pauseBuffering()}))}get inFlightFragments(){let e={[J.MAIN]:this.streamController.inFlightFrag};return this.audioStreamController&&(e[J.AUDIO]=this.audioStreamController.inFlightFrag),this.subtititleStreamController&&(e[J.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=$D()),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){dx(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 s=e.length;for(let r=0;r<s;r++)if(e[r].maxBitrate>=t)return r;return 0}get maxAutoLevel(){let{levels:e,autoLevelCapping:t,maxHdcpLevel:s}=this,r;if(t===-1&&e!=null&&e.length?r=e.length-1:r=t,s)for(let n=r;n--;){let a=e[n].attrs["HDCP-LEVEL"];if(a&&a<=s)return n}return r}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 s=hT(t);return uT(e,s,navigator.mediaCapabilities)}};Xo.defaultConfig=void 0;var _e=Xo,Ue={VIDEO:"video",THUMBNAIL:"thumbnail",STORYBOARD:"storyboard",DRM:"drm"},ne={NOT_AN_ERROR:0,NETWORK_OFFLINE:2000002,NETWORK_UNKNOWN_ERROR:2e6,NETWORK_NO_STATUS:2000001,NETWORK_INVALID_URL:24e5,NETWORK_NOT_FOUND:2404e3,NETWORK_NOT_READY:2412e3,NETWORK_GENERIC_SERVER_FAIL:25e5,NETWORK_TOKEN_MISSING:2403201,NETWORK_TOKEN_MALFORMED:2412202,NETWORK_TOKEN_EXPIRED:2403210,NETWORK_TOKEN_AUD_MISSING:2403221,NETWORK_TOKEN_AUD_MISMATCH:2403222,NETWORK_TOKEN_SUB_MISMATCH:2403232,ENCRYPTED_ERROR:5e6,ENCRYPTED_UNSUPPORTED_KEY_SYSTEM:5000001,ENCRYPTED_GENERATE_REQUEST_FAILED:5000002,ENCRYPTED_UPDATE_LICENSE_FAILED:5000003,ENCRYPTED_UPDATE_SERVER_CERT_FAILED:5000004,ENCRYPTED_CDM_ERROR:5000005,ENCRYPTED_OUTPUT_RESTRICTED:5000006,ENCRYPTED_MISSING_TOKEN:5000002},tl=i=>i===Ue.VIDEO?"playback":i,or=class Zo extends Error{constructor(e,t=Zo.MEDIA_ERR_CUSTOM,s,r){var n;super(e),this.name="MediaError",this.code=t,this.context=r,this.fatal=s!=null?s:t>=Zo.MEDIA_ERR_NETWORK&&t<=Zo.MEDIA_ERR_ENCRYPTED,this.message||(this.message=(n=Zo.defaultMessages[this.code])!=null?n:"")}};or.MEDIA_ERR_ABORTED=1,or.MEDIA_ERR_NETWORK=2,or.MEDIA_ERR_DECODE=3,or.MEDIA_ERR_SRC_NOT_SUPPORTED=4,or.MEDIA_ERR_ENCRYPTED=5,or.MEDIA_ERR_CUSTOM=100,or.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 z=or,kC=i=>i==null,Sg=(i,e)=>kC(e)?!1:i in e,pg={ANY:"any",MUTED:"muted"},we={ON_DEMAND:"on-demand",LIVE:"live",UNKNOWN:"unknown"},gi={MSE:"mse",NATIVE:"native"},Jo={HEADER:"header",QUERY:"query",NONE:"none"},la=Object.values(Jo),Cs={M3U8:"application/vnd.apple.mpegurl",MP4:"video/mp4"},gg={HLS:Cs.M3U8},IN=Object.keys(gg),LN=[...Object.values(Cs),"hls","HLS"];var DC="en",vg={code:DC},mt=(i,e,t,s,r=i)=>{r.addEventListener(e,t,s),i.addEventListener("teardown",()=>{r.removeEventListener(e,t)},{once:!0})};function CC(i,e,t){e&&t>e&&(t=e);for(let s=0;s<i.length;s++)if(i.start(s)<=t&&i.end(s)>=t)return!0;return!1}var Gu=i=>{let e=i.indexOf("?");if(e<0)return[i];let t=i.slice(0,e),s=i.slice(e);return[t,s]},Ku=i=>{let{type:e}=i;if(e){let t=e.toUpperCase();return Sg(t,gg)?gg[t]:e}return wC(i)},xb=i=>i==="VOD"?we.ON_DEMAND:we.LIVE,kb=i=>i==="EVENT"?Number.POSITIVE_INFINITY:i==="VOD"?Number.NaN:0,wC=i=>{let{src:e}=i;if(!e)return"";let t="";try{t=Ig(e).pathname}catch{console.error("Invalid url when trying to infer mime type",e)}let s=t.lastIndexOf(".");if(s<0)return OC(i)?Cs.M3U8:"";let r=t.slice(s+1).toUpperCase();return Sg(r,Cs)?Cs[r]:""},Eg=i=>{try{return new URL(i),!1}catch{return!0}},MC=i=>i.split(`
|
|
56
|
-
`).find((e,t,s)=>t>0&&s[t-1].startsWith("#EXT-X-STREAM-INF")),Ig=(i,e)=>{var t;if(!Eg(i))return new URL(i);let s=(t=window==null?void 0:window.location)==null?void 0:t.href,r=e!=null?e:s;return e&&Eg(e.toString())&&(r=new URL(e,s)),new URL(i,r)},PC="mux.com",OC=({src:i,customDomain:e=PC})=>{let t;try{t=new URL(`${i}`)}catch{return!1}let s=t.protocol==="https:",r=t.hostname===`stream.${e}`.toLowerCase(),n=t.pathname.split("/"),a=n.length===2,o=!(n!=null&&n[1].includes("."));return s&&r&&a&&o},dr=i=>{let e=(i!=null?i:"").split(".")[1];if(e)try{let t=e.replace(/-/g,"+").replace(/_/g,"/"),s=decodeURIComponent(atob(t).split("").map(function(r){return"%"+("00"+r.charCodeAt(0).toString(16)).slice(-2)}).join(""));return JSON.parse(s)}catch{return}},NC=({exp:i},e=Date.now())=>!i||i*1e3<e,UC=({sub:i},e)=>i!==e,FC=({aud:i},e)=>!i,BC=({aud:i},e)=>i!==e,Db="en";function te(i,e=!0){var t,s;let r=e&&(s=(t=vg)==null?void 0:t[i])!=null?s:i,n=e?vg.code:Db;return new $C(r,n)}var $C=class{constructor(i,e=(t=>(t=vg)!=null?t:Db)()){this.message=i,this.locale=e}format(i){return this.message.replace(/\{(\w+)\}/g,(e,t)=>{var s;return(s=i[t])!=null?s:""})}toString(){return this.message}},HC=Object.values(pg),yb=i=>typeof i=="boolean"||typeof i=="string"&&HC.includes(i),GC=(i,e,t)=>{let{autoplay:s}=i,r=!1,n=!1,a=yb(s)?s:!!s,o=()=>{r||mt(e,"playing",()=>{r=!0},{once:!0})};if(o(),mt(e,"loadstart",()=>{r=!1,o(),fg(e,a)},{once:!0}),mt(e,"loadstart",()=>{t||(i.streamType&&i.streamType!==we.UNKNOWN?n=i.streamType===we.LIVE:n=!Number.isFinite(e.duration)),fg(e,a)},{once:!0}),t&&t.once(_e.Events.LEVEL_LOADED,(l,d)=>{var u;i.streamType&&i.streamType!==we.UNKNOWN?n=i.streamType===we.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&&mt(e,"play",()=>{e.preload==="metadata"?t.once(_e.Events.LEVEL_UPDATED,l):l()},{once:!0})}return l=>{r||(a=yb(l)?l:!!l,fg(e,a))}},fg=(i,e)=>{if(!e)return;let t=i.muted,s=()=>i.muted=t;switch(e){case pg.ANY:i.play().catch(()=>{i.muted=!0,i.play().catch(s)});break;case pg.MUTED:i.muted=!0,i.play().catch(s);break;default:i.play().catch(()=>{});break}},KC=({preload:i,src:e},t,s)=>{let r=c=>{c!=null&&["","none","metadata","auto"].includes(c)?t.setAttribute("preload",c):t.removeAttribute("preload")};if(!s)return r(i),r;let n=!1,a=!1,o=s.config.maxBufferLength,l=s.config.maxBufferSize,d=c=>{r(c);let h=c!=null?c:t.preload;a||h==="none"||(h==="metadata"?(s.config.maxBufferLength=1,s.config.maxBufferSize=1):(s.config.maxBufferLength=o,s.config.maxBufferSize=l),u())},u=()=>{!n&&e&&(n=!0,s.loadSource(e))};return mt(t,"play",()=>{a=!0,s.config.maxBufferLength=o,s.config.maxBufferSize=l,u()},{once:!0}),d(i),d},VC=(i,e,t)=>{let{minPreloadSegments:s}=i;if(s==null||s<=0||!t)return;let r=0,n=!1,a=e.playbackRate||1,o=()=>{e.playbackRate!==0&&(a=e.playbackRate,e.playbackRate=0)};e.playbackRate=0,mt(e,"ratechange",o);let l=(d,{frag:u})=>{n||u.type!=="main"||(r++,r>=s&&(n=!0,e.removeEventListener("ratechange",o),e.playbackRate=a))};t.on(_e.Events.FRAG_BUFFERED,l),e.addEventListener("teardown",()=>{n||(n=!0,t.off(_e.Events.FRAG_BUFFERED,l),e.playbackRate=a)},{once:!0})},WC=(i,e,t)=>{let{initialEstimateSegments:s}=i;if(s==null||s<=0||!t)return;let r=0;t.on(_e.Events.FRAG_BUFFERED,(n,{frag:a})=>{a.type==="main"&&(r++,r<s&&t.abrController.resetEstimator(t.config.abrEwmaDefaultEstimate))})};function qC(i,e){var t;if(!("videoTracks"in i))return;let s=new WeakMap;e.on(_e.Events.MANIFEST_PARSED,function(d,u){l();let c=i.addVideoTrack("main");c.selected=!0;for(let[h,f]of u.levels.entries()){let m=c.addRendition(f.url[0],f.width,f.height,f.videoCodec,f.bitrate);s.set(f,`${h}`),m.id=`${h}`}}),e.on(_e.Events.AUDIO_TRACKS_UPDATED,function(d,u){o();for(let c of u.audioTracks){let h=c.default?"main":"alternative",f=i.addAudioTrack(h,c.name,c.lang);f.id=`${c.id}`,c.default&&(f.enabled=!0)}});let r=()=>{var d;let u=+((d=[...i.audioTracks].find(h=>h.enabled))==null?void 0:d.id),c=e.audioTracks.map(h=>h.id);u!=e.audioTrack&&c.includes(u)&&(e.audioTrack=u)};i.audioTracks.addEventListener("change",r),e.on(_e.Events.LEVELS_UPDATED,function(d,u){var c;let h=i.videoTracks[(c=i.videoTracks.selectedIndex)!=null?c:0];if(!h)return;let f=u.levels.map(m=>s.get(m));for(let m of i.videoRenditions)m.id&&!f.includes(m.id)&&h.removeRendition(m)});let n=d=>{let u=d.target.selectedIndex;u!=e.nextLevel&&(e.nextLevel=u)};(t=i.videoRenditions)==null||t.addEventListener("change",n);let a=()=>{for(let d of i.videoTracks)i.removeVideoTrack(d)},o=()=>{for(let d of i.audioTracks)i.removeAudioTrack(d)},l=()=>{a(),o()};e.once(_e.Events.DESTROYING,()=>{var d,u;l(),(d=i.audioTracks)==null||d.removeEventListener("change",r),(u=i.videoRenditions)==null||u.removeEventListener("change",n)})}var mg=i=>"time"in i?i.time:i.startTime;function YC(i,e){e.on(_e.Events.NON_NATIVE_TEXT_TRACKS_FOUND,(r,{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}`;Vu(i,a.kind,a.label,d==null?void 0:d.lang,c,a.default)})});let t=()=>{if(!e.subtitleTracks.length)return;let r=Array.from(i.textTracks).find(o=>o.id&&o.mode==="showing"&&["subtitles","captions"].includes(o.kind));if(!r)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||(r==null?void 0:r.id)!==a){let o=e.subtitleTracks.findIndex(({lang:l,name:d,type:u,default:c})=>r.id==="default"&&c||l==r.language&&d===r.label&&u.toLowerCase()===r.kind);e.subtitleTrack=o}(r==null?void 0:r.id)===a&&r.cues&&Array.from(r.cues).forEach(o=>{r.addCue(o)})};i.textTracks.addEventListener("change",t),e.on(_e.Events.CUES_PARSED,(r,{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(_e.Events.DESTROYING,()=>{i.textTracks.removeEventListener("change",t),i.querySelectorAll("track[data-removeondestroy]").forEach(r=>{r.remove()})});let s=()=>{Array.from(i.textTracks).forEach(r=>{var n,a;if(!["subtitles","caption"].includes(r.kind)&&(r.label==="thumbnails"||r.kind==="chapters")){if(!((n=r.cues)!=null&&n.length)){let o="track";r.kind&&(o+=`[kind="${r.kind}"]`),r.label&&(o+=`[label="${r.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)}r.mode!=="hidden"&&(r.mode="hidden")}})};e.once(_e.Events.MANIFEST_LOADED,s),e.once(_e.Events.MEDIA_ATTACHED,s)}function Vu(i,e,t,s,r,n){let a=document.createElement("track");return a.kind=e,a.label=t,s&&(a.srclang=s),r&&(a.id=r),n&&(a.default=!0),a.track.mode=["subtitles","captions"].includes(e)?"disabled":"hidden",a.setAttribute("data-removeondestroy",""),i.append(a),a.track}function Cb(i,e){let t=Array.prototype.find.call(i.querySelectorAll("track"),s=>s.track===e);t==null||t.remove()}function il(i,e,t){var s;return(s=Array.from(i.querySelectorAll("track")).find(r=>r.track.label===e&&r.track.kind===t))==null?void 0:s.track}async function wb(i,e,t,s){let r=il(i,t,s);return r||(r=Vu(i,s,t),r.mode="hidden",await new Promise(n=>setTimeout(()=>n(void 0),0))),r.mode!=="hidden"&&(r.mode="hidden"),[...e].sort((n,a)=>mg(a)-mg(n)).forEach(n=>{var a,o;let l=n.value,d=mg(n);if("endTime"in n&&n.endTime!=null)r==null||r.addCue(new VTTCue(d,n.endTime,s==="chapters"?l:JSON.stringify(l!=null?l:null)));else{let u=Array.prototype.findIndex.call(r==null?void 0:r.cues,m=>m.startTime>=d),c=(a=r==null?void 0:r.cues)==null?void 0:a[u],h=c?c.startTime:Number.isFinite(i.duration)?i.duration:Number.MAX_SAFE_INTEGER,f=(o=r==null?void 0:r.cues)==null?void 0:o[u-1];f&&(f.endTime=d),r==null||r.addCue(new VTTCue(d,h,s==="chapters"?l:JSON.stringify(l!=null?l:null)))}}),i.textTracks.dispatchEvent(new Event("change",{bubbles:!0,composed:!0})),r}var Lg="cuepoints",Mb=Object.freeze({label:Lg});async function Rg(i,e,t=Mb){return wb(i,e,t.label,"metadata")}var yg=i=>({time:i.startTime,value:JSON.parse(i.text)});function Pb(i,e={label:Lg}){let t=il(i,e.label,"metadata");return t!=null&&t.cues?Array.from(t.cues,s=>yg(s)):[]}function xg(i,e={label:Lg}){var t,s;let r=il(i,e.label,"metadata");if(!((t=r==null?void 0:r.activeCues)!=null&&t.length))return;if(r.activeCues.length===1)return yg(r.activeCues[0]);let{currentTime:n}=i,a=Array.prototype.find.call((s=r.activeCues)!=null?s:[],({startTime:o,endTime:l})=>o<=n&&l>n);return yg(a||r.activeCues[0])}async function jC(i,e=Mb){return new Promise(t=>{mt(i,"loadstart",async()=>{let s=await Rg(i,[],e);mt(i,"cuechange",()=>{let r=xg(i);if(r){let n=new CustomEvent("cuepointchange",{composed:!0,bubbles:!0,detail:r});i.dispatchEvent(n)}},{},s),t(s)})})}var kg="chapters",Ob=Object.freeze({label:kg}),Tg=i=>({startTime:i.startTime,endTime:i.endTime,value:i.text});async function Dg(i,e,t=Ob){return wb(i,e,t.label,"chapters")}function Nb(i,e={label:kg}){var t;let s=il(i,e.label,"chapters");return(t=s==null?void 0:s.cues)!=null&&t.length?Array.from(s.cues,r=>Tg(r)):[]}function Cg(i,e={label:kg}){var t,s;let r=il(i,e.label,"chapters");if(!((t=r==null?void 0:r.activeCues)!=null&&t.length))return;if(r.activeCues.length===1)return Tg(r.activeCues[0]);let{currentTime:n}=i,a=Array.prototype.find.call((s=r.activeCues)!=null?s:[],({startTime:o,endTime:l})=>o<=n&&l>n);return Tg(a||r.activeCues[0])}async function zC(i,e=Ob){return new Promise(t=>{mt(i,"loadstart",async()=>{let s=await Dg(i,[],e);mt(i,"cuechange",()=>{let r=Cg(i);if(r){let n=new CustomEvent("chapterchange",{composed:!0,bubbles:!0,detail:r});i.dispatchEvent(n)}},{},s),t(s)})})}function Ub(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 Fb(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 oa={VIDEO:"v",THUMBNAIL:"t",STORYBOARD:"s",DRM:"d"},QC=i=>{if(i===Ue.VIDEO)return oa.VIDEO;if(i===Ue.DRM)return oa.DRM},XC=(i,e)=>{var t,s;let r=tl(i),n=`${r}Token`;return(t=e.tokens)!=null&&t[r]?(s=e.tokens)==null?void 0:s[r]:Sg(n,e)?e[n]:void 0},$u=(i,e,t,s,r=!1,n=!(a=>(a=globalThis.navigator)==null?void 0:a.onLine)())=>{var a,o;if(n){let v=te("Your device appears to be offline",r),T,y=z.MEDIA_ERR_NETWORK,b=new z(v,y,!1,T);return b.errorCategory=e,b.muxCode=ne.NETWORK_OFFLINE,b.data=i,b}let l="status"in i?i.status:i.code,d=Date.now(),u=z.MEDIA_ERR_NETWORK;if(l===200)return;let c=tl(e),h=XC(e,t),f=QC(e),[m]=Gu((a=t.playbackId)!=null?a:"");if(!l||!m)return;let p=dr(h);if(h&&!p){let v=te("The {tokenNamePrefix}-token provided is invalid or malformed.",r).format({tokenNamePrefix:c}),T=te("Compact JWT string: {token}",r).format({token:h}),y=new z(v,u,!0,T);return y.errorCategory=e,y.muxCode=ne.NETWORK_TOKEN_MALFORMED,y.data=i,y}if(l>=500){let v=new z("",u,s!=null?s:!0);return v.errorCategory=e,v.muxCode=ne.NETWORK_UNKNOWN_ERROR,v}if(l===403)if(p){if(NC(p,d)){let v={timeStyle:"medium",dateStyle:"medium"},T=te("The video\u2019s secured {tokenNamePrefix}-token has expired.",r).format({tokenNamePrefix:c}),y=te("Expired at: {expiredDate}. Current time: {currentDate}.",r).format({expiredDate:new Intl.DateTimeFormat("en",v).format((o=p.exp)!=null?o:0*1e3),currentDate:new Intl.DateTimeFormat("en",v).format(d)}),b=new z(T,u,!0,y);return b.errorCategory=e,b.muxCode=ne.NETWORK_TOKEN_EXPIRED,b.data=i,b}if(UC(p,m)){let v=te("The video\u2019s playback ID does not match the one encoded in the {tokenNamePrefix}-token.",r).format({tokenNamePrefix:c}),T=te("Specified playback ID: {playbackId} and the playback ID encoded in the {tokenNamePrefix}-token: {tokenPlaybackId}",r).format({tokenNamePrefix:c,playbackId:m,tokenPlaybackId:p.sub}),y=new z(v,u,!0,T);return y.errorCategory=e,y.muxCode=ne.NETWORK_TOKEN_SUB_MISMATCH,y.data=i,y}if(FC(p,f)){let v=te("The {tokenNamePrefix}-token is formatted with incorrect information.",r).format({tokenNamePrefix:c}),T=te("The {tokenNamePrefix}-token has no aud value. aud value should be {expectedAud}.",r).format({tokenNamePrefix:c,expectedAud:f}),y=new z(v,u,!0,T);return y.errorCategory=e,y.muxCode=ne.NETWORK_TOKEN_AUD_MISSING,y.data=i,y}if(BC(p,f)){let v=te("The {tokenNamePrefix}-token is formatted with incorrect information.",r).format({tokenNamePrefix:c}),T=te("The {tokenNamePrefix}-token has an incorrect aud value: {aud}. aud value should be {expectedAud}.",r).format({tokenNamePrefix:c,expectedAud:f,aud:p.aud}),y=new z(v,u,!0,T);return y.errorCategory=e,y.muxCode=ne.NETWORK_TOKEN_AUD_MISMATCH,y.data=i,y}}else{let v=te("Authorization error trying to access this {category} URL. If this is a signed URL, you might need to provide a {tokenNamePrefix}-token.",r).format({tokenNamePrefix:c,category:e}),T=te("Specified playback ID: {playbackId}",r).format({playbackId:m}),y=new z(v,u,s!=null?s:!0,T);return y.errorCategory=e,y.muxCode=ne.NETWORK_TOKEN_MISSING,y.data=i,y}if(l===412){let v=te("This playback-id may belong to a live stream that is not currently active or an asset that is not ready.",r),T=te("Specified playback ID: {playbackId}",r).format({playbackId:m}),y=new z(v,u,s!=null?s:!0,T);return y.errorCategory=e,y.muxCode=ne.NETWORK_NOT_READY,y.streamType=t.streamType===we.LIVE?"live":t.streamType===we.ON_DEMAND?"on-demand":"unknown",y.data=i,y}if(l===404){let v=te("This URL or playback-id does not exist. You may have used an Asset ID or an ID from a different resource.",r),T=te("Specified playback ID: {playbackId}",r).format({playbackId:m}),y=new z(v,u,s!=null?s:!0,T);return y.errorCategory=e,y.muxCode=ne.NETWORK_NOT_FOUND,y.data=i,y}if(l===400){let v=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}",r).format({playbackId:m}),y=new z(v,u,s!=null?s:!0,T);return y.errorCategory=e,y.muxCode=ne.NETWORK_INVALID_URL,y.data=i,y}let g=new z("",u,s!=null?s:!0);return g.errorCategory=e,g.muxCode=ne.NETWORK_UNKNOWN_ERROR,g.data=i,g},Tb=_e.DefaultConfig.capLevelController,ZC={"720p":921600,"1080p":2073600,"1440p":4194304,"2160p":8294400};function JC(i){let e=i.toLowerCase().trim();return ZC[e]}var bg=class el extends Tb{constructor(e){super(e)}static setMaxAutoResolution(e,t){t?el.maxAutoResolution.set(e,t):el.maxAutoResolution.delete(e)}getMaxAutoResolution(){var e;let t=this.hls;return(e=el.maxAutoResolution.get(t))!=null?e:void 0}get levels(){var e;return(e=this.hls.levels)!=null?e:[]}getValidLevels(e){return this.levels.filter((t,s)=>this.isLevelAllowed(t)&&s<=e)}getMaxLevelCapped(e){let t=this.getValidLevels(e),s=this.getMaxAutoResolution();if(!s)return super.getMaxLevel(e);let r=JC(s);if(!r)return super.getMaxLevel(e);let n=t.filter(l=>l.width*l.height<=r),a=n.findIndex(l=>l.width*l.height===r);if(a!==-1){let l=n[a];return t.findIndex(d=>d===l)}if(n.length===0)return 0;let o=n[n.length-1];return t.findIndex(l=>l===o)}getMaxLevel(e){if(this.getMaxAutoResolution()!==void 0)return this.getMaxLevelCapped(e);let t=super.getMaxLevel(e),s=this.getValidLevels(e);if(!s[t])return t;let r=Math.min(s[t].width,s[t].height),n=el.minMaxResolution;return r>=n?t:Tb.getMaxLevelByMediaSize(s,n*(16/9),n)}};bg.minMaxResolution=720,bg.maxAutoResolution=new WeakMap;var ew=bg,_g=ew,tw="com.apple.fps.1_0",iw="application/vnd.apple.mpegurl",sw=({mediaEl:i,getAppCertificate:e,getLicenseKey:t,saveAndDispatchError:s,drmTypeCb:r})=>{if(!window.WebKitMediaKeys||!("onwebkitneedkey"in i)){console.error("No WebKitMediaKeys. FairPlay may not be supported");let h=te("Cannot play DRM-protected content with current security configuration on this browser. Try playing in another browser."),f=new z(h,z.MEDIA_ERR_ENCRYPTED,!0);return f.errorCategory=Ue.DRM,f.muxCode=ne.ENCRYPTED_CDM_ERROR,s(i,f),()=>{}}let n=i,a=e(),o=null,l=h=>{(async()=>{try{n.webkitKeys||d();let f=await a;if(h.initData===null||f==null)return;let m=rw(h.initData,f);u(m)}catch(f){console.error("Could not start encrypted playback due to exception",f),s(n,f)}})()},d=()=>{try{let h=new WebKitMediaKeys(tw);n.webkitSetMediaKeys(h),r()}catch{let h="Cannot play DRM-protected content with current security configuration on this browser. Try playing in another browser.",f=new z(h,z.MEDIA_ERR_ENCRYPTED,!0);throw f.errorCategory=Ue.DRM,f.muxCode=ne.ENCRYPTED_UNSUPPORTED_KEY_SYSTEM,f}},u=h=>{let f=n.webkitKeys.createSession(iw,h),m=async v=>{try{let T=v.message,y=await t(T);f.update(y)}catch(T){console.error("Error on FairPlay session message",T),s(i,T)}},p=v=>{let T=v.target.error;if(!T)return;console.error(`Internal Webkit Key Session Error - sysCode: ${T.systemCode} code: ${T.code}`);let y=te("The DRM Content Decryption Module system had an internal failure. Try reloading the page, upading your browser, or playing in another browser."),b=new z(y,z.MEDIA_ERR_ENCRYPTED,!0);b.errorCategory=Ue.DRM,b.muxCode=ne.ENCRYPTED_CDM_ERROR,s(i,b)},g=()=>{f.removeEventListener("webkitkeymessage",m),f.removeEventListener("webkitkeyerror",p),i.removeEventListener("teardown",g),"webkitCurrentPlaybackTargetIsWireless"in i&&i.removeEventListener("webkitcurrentplaybacktargetiswirelesschanged",g),o=null;try{f.close()}catch{}};"webkitCurrentPlaybackTargetIsWireless"in i&&i.addEventListener("webkitcurrentplaybacktargetiswirelesschanged",g,{once:!0}),f.addEventListener("webkitkeymessage",m),f.addEventListener("webkitkeyerror",p),i.addEventListener("teardown",g),o=g},c=()=>{i.removeEventListener("webkitneedkey",l),i.removeEventListener("teardown",c),o==null||o();try{n.webkitSetMediaKeys(null)}catch{}};return i.addEventListener("webkitneedkey",l),i.addEventListener("teardown",c,{once:!0}),c},rw=(i,e)=>{let t=aw(nw(i)),s=new Uint8Array(i),r=new Uint8Array(t),n=new Uint8Array(e),a=s.byteLength+4+n.byteLength+4+r.byteLength,o=new Uint8Array(a),l=0,d=c=>{o.set(c,l),l+=c.byteLength},u=c=>{let h=new DataView(o.buffer),f=c.byteLength;h.setUint32(l,f,!0),l+=4,d(c)};return d(s),u(r),u(n),o},nw=i=>new TextDecoder("utf-16le").decode(i).replace("skd://","").slice(1);function aw(i){let e=new ArrayBuffer(i.length*2),t=new DataView(e);for(let s=0;s<i.length;s++)t.setUint16(s*2,i.charCodeAt(s),!0);return e}var ow=({mediaEl:i,getAppCertificate:e,getLicenseKey:t,saveAndDispatchError:s,drmTypeCb:r,fallbackToWebkitFairplay:n})=>{let a=null,o=async c=>{try{let h=c.initDataType;if(h!=="skd"){console.error(`Received unexpected initialization data type "${h}"`);return}i.mediaKeys||await l(h);let f=c.initData;if(f==null){console.error(`Could not start encrypted playback due to missing initData in ${c.type} event`);return}await d(h,f)}catch(h){s(i,h);return}},l=async c=>{let h=await navigator.requestMediaKeySystemAccess("com.apple.fps",[{initDataTypes:[c],videoCapabilities:[{contentType:"application/vnd.apple.mpegurl",robustness:""}],distinctiveIdentifier:"not-allowed",persistentState:"not-allowed",sessionTypes:["temporary"]}]).then(m=>(r(),m)).catch(()=>{let m=te("Cannot play DRM-protected content with current security configuration on this browser. Try playing in another browser."),p=new z(m,z.MEDIA_ERR_ENCRYPTED,!0);p.errorCategory=Ue.DRM,p.muxCode=ne.ENCRYPTED_UNSUPPORTED_KEY_SYSTEM,s(i,p)});if(!h)return;let f=await h.createMediaKeys();try{let m=await e();await f.setServerCertificate(m).catch(()=>{let p=te("Your server certificate failed when attempting to set it. This may be an issue with a no longer valid certificate."),g=new z(p,z.MEDIA_ERR_ENCRYPTED,!0);return g.errorCategory=Ue.DRM,g.muxCode=ne.ENCRYPTED_UPDATE_SERVER_CERT_FAILED,Promise.reject(g)})}catch(m){s(i,m);return}await i.setMediaKeys(f)},d=async(c,h)=>{let f=i.mediaKeys.createSession(),m=async v=>{let T=v.message,y=await t(T);try{await f.update(y)}catch{let b=te("Failed to update DRM license. This may be an issue with the player or your protected content."),A=new z(b,z.MEDIA_ERR_ENCRYPTED,!0);A.errorCategory=Ue.DRM,A.muxCode=ne.ENCRYPTED_UPDATE_LICENSE_FAILED,s(i,A)}},p=()=>{let v=T=>{let y;if(T==="internal-error"){let b=te("The DRM Content Decryption Module system had an internal failure. Try reloading the page, upading your browser, or playing in another browser.");y=new z(b,z.MEDIA_ERR_ENCRYPTED,!0),y.errorCategory=Ue.DRM,y.muxCode=ne.ENCRYPTED_CDM_ERROR}else if(T==="output-restricted"||T==="output-downscaled"){let b=te("DRM playback is being attempted in an environment that is not sufficiently secure. User may see black screen.");y=new z(b,z.MEDIA_ERR_ENCRYPTED,!1),y.errorCategory=Ue.DRM,y.muxCode=ne.ENCRYPTED_OUTPUT_RESTRICTED}y&&s(i,y)};f.keyStatuses.forEach(T=>v(T))};f.addEventListener("keystatuseschange",p),f.addEventListener("message",m);let g=async()=>{f.removeEventListener("keystatuseschange",p),f.removeEventListener("message",m),"webkitCurrentPlaybackTargetIsWireless"in i&&i.removeEventListener("webkitcurrentplaybacktargetiswirelesschanged",g),i.removeEventListener("teardown",g),await f.close().catch(v=>{console.warn("There was an error when closing EME session",v)}),a=null};"webkitCurrentPlaybackTargetIsWireless"in i&&i.addEventListener("webkitcurrentplaybacktargetiswirelesschanged",g,{once:!0}),i.addEventListener("teardown",g,{once:!0}),a=g,await f.generateRequest(c,h).catch(async v=>{if(v.name==="NotSupportedError"&&"webkitCurrentPlaybackTargetIsWireless"in i&&i.webkitCurrentPlaybackTargetIsWireless)console.warn("Failed to generate a DRM license request. Attempting to fallback to Webkit DRM"),n==null||n();else{let T=te("Failed to generate a DRM license request. This may be an issue with the player or your protected content."),y=new z(T,z.MEDIA_ERR_ENCRYPTED,!0);return y.errorCategory=Ue.DRM,y.muxCode=ne.ENCRYPTED_GENERATE_REQUEST_FAILED,console.error("Failed to generate license request",v),Promise.reject(y)}})},u=async()=>{i.removeEventListener("encrypted",o),i.removeEventListener("teardown",u),a&&await a(),await i.setMediaKeys(null).catch(()=>{})};return i.addEventListener("encrypted",o),i.addEventListener("teardown",u,{once:!0}),u},Fu={FAIRPLAY:"fairplay",PLAYREADY:"playready",WIDEVINE:"widevine"},lw=i=>{if(i.includes("fps"))return Fu.FAIRPLAY;if(i.includes("playready"))return Fu.PLAYREADY;if(i.includes("widevine"))return Fu.WIDEVINE},dw=(i,e)=>{let t=MC(i);if(!t)return Promise.reject(new Error("No media playlist URL found in multivariant playlist"));if(Eg(t)&&!e)return Promise.reject(new Error("masterPlaylistUrl is required to resolve relative media playlist URL"));let s;try{s=Ig(t,e)}catch(r){return Promise.reject(r)}return fetch(s).then(r=>r.status!==200?Promise.reject(r):r.text())},uw=i=>{let e=i.split(`
|
|
56
|
+
`).find((e,t,s)=>t>0&&s[t-1].startsWith("#EXT-X-STREAM-INF")),Ig=(i,e)=>{var t;if(!Eg(i))return new URL(i);let s=(t=window==null?void 0:window.location)==null?void 0:t.href,r=e!=null?e:s;return e&&Eg(e.toString())&&(r=new URL(e,s)),new URL(i,r)},PC="mux.com",OC=({src:i,customDomain:e=PC})=>{let t;try{t=new URL(`${i}`)}catch{return!1}let s=t.protocol==="https:",r=t.hostname===`stream.${e}`.toLowerCase(),n=t.pathname.split("/"),a=n.length===2,o=!(n!=null&&n[1].includes("."));return s&&r&&a&&o},dr=i=>{let e=(i!=null?i:"").split(".")[1];if(e)try{let t=e.replace(/-/g,"+").replace(/_/g,"/"),s=decodeURIComponent(atob(t).split("").map(function(r){return"%"+("00"+r.charCodeAt(0).toString(16)).slice(-2)}).join(""));return JSON.parse(s)}catch{return}},NC=({exp:i},e=Date.now())=>!i||i*1e3<e,UC=({sub:i},e)=>i!==e,FC=({aud:i},e)=>!i,BC=({aud:i},e)=>i!==e,Db="en";function te(i,e=!0){var t,s;let r=e&&(s=(t=vg)==null?void 0:t[i])!=null?s:i,n=e?vg.code:Db;return new $C(r,n)}var $C=class{constructor(i,e=(t=>(t=vg)!=null?t:Db)()){this.message=i,this.locale=e}format(i){return this.message.replace(/\{(\w+)\}/g,(e,t)=>{var s;return(s=i[t])!=null?s:""})}toString(){return this.message}},HC=Object.values(pg),yb=i=>typeof i=="boolean"||typeof i=="string"&&HC.includes(i),GC=(i,e,t)=>{let{autoplay:s}=i,r=!1,n=!1,a=yb(s)?s:!!s,o=()=>{r||mt(e,"playing",()=>{r=!0},{once:!0})};if(o(),mt(e,"loadstart",()=>{r=!1,o(),fg(e,a)},{once:!0}),mt(e,"loadstart",()=>{t||(i.streamType&&i.streamType!==we.UNKNOWN?n=i.streamType===we.LIVE:n=!Number.isFinite(e.duration)),fg(e,a)},{once:!0}),t&&t.once(_e.Events.LEVEL_LOADED,(l,d)=>{var u;i.streamType&&i.streamType!==we.UNKNOWN?n=i.streamType===we.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&&mt(e,"play",()=>{e.preload==="metadata"?t.once(_e.Events.LEVEL_UPDATED,l):l()},{once:!0})}return l=>{r||(a=yb(l)?l:!!l,fg(e,a))}},fg=(i,e)=>{if(!e)return;let t=i.muted,s=()=>i.muted=t;switch(e){case pg.ANY:i.play().catch(()=>{i.muted=!0,i.play().catch(s)});break;case pg.MUTED:i.muted=!0,i.play().catch(s);break;default:i.play().catch(()=>{});break}},KC=({preload:i,src:e},t,s)=>{let r=c=>{c!=null&&["","none","metadata","auto"].includes(c)?t.setAttribute("preload",c):t.removeAttribute("preload")};if(!s)return r(i),r;let n=!1,a=!1,o=s.config.maxBufferLength,l=s.config.maxBufferSize,d=c=>{r(c);let h=c!=null?c:t.preload;a||h==="none"||(h==="metadata"?(s.config.maxBufferLength=1,s.config.maxBufferSize=1):(s.config.maxBufferLength=o,s.config.maxBufferSize=l),u())},u=()=>{!n&&e&&(n=!0,s.loadSource(e))};return mt(t,"play",()=>{a=!0,s.config.maxBufferLength=o,s.config.maxBufferSize=l,u()},{once:!0}),d(i),d},VC=(i,e,t)=>{let{minPreloadSegments:s}=i;if(s==null||s<=0||!t)return;let r=0,n=!1,a=e.playbackRate||1,o=()=>{e.playbackRate!==0&&(a=e.playbackRate,e.playbackRate=0)};e.playbackRate=0,mt(e,"ratechange",o);let l=(d,{frag:u})=>{n||u.type!=="main"||(r++,r>=s&&(n=!0,e.removeEventListener("ratechange",o),e.playbackRate=a))};t.on(_e.Events.FRAG_BUFFERED,l),e.addEventListener("teardown",()=>{n||(n=!0,t.off(_e.Events.FRAG_BUFFERED,l),e.playbackRate=a)},{once:!0})},WC=(i,e,t)=>{let{initialEstimateSegments:s}=i;if(s==null||s<=0||!t)return;let r=0;t.on(_e.Events.FRAG_BUFFERED,(n,{frag:a})=>{a.type==="main"&&(r++,r<s&&t.abrController.resetEstimator(t.config.abrEwmaDefaultEstimate))})};function qC(i,e){var t;if(!("videoTracks"in i))return;let s=new WeakMap;e.on(_e.Events.MANIFEST_PARSED,function(d,u){l();let c=i.addVideoTrack("main");c.selected=!0;for(let[h,f]of u.levels.entries()){let m=c.addRendition(f.url[0],f.width,f.height,f.videoCodec,f.bitrate);s.set(f,`${h}`),m.id=`${h}`}}),e.on(_e.Events.AUDIO_TRACKS_UPDATED,function(d,u){o();for(let c of u.audioTracks){let h=c.default?"main":"alternative",f=i.addAudioTrack(h,c.name,c.lang);f.id=`${c.id}`,c.default&&(f.enabled=!0)}});let r=()=>{var d;let u=+((d=[...i.audioTracks].find(h=>h.enabled))==null?void 0:d.id),c=e.audioTracks.map(h=>h.id);u!=e.audioTrack&&c.includes(u)&&(e.audioTrack=u)};i.audioTracks.addEventListener("change",r),e.on(_e.Events.LEVELS_UPDATED,function(d,u){var c;let h=i.videoTracks[(c=i.videoTracks.selectedIndex)!=null?c:0];if(!h)return;let f=u.levels.map(m=>s.get(m));for(let m of i.videoRenditions)m.id&&!f.includes(m.id)&&h.removeRendition(m)});let n=d=>{let u=d.target.selectedIndex;u!=e.nextLevel&&(e.nextLevel=u)};(t=i.videoRenditions)==null||t.addEventListener("change",n);let a=()=>{for(let d of i.videoTracks)i.removeVideoTrack(d)},o=()=>{for(let d of i.audioTracks)i.removeAudioTrack(d)},l=()=>{a(),o()};e.once(_e.Events.DESTROYING,()=>{var d,u;l(),(d=i.audioTracks)==null||d.removeEventListener("change",r),(u=i.videoRenditions)==null||u.removeEventListener("change",n)})}var mg=i=>"time"in i?i.time:i.startTime;function YC(i,e){e.on(_e.Events.NON_NATIVE_TEXT_TRACKS_FOUND,(r,{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}`;Vu(i,a.kind,a.label,d==null?void 0:d.lang,c,a.default)})});let t=()=>{if(!e.subtitleTracks.length)return;let r=Array.from(i.textTracks).find(o=>o.id&&o.mode==="showing"&&["subtitles","captions"].includes(o.kind));if(!r)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||(r==null?void 0:r.id)!==a){let o=e.subtitleTracks.findIndex(({lang:l,name:d,type:u,default:c})=>r.id==="default"&&c||l==r.language&&d===r.label&&u.toLowerCase()===r.kind);e.subtitleTrack=o}(r==null?void 0:r.id)===a&&r.cues&&Array.from(r.cues).forEach(o=>{r.addCue(o)})};i.textTracks.addEventListener("change",t),e.on(_e.Events.CUES_PARSED,(r,{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(_e.Events.DESTROYING,()=>{i.textTracks.removeEventListener("change",t),i.querySelectorAll("track[data-removeondestroy]").forEach(r=>{r.remove()})});let s=()=>{Array.from(i.textTracks).forEach(r=>{var n,a;if(!["subtitles","caption"].includes(r.kind)&&(r.label==="thumbnails"||r.kind==="chapters")){if(!((n=r.cues)!=null&&n.length)){let o="track";r.kind&&(o+=`[kind="${r.kind}"]`),r.label&&(o+=`[label="${r.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)}r.mode!=="hidden"&&(r.mode="hidden")}})};e.once(_e.Events.MANIFEST_LOADED,s),e.once(_e.Events.MEDIA_ATTACHED,s)}function Vu(i,e,t,s,r,n){let a=document.createElement("track");return a.kind=e,a.label=t,s&&(a.srclang=s),r&&(a.id=r),n&&(a.default=!0),a.track.mode=["subtitles","captions"].includes(e)?"disabled":"hidden",a.setAttribute("data-removeondestroy",""),i.append(a),a.track}function Cb(i,e){let t=Array.prototype.find.call(i.querySelectorAll("track"),s=>s.track===e);t==null||t.remove()}function il(i,e,t){var s;return(s=Array.from(i.querySelectorAll("track")).find(r=>r.track.label===e&&r.track.kind===t))==null?void 0:s.track}async function wb(i,e,t,s){let r=il(i,t,s);return r||(r=Vu(i,s,t),r.mode="hidden",await new Promise(n=>setTimeout(()=>n(void 0),0))),r.mode!=="hidden"&&(r.mode="hidden"),[...e].sort((n,a)=>mg(a)-mg(n)).forEach(n=>{var a,o;let l=n.value,d=mg(n);if("endTime"in n&&n.endTime!=null)r==null||r.addCue(new VTTCue(d,n.endTime,s==="chapters"?l:JSON.stringify(l!=null?l:null)));else{let u=Array.prototype.findIndex.call(r==null?void 0:r.cues,m=>m.startTime>=d),c=(a=r==null?void 0:r.cues)==null?void 0:a[u],h=c?c.startTime:Number.isFinite(i.duration)?i.duration:Number.MAX_SAFE_INTEGER,f=(o=r==null?void 0:r.cues)==null?void 0:o[u-1];f&&(f.endTime=d),r==null||r.addCue(new VTTCue(d,h,s==="chapters"?l:JSON.stringify(l!=null?l:null)))}}),i.textTracks.dispatchEvent(new Event("change",{bubbles:!0,composed:!0})),r}var Lg="cuepoints",Mb=Object.freeze({label:Lg});async function Rg(i,e,t=Mb){return wb(i,e,t.label,"metadata")}var yg=i=>({time:i.startTime,value:JSON.parse(i.text)});function Pb(i,e={label:Lg}){let t=il(i,e.label,"metadata");return t!=null&&t.cues?Array.from(t.cues,s=>yg(s)):[]}function xg(i,e={label:Lg}){var t,s;let r=il(i,e.label,"metadata");if(!((t=r==null?void 0:r.activeCues)!=null&&t.length))return;if(r.activeCues.length===1)return yg(r.activeCues[0]);let{currentTime:n}=i,a=Array.prototype.find.call((s=r.activeCues)!=null?s:[],({startTime:o,endTime:l})=>o<=n&&l>n);return yg(a||r.activeCues[0])}async function jC(i,e=Mb){return new Promise(t=>{mt(i,"loadstart",async()=>{let s=await Rg(i,[],e);mt(i,"cuechange",()=>{let r=xg(i);if(r){let n=new CustomEvent("cuepointchange",{composed:!0,bubbles:!0,detail:r});i.dispatchEvent(n)}},{},s),t(s)})})}var kg="chapters",Ob=Object.freeze({label:kg}),Tg=i=>({startTime:i.startTime,endTime:i.endTime,value:i.text});async function Dg(i,e,t=Ob){return wb(i,e,t.label,"chapters")}function Nb(i,e={label:kg}){var t;let s=il(i,e.label,"chapters");return(t=s==null?void 0:s.cues)!=null&&t.length?Array.from(s.cues,r=>Tg(r)):[]}function Cg(i,e={label:kg}){var t,s;let r=il(i,e.label,"chapters");if(!((t=r==null?void 0:r.activeCues)!=null&&t.length))return;if(r.activeCues.length===1)return Tg(r.activeCues[0]);let{currentTime:n}=i,a=Array.prototype.find.call((s=r.activeCues)!=null?s:[],({startTime:o,endTime:l})=>o<=n&&l>n);return Tg(a||r.activeCues[0])}async function zC(i,e=Ob){return new Promise(t=>{mt(i,"loadstart",async()=>{let s=await Dg(i,[],e);mt(i,"cuechange",()=>{let r=Cg(i);if(r){let n=new CustomEvent("chapterchange",{composed:!0,bubbles:!0,detail:r});i.dispatchEvent(n)}},{},s),t(s)})})}function Ub(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 Fb(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 oa={VIDEO:"v",THUMBNAIL:"t",STORYBOARD:"s",DRM:"d"},QC=i=>{if(i===Ue.VIDEO)return oa.VIDEO;if(i===Ue.DRM)return oa.DRM},XC=(i,e)=>{var t,s;let r=tl(i),n=`${r}Token`;return(t=e.tokens)!=null&&t[r]?(s=e.tokens)==null?void 0:s[r]:Sg(n,e)?e[n]:void 0},$u=(i,e,t,s,r=!1,n=!(a=>(a=globalThis.navigator)==null?void 0:a.onLine)())=>{var a,o;if(n){let v=te("Your device appears to be offline",r),T,y=z.MEDIA_ERR_NETWORK,b=new z(v,y,!1,T);return b.errorCategory=e,b.muxCode=ne.NETWORK_OFFLINE,b.data=i,b}let l="status"in i?i.status:i.code,d=Date.now(),u=z.MEDIA_ERR_NETWORK;if(l===200)return;let c=tl(e),h=XC(e,t),f=QC(e),[m]=Gu((a=t.playbackId)!=null?a:"");if(!l||!m)return;let p=dr(h);if(h&&!p){let v=te("The {tokenNamePrefix}-token provided is invalid or malformed.",r).format({tokenNamePrefix:c}),T=te("Compact JWT string: {token}",r).format({token:h}),y=new z(v,u,!0,T);return y.errorCategory=e,y.muxCode=ne.NETWORK_TOKEN_MALFORMED,y.data=i,y}if(l>=500){let v=new z("",u,s!=null?s:!0);return v.errorCategory=e,v.muxCode=ne.NETWORK_UNKNOWN_ERROR,v}if(l===403)if(p){if(NC(p,d)){let v={timeStyle:"medium",dateStyle:"medium"},T=te("The video\u2019s secured {tokenNamePrefix}-token has expired.",r).format({tokenNamePrefix:c}),y=te("Expired at: {expiredDate}. Current time: {currentDate}.",r).format({expiredDate:new Intl.DateTimeFormat("en",v).format((o=p.exp)!=null?o:0*1e3),currentDate:new Intl.DateTimeFormat("en",v).format(d)}),b=new z(T,u,!0,y);return b.errorCategory=e,b.muxCode=ne.NETWORK_TOKEN_EXPIRED,b.data=i,b}if(UC(p,m)){let v=te("The video\u2019s playback ID does not match the one encoded in the {tokenNamePrefix}-token.",r).format({tokenNamePrefix:c}),T=te("Specified playback ID: {playbackId} and the playback ID encoded in the {tokenNamePrefix}-token: {tokenPlaybackId}",r).format({tokenNamePrefix:c,playbackId:m,tokenPlaybackId:p.sub}),y=new z(v,u,!0,T);return y.errorCategory=e,y.muxCode=ne.NETWORK_TOKEN_SUB_MISMATCH,y.data=i,y}if(FC(p,f)){let v=te("The {tokenNamePrefix}-token is formatted with incorrect information.",r).format({tokenNamePrefix:c}),T=te("The {tokenNamePrefix}-token has no aud value. aud value should be {expectedAud}.",r).format({tokenNamePrefix:c,expectedAud:f}),y=new z(v,u,!0,T);return y.errorCategory=e,y.muxCode=ne.NETWORK_TOKEN_AUD_MISSING,y.data=i,y}if(BC(p,f)){let v=te("The {tokenNamePrefix}-token is formatted with incorrect information.",r).format({tokenNamePrefix:c}),T=te("The {tokenNamePrefix}-token has an incorrect aud value: {aud}. aud value should be {expectedAud}.",r).format({tokenNamePrefix:c,expectedAud:f,aud:p.aud}),y=new z(v,u,!0,T);return y.errorCategory=e,y.muxCode=ne.NETWORK_TOKEN_AUD_MISMATCH,y.data=i,y}}else{let v=te("Authorization error trying to access this {category} URL. If this is a signed URL, you might need to provide a {tokenNamePrefix}-token.",r).format({tokenNamePrefix:c,category:e}),T=te("Specified playback ID: {playbackId}",r).format({playbackId:m}),y=new z(v,u,s!=null?s:!0,T);return y.errorCategory=e,y.muxCode=ne.NETWORK_TOKEN_MISSING,y.data=i,y}if(l===412){let v=te("This playback-id may belong to a live stream that is not currently active or an asset that is not ready.",r),T=te("Specified playback ID: {playbackId}",r).format({playbackId:m}),y=new z(v,u,s!=null?s:!0,T);return y.errorCategory=e,y.muxCode=ne.NETWORK_NOT_READY,y.streamType=t.streamType===we.LIVE?"live":t.streamType===we.ON_DEMAND?"on-demand":"unknown",y.data=i,y}if(l===404){let v=te("This URL or playback-id does not exist. You may have used an Asset ID or an ID from a different resource.",r),T=te("Specified playback ID: {playbackId}",r).format({playbackId:m}),y=new z(v,u,s!=null?s:!0,T);return y.errorCategory=e,y.muxCode=ne.NETWORK_NOT_FOUND,y.data=i,y}if(l===400){let v=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}",r).format({playbackId:m}),y=new z(v,u,s!=null?s:!0,T);return y.errorCategory=e,y.muxCode=ne.NETWORK_INVALID_URL,y.data=i,y}let g=new z("",u,s!=null?s:!0);return g.errorCategory=e,g.muxCode=ne.NETWORK_UNKNOWN_ERROR,g.data=i,g},Tb=_e.DefaultConfig.capLevelController,ZC={"720p":921600,"1080p":2073600,"1440p":4194304,"2160p":8294400};function JC(i){let e=i.toLowerCase().trim();return ZC[e]}var bg=class el extends Tb{constructor(e){super(e)}static setMaxAutoResolution(e,t){t?el.maxAutoResolution.set(e,t):el.maxAutoResolution.delete(e)}getMaxAutoResolution(){var e;let t=this.hls;return(e=el.maxAutoResolution.get(t))!=null?e:void 0}get levels(){var e;return(e=this.hls.levels)!=null?e:[]}getValidLevels(e){return this.levels.filter((t,s)=>this.isLevelAllowed(t)&&s<=e)}getMaxLevelCapped(e){let t=this.getValidLevels(e),s=this.getMaxAutoResolution();if(!s)return super.getMaxLevel(e);let r=JC(s);if(!r)return super.getMaxLevel(e);let n=t.filter(l=>l.width*l.height<=r),a=n.findIndex(l=>l.width*l.height===r);if(a!==-1){let l=n[a];return t.findIndex(d=>d===l)}if(n.length===0)return 0;let o=n[n.length-1];return t.findIndex(l=>l===o)}getMaxLevel(e){if(this.getMaxAutoResolution()!==void 0)return this.getMaxLevelCapped(e);let t=super.getMaxLevel(e),s=this.getValidLevels(e);if(!s[t])return t;let r=Math.min(s[t].width,s[t].height),n=el.minMaxResolution;return r>=n?t:Tb.getMaxLevelByMediaSize(s,n*(16/9),n)}};bg.minMaxResolution=720,bg.maxAutoResolution=new WeakMap;var ew=bg,_g=ew,tw="com.apple.fps.1_0",iw="application/vnd.apple.mpegurl",sw=({mediaEl:i,getAppCertificate:e,getLicenseKey:t,saveAndDispatchError:s,drmTypeCb:r})=>{if(!window.WebKitMediaKeys||!("onwebkitneedkey"in i)){console.error("No WebKitMediaKeys. FairPlay may not be supported");let h=te("Cannot play DRM-protected content with current security configuration on this browser. Try playing in another browser."),f=new z(h,z.MEDIA_ERR_ENCRYPTED,!0);return f.errorCategory=Ue.DRM,f.muxCode=ne.ENCRYPTED_CDM_ERROR,s(i,f),()=>{}}let n=i,a=e(),o=null,l=h=>{(async()=>{try{n.webkitKeys||d();let f=await a;if(h.initData===null||f==null)return;let m=rw(h.initData,f);u(m)}catch(f){console.error("Could not start encrypted playback due to exception",f),s(n,f)}})()},d=()=>{try{let h=new WebKitMediaKeys(tw);n.webkitSetMediaKeys(h),r()}catch{let h="Cannot play DRM-protected content with current security configuration on this browser. Try playing in another browser.",f=new z(h,z.MEDIA_ERR_ENCRYPTED,!0);throw f.errorCategory=Ue.DRM,f.muxCode=ne.ENCRYPTED_UNSUPPORTED_KEY_SYSTEM,f}},u=h=>{let f=n.webkitKeys.createSession(iw,h),m=async v=>{try{let T=v.message,y=await t(T);f.update(y)}catch(T){console.error("Error on FairPlay session message",T),s(i,T)}},p=v=>{let T=v.target.error;if(!T)return;console.error(`Internal Webkit Key Session Error - sysCode: ${T.systemCode} code: ${T.code}`);let y=te("The DRM Content Decryption Module system had an internal failure. Try reloading the page, updating your browser, or playing in another browser."),b=new z(y,z.MEDIA_ERR_ENCRYPTED,!0);b.errorCategory=Ue.DRM,b.muxCode=ne.ENCRYPTED_CDM_ERROR,s(i,b)},g=()=>{f.removeEventListener("webkitkeymessage",m),f.removeEventListener("webkitkeyerror",p),i.removeEventListener("teardown",g),"webkitCurrentPlaybackTargetIsWireless"in i&&i.removeEventListener("webkitcurrentplaybacktargetiswirelesschanged",g),o=null;try{f.close()}catch{}};"webkitCurrentPlaybackTargetIsWireless"in i&&i.addEventListener("webkitcurrentplaybacktargetiswirelesschanged",g,{once:!0}),f.addEventListener("webkitkeymessage",m),f.addEventListener("webkitkeyerror",p),i.addEventListener("teardown",g),o=g},c=()=>{i.removeEventListener("webkitneedkey",l),i.removeEventListener("teardown",c),o==null||o();try{n.webkitSetMediaKeys(null)}catch{}};return i.addEventListener("webkitneedkey",l),i.addEventListener("teardown",c,{once:!0}),c},rw=(i,e)=>{let t=aw(nw(i)),s=new Uint8Array(i),r=new Uint8Array(t),n=new Uint8Array(e),a=s.byteLength+4+n.byteLength+4+r.byteLength,o=new Uint8Array(a),l=0,d=c=>{o.set(c,l),l+=c.byteLength},u=c=>{let h=new DataView(o.buffer),f=c.byteLength;h.setUint32(l,f,!0),l+=4,d(c)};return d(s),u(r),u(n),o},nw=i=>new TextDecoder("utf-16le").decode(i).replace("skd://","").slice(1);function aw(i){let e=new ArrayBuffer(i.length*2),t=new DataView(e);for(let s=0;s<i.length;s++)t.setUint16(s*2,i.charCodeAt(s),!0);return e}var ow=({mediaEl:i,getAppCertificate:e,getLicenseKey:t,saveAndDispatchError:s,drmTypeCb:r,fallbackToWebkitFairplay:n})=>{let a=null,o=async c=>{try{let h=c.initDataType;if(h!=="skd"){console.error(`Received unexpected initialization data type "${h}"`);return}i.mediaKeys||await l(h);let f=c.initData;if(f==null){console.error(`Could not start encrypted playback due to missing initData in ${c.type} event`);return}await d(h,f)}catch(h){s(i,h);return}},l=async c=>{let h=await navigator.requestMediaKeySystemAccess("com.apple.fps",[{initDataTypes:[c],videoCapabilities:[{contentType:"application/vnd.apple.mpegurl",robustness:""}],distinctiveIdentifier:"not-allowed",persistentState:"not-allowed",sessionTypes:["temporary"]}]).then(m=>(r(),m)).catch(()=>{let m=te("Cannot play DRM-protected content with current security configuration on this browser. Try playing in another browser."),p=new z(m,z.MEDIA_ERR_ENCRYPTED,!0);p.errorCategory=Ue.DRM,p.muxCode=ne.ENCRYPTED_UNSUPPORTED_KEY_SYSTEM,s(i,p)});if(!h)return;let f=await h.createMediaKeys();try{let m=await e();await f.setServerCertificate(m).catch(()=>{let p=te("Your server certificate failed when attempting to set it. This may be an issue with a no longer valid certificate."),g=new z(p,z.MEDIA_ERR_ENCRYPTED,!0);return g.errorCategory=Ue.DRM,g.muxCode=ne.ENCRYPTED_UPDATE_SERVER_CERT_FAILED,Promise.reject(g)})}catch(m){s(i,m);return}await i.setMediaKeys(f)},d=async(c,h)=>{let f=i.mediaKeys.createSession(),m=async v=>{let T=v.message,y=await t(T);try{await f.update(y)}catch{let b=te("Failed to update DRM license. This may be an issue with the player or your protected content."),A=new z(b,z.MEDIA_ERR_ENCRYPTED,!0);A.errorCategory=Ue.DRM,A.muxCode=ne.ENCRYPTED_UPDATE_LICENSE_FAILED,s(i,A)}},p=()=>{let v=T=>{let y;if(T==="internal-error"){let b=te("The DRM Content Decryption Module system had an internal failure. Try reloading the page, updating your browser, or playing in another browser.");y=new z(b,z.MEDIA_ERR_ENCRYPTED,!0),y.errorCategory=Ue.DRM,y.muxCode=ne.ENCRYPTED_CDM_ERROR}else if(T==="output-restricted"||T==="output-downscaled"){let b=te("DRM playback is being attempted in an environment that is not sufficiently secure. User may see black screen.");y=new z(b,z.MEDIA_ERR_ENCRYPTED,!1),y.errorCategory=Ue.DRM,y.muxCode=ne.ENCRYPTED_OUTPUT_RESTRICTED}y&&s(i,y)};f.keyStatuses.forEach(T=>v(T))};f.addEventListener("keystatuseschange",p),f.addEventListener("message",m);let g=async()=>{f.removeEventListener("keystatuseschange",p),f.removeEventListener("message",m),"webkitCurrentPlaybackTargetIsWireless"in i&&i.removeEventListener("webkitcurrentplaybacktargetiswirelesschanged",g),i.removeEventListener("teardown",g),await f.close().catch(v=>{console.warn("There was an error when closing EME session",v)}),a=null};"webkitCurrentPlaybackTargetIsWireless"in i&&i.addEventListener("webkitcurrentplaybacktargetiswirelesschanged",g,{once:!0}),i.addEventListener("teardown",g,{once:!0}),a=g,await f.generateRequest(c,h).catch(async v=>{if(v.name==="NotSupportedError"&&"webkitCurrentPlaybackTargetIsWireless"in i&&i.webkitCurrentPlaybackTargetIsWireless)console.warn("Failed to generate a DRM license request. Attempting to fallback to Webkit DRM"),n==null||n();else{let T=te("Failed to generate a DRM license request. This may be an issue with the player or your protected content."),y=new z(T,z.MEDIA_ERR_ENCRYPTED,!0);return y.errorCategory=Ue.DRM,y.muxCode=ne.ENCRYPTED_GENERATE_REQUEST_FAILED,console.error("Failed to generate license request",v),Promise.reject(y)}})},u=async()=>{i.removeEventListener("encrypted",o),i.removeEventListener("teardown",u),a&&await a(),await i.setMediaKeys(null).catch(()=>{})};return i.addEventListener("encrypted",o),i.addEventListener("teardown",u,{once:!0}),u},Fu={FAIRPLAY:"fairplay",PLAYREADY:"playready",WIDEVINE:"widevine"},lw=i=>{if(i.includes("fps"))return Fu.FAIRPLAY;if(i.includes("playready"))return Fu.PLAYREADY;if(i.includes("widevine"))return Fu.WIDEVINE},dw=(i,e)=>{let t=MC(i);if(!t)return Promise.reject(new Error("No media playlist URL found in multivariant playlist"));if(Eg(t)&&!e)return Promise.reject(new Error("masterPlaylistUrl is required to resolve relative media playlist URL"));let s;try{s=Ig(t,e)}catch(r){return Promise.reject(r)}return fetch(s).then(r=>r.status!==200?Promise.reject(r):r.text())},uw=i=>{let e=i.split(`
|
|
57
57
|
`).filter(s=>s.startsWith("#EXT-X-SESSION-DATA"));if(!e.length)return{};let t={};for(let s of e){let r=hw(s),n=r["DATA-ID"];n&&(t[n]={...r})}return{sessionData:t}},cw=/([A-Z0-9-]+)="?(.*?)"?(?:,|$)/g;function hw(i){let e=[...i.matchAll(cw)];return Object.fromEntries(e.map(([,t,s])=>[t,s]))}var fw=i=>{var e,t,s;let r=i.split(`
|
|
58
|
-
`),n=(t=((e=r.find(d=>d.startsWith("#EXT-X-PLAYLIST-TYPE")))!=null?e:"").split(":")[1])==null?void 0:t.trim(),a=xb(n),o=kb(n),l;if(a===we.LIVE){let d=r.find(u=>u.startsWith("#EXT-X-PART-INF"));if(d)l=+d.split(":")[1].split("=")[1]*2;else{let u=r.find(h=>h.startsWith("#EXT-X-TARGETDURATION")),c=(s=u==null?void 0:u.split(":"))==null?void 0:s[1];l=+(c!=null?c:6)*3}}return{streamType:a,targetLiveWindow:o,liveEdgeStartOffset:l}},mw=async(i,e)=>{if(e===Cs.MP4)return{streamType:we.ON_DEMAND,targetLiveWindow:Number.NaN,liveEdgeStartOffset:void 0,sessionData:void 0};if(e===Cs.M3U8){let t=await fetch(i);if(!t.ok)return Promise.reject(t);let s=await t.text(),r=await dw(s,t.url);return{...uw(s),...fw(r)}}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}},pw=async(i,e,t=Ku({src:i}))=>{var s,r,n,a;let{streamType:o,targetLiveWindow:l,liveEdgeStartOffset:d,sessionData:u}=await mw(i,t),c=u==null?void 0:u["com.apple.hls.chapters"];(c!=null&&c.URI||c!=null&&c.VALUE.toLocaleLowerCase().startsWith("http"))&&wg((s=c.URI)!=null?s:c.VALUE,e),((r=Xe.get(e))!=null?r:{}).liveEdgeStartOffset=d,((n=Xe.get(e))!=null?n:{}).targetLiveWindow=l,e.dispatchEvent(new CustomEvent("targetlivewindowchange",{composed:!0,bubbles:!0})),((a=Xe.get(e))!=null?a:{}).streamType=o,e.dispatchEvent(new CustomEvent("streamtypechange",{composed:!0,bubbles:!0}))},wg=async(i,e)=>{var t,s;try{let r=await fetch(i);if(!r.ok)throw new Error(`Failed to fetch Mux metadata: ${r.status} ${r.statusText}`);let n=await r.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);((s=Xe.get(e))!=null?s:{}).metadata=a;let o=new CustomEvent("muxmetadata");e.dispatchEvent(o)}catch(r){console.error(r)}},gw=i=>{var e;let t=i.type,s=xb(t),r=kb(t),n,a=!!((e=i.partList)!=null&&e.length);return s===we.LIVE&&(n=a?i.partTarget*2:i.targetduration*3),{streamType:s,targetLiveWindow:r,liveEdgeStartOffset:n,lowLatency:a}},vw=(i,e,t)=>{var s,r,n,a,o,l,d,u;let{streamType:c,targetLiveWindow:h,liveEdgeStartOffset:f,lowLatency:m}=gw(i);if(c===we.LIVE){m?(t.config.backBufferLength=(s=t.userConfig.backBufferLength)!=null?s:4,t.config.maxFragLookUpTolerance=(r=t.userConfig.maxFragLookUpTolerance)!=null?r:.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 v;return g>this.length||g<0||Number.isFinite(e.duration)?e.seekable.end(g):(v=t.liveSyncPosition)!=null?v:e.seekable.end(g)}});((o=Xe.get(e))!=null?o:{}).seekable=p}((l=Xe.get(e))!=null?l:{}).liveEdgeStartOffset=f,((d=Xe.get(e))!=null?d:{}).targetLiveWindow=h,e.dispatchEvent(new CustomEvent("targetlivewindowchange",{composed:!0,bubbles:!0})),((u=Xe.get(e))!=null?u:{}).streamType=c,e.dispatchEvent(new CustomEvent("streamtypechange",{composed:!0,bubbles:!0}))},bb,_b,Bb=(_b=(bb=globalThis==null?void 0:globalThis.navigator)==null?void 0:bb.userAgent)!=null?_b:"",Ab,Sb,Ib,Ew=(Ib=(Sb=(Ab=globalThis==null?void 0:globalThis.navigator)==null?void 0:Ab.userAgentData)==null?void 0:Sb.platform)!=null?Ib:"",yw=Bb.toLowerCase().includes("android")||["x11","android"].some(i=>Ew.toLowerCase().includes(i)),Tw=i=>/^((?!chrome|android).)*safari/i.test(Bb)&&!!i.canPlayType("application/vnd.apple.mpegurl"),Xe=new WeakMap,ws="mux.com",Lb,Rb,$b=(Rb=(Lb=_e).isSupported)==null?void 0:Rb.call(Lb),bw=i=>yw||!Tw(i),Wu=()=>{if(typeof window!="undefined")return Hd.utils.now()},_w=Hd.utils.generateUUID,sl=({playbackId:i,customDomain:e=ws,maxResolution:t,minResolution:s,renditionOrder:r,programStartTime:n,programEndTime:a,assetStartTime:o,assetEndTime:l,playbackToken:d,tokens:{playback:u=d}={},extraSourceParams:c={}}={})=>{if(!i)return;let[h,f=""]=Gu(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),s&&(m.searchParams.set("min_resolution",s),t&&+t.slice(0,-1)<+s.slice(0,-1)&&console.error("minResolution must be <= maxResolution","minResolution",s,"maxResolution",t)),r&&m.searchParams.set("rendition_order",r),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()},qu=i=>{if(!i)return;let[e]=i.split("?");return e||void 0},Yu=i=>{if(!i||!i.startsWith("https://stream."))return;let[e]=new URL(i).pathname.slice(1).split(/\.m3u8|\//);return e||void 0},Aw=i=>{var e,t,s;return(e=i==null?void 0:i.metadata)!=null&&e.video_id?i.metadata.video_id:zb(i)&&(s=(t=qu(i.playbackId))!=null?t:Yu(i.src))!=null?s:i.src},Mg=i=>{var e;return(e=Xe.get(i))==null?void 0:e.error},Hb=i=>{var e;return(e=Xe.get(i))==null?void 0:e.metadata},Hu=i=>{var e,t;return(t=(e=Xe.get(i))==null?void 0:e.streamType)!=null?t:we.UNKNOWN},Gb=i=>{var e,t;return(t=(e=Xe.get(i))==null?void 0:e.targetLiveWindow)!=null?t:Number.NaN},ju=i=>{var e,t;return(t=(e=Xe.get(i))==null?void 0:e.seekable)!=null?t:i.seekable},Kb=i=>{var e;let t=(e=Xe.get(i))==null?void 0:e.liveEdgeStartOffset;if(typeof t!="number")return Number.NaN;let s=ju(i);return s.length?s.end(s.length-1)-t:Number.NaN},Vb=i=>{var e;return(e=Xe.get(i))==null?void 0:e.coreReference},Pg=.034,Sw=(i,e,t=Pg)=>Math.abs(i-e)<=t,Wb=(i,e,t=Pg)=>i>e||Sw(i,e,t),Iw=(i,e=Pg)=>i.paused&&Wb(i.currentTime,i.duration,e),qb=(i,e)=>{var t,s,r;if(!e||!i.buffered.length)return;if(i.readyState>2)return!1;let n=e.currentLevel>=0?(s=(t=e.levels)==null?void 0:t[e.currentLevel])==null?void 0:s.details:(r=e.levels.find(c=>!!c.details))==null?void 0:r.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},Og=(i,e)=>i.ended||i.loop?i.ended:e&&qb(i,e)?!0:Iw(i),Ng=(i,e,t)=>{Ug(e,t,i);let{metadata:s={}}=i,{view_session_id:r=_w()}=s,n=Aw(i);s.view_session_id=r,s.video_id=n,i.metadata=s;let a=h=>{var f;(f=e.mux)==null||f.emit("hb",{view_drm_type:h})};i.drmTypeCb=a,i.fallbackToWebkitFairplay=async()=>{var h;let f=!e.paused,m=e.currentTime;i.useWebkitFairplay=!0;let p=i.muxDataKeepSession;i.muxDataKeepSession=!0;let g=(h=Xe.get(e))==null?void 0:h.coreReference;Ng(i,e,g),i.muxDataKeepSession=p,i.useWebkitFairplay=!1,f&&await e.play().then(()=>{e.currentTime=m}).catch(()=>{}),e.currentTime=m},Xe.set(e,{retryCount:0});let o=Lw(i,e),l=KC(i,e,o);i!=null&&i.muxDataKeepSession&&e!=null&&e.mux&&!e.mux.deleted?o&&e.mux.addHLSJS({hlsjs:o,Hls:o?_e:void 0}):Mw(i,e,o),Pw(i,e,o),jC(e),zC(e);let d=GC(i,e,o);VC(i,e,o),WC(i,e,o);let u={engine:o,setAutoplay:d,setPreload:l},c=Xe.get(e);return c&&(c.coreReference=u),u},Ug=(i,e,t)=>{let s=e==null?void 0:e.engine;i!=null&&i.mux&&!i.mux.deleted&&(t!=null&&t.muxDataKeepSession?s&&i.mux.removeHLSJS():(i.mux.destroy(),delete i.mux)),s&&(s.detachMedia(),s.destroy()),i&&(i.hasAttribute("src")&&(i.removeAttribute("src"),i.load()),i.removeEventListener("error",Xb),i.removeEventListener("error",Ag),i.removeEventListener("durationchange",Qb),Xe.delete(i),i.dispatchEvent(new Event("teardown")))};function Yb(i,e){var t;let s=Ku(i);if(s!==Cs.M3U8)return!0;let r=!s||((t=e.canPlayType(s))!=null?t:!0),{preferPlayback:n}=i,a=n===gi.MSE,o=n===gi.NATIVE,l=$b&&(a||bw(e));return r&&(o||!l)}var Lw=(i,e)=>{let{debug:t,streamType:s,startTime:r=-1,metadata:n,preferCmcd:a,_hlsConfig:o={},maxAutoResolution:l,initialBandwidthEstimateKbps:d}=i,u=Ku(i)===Cs.M3U8,c=Yb(i,e);if(u&&!c&&$b){let h={backBufferLength:30,renderTextTracksNatively:!1,liveDurationInfinity:!0,capLevelOnFPSDrop:!0,...d!=null?{abrEwmaDefaultEstimate:d*1e3}:{}},f=Rw(s),m=xw(i),p=[Jo.QUERY,Jo.HEADER].includes(a)?{useHeaders:a===Jo.HEADER,sessionId:n==null?void 0:n.view_session_id,contentId:n==null?void 0:n.video_id}:void 0,g=ww(i,o),v=new _e({debug:t,startPosition:r,cmcd:p,xhrSetup:(T,y)=>{var b,A;if(a&&a!==Jo.QUERY)return;let R=Ig(y);if(!R.searchParams.has("CMCD"))return;let I=((A=(b=R.searchParams.get("CMCD"))==null?void 0:b.split(","))!=null?A:[]).filter(x=>x.startsWith("sid")||x.startsWith("cid")).join(",");R.searchParams.set("CMCD",I),T.open("GET",R)},...h,...g,...f,...m,...o});return g.capLevelController===_g&&l!==void 0&&_g.setMaxAutoResolution(v,l),v.on(_e.Events.MANIFEST_PARSED,async function(T,y){var b,A;let R=(b=y.sessionData)==null?void 0:b["com.apple.hls.chapters"];(R!=null&&R.URI||R!=null&&R.VALUE.toLocaleLowerCase().startsWith("http"))&&wg((A=R==null?void 0:R.URI)!=null?A:R==null?void 0:R.VALUE,e)}),v}},Rw=i=>i===we.LIVE?{backBufferLength:8}:{},xw=i=>{let{tokens:{drm:e}={},playbackId:t,drmTypeCb:s}=i,r=qu(t);return!e||!r?{}:{emeEnabled:!0,drmSystems:{"com.apple.fps":{licenseUrl:Bu(i,"fairplay"),serverCertificateUrl:jb(i,"fairplay")},"com.widevine.alpha":{licenseUrl:Bu(i,"widevine")},"com.microsoft.playready":{licenseUrl:Bu(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=lw(n);return s==null||s(l),o}))}},kw=async i=>{let e=await fetch(i);return e.status!==200?Promise.reject(e):await e.arrayBuffer()},Dw=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 s=await t.arrayBuffer();return new Uint8Array(s)},Cw=(i,e)=>{let t={mediaEl:e,getAppCertificate:()=>kw(jb(i,"fairplay")).catch(s=>{if(s instanceof Response){let r=$u(s,Ue.DRM,i);return console.error("mediaError",r==null?void 0:r.message,r==null?void 0:r.context),r?Promise.reject(r):Promise.reject(new Error("Unexpected error in app cert request"))}return Promise.reject(s)}),getLicenseKey:s=>Dw(s,Bu(i,"fairplay")).catch(r=>{if(r instanceof Response){let n=$u(r,Ue.DRM,i);return console.error("mediaError",n==null?void 0:n.message,n==null?void 0:n.context),n?Promise.reject(n):Promise.reject(new Error("Unexpected error in license key request"))}return Promise.reject(r)}),saveAndDispatchError:lr,drmTypeCb:()=>{var s;(s=i.drmTypeCb)==null||s.call(i,Fu.FAIRPLAY)}};if(i.useWebkitFairplay)sw(t);else{let s={fallbackToWebkitFairplay:async()=>{var n;await r(),(n=i.fallbackToWebkitFairplay)==null||n.call(i)},...t},r=ow(s)}},Bu=({playbackId:i,tokens:{drm:e}={},customDomain:t=ws},s)=>{let r=qu(i);return`https://license.${t.toLocaleLowerCase().endsWith(ws)?t:ws}/license/${s}/${r}?token=${e}`},jb=({playbackId:i,tokens:{drm:e}={},customDomain:t=ws},s)=>{let r=qu(i);return`https://license.${t.toLocaleLowerCase().endsWith(ws)?t:ws}/appcert/${s}/${r}?token=${e}`},zb=({playbackId:i,src:e,customDomain:t})=>{if(i)return!0;if(typeof e!="string")return!1;let s=window==null?void 0:window.location.href,r=new URL(e,s).hostname.toLocaleLowerCase();return r.includes(ws)||!!t&&r.includes(t.toLocaleLowerCase())},ww=(i,e)=>{let t={};return t.capLevelToPlayerSize=i.capRenditionToPlayerSize,t.capLevelToPlayerSize==null?(t.capLevelController=_g,t.capLevelToPlayerSize=!0):t.capLevelController=Qo,t},Mw=(i,e,t)=>{var s;let{envKey:r,disableTracking:n,muxDataSDK:a=Hd,muxDataSDKOptions:o={}}=i,l=zb(i);if(!n&&(r||l)){let{playerInitTime:d,playerSoftwareName:u,playerSoftwareVersion:c,beaconCollectionDomain:h,debug:f,disableCookies:m}=i,p={...i.metadata,video_title:((s=i==null?void 0:i.metadata)==null?void 0:s.video_title)||void 0},g=v=>typeof v.player_error_code=="string"?!1:typeof i.errorTranslator=="function"?i.errorTranslator(v):v;a.monitor(e,{debug:f,beaconCollectionDomain:h,hlsjs:t,Hls:t?_e:void 0,automaticErrorTracking:!1,errorTranslator:g,disableCookies:m,...o,data:{...r?{env_key:r}:{},player_software_name:u,player_software:u,player_software_version:c,player_init_time:d,...p}})}},Pw=(i,e,t)=>{var s,r;let n=Yb(i,e),{src:a,customDomain:o=ws}=i,l=()=>{e.ended||i.disablePseudoEnded||!Og(e,t)||(qb(e,t)?e.currentTime=e.buffered.end(e.buffered.length-1):e.dispatchEvent(new Event("ended")))},d,u,c=()=>{let h=ju(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(mt(e,"durationchange",c),e&&n){let h=Ku(i);if(typeof a=="string"){if(a.endsWith(".mp4")&&a.includes(o)){let p=Yu(a),g=new URL(`https://stream.${o}/${p}/metadata.json`);wg(g.toString(),e)}let f=()=>{if(Hu(e)!==we.LIVE||Number.isFinite(e.duration))return;let p=setInterval(c,1e3);e.addEventListener("teardown",()=>{clearInterval(p)},{once:!0}),mt(e,"durationchange",()=>{Number.isFinite(e.duration)&&clearInterval(p)})},m=async()=>pw(a,e,h).then(f).catch(p=>{if(p instanceof Response){let g=$u(p,Ue.VIDEO,i);if(g){lr(e,g);return}}else p instanceof Error});if(e.preload==="none"){let p=()=>{m(),e.removeEventListener("loadedmetadata",g)},g=()=>{m(),e.removeEventListener("play",p)};mt(e,"play",p,{once:!0}),mt(e,"loadedmetadata",g,{once:!0})}else m();(s=i.tokens)!=null&&s.drm?Cw(i,e):mt(e,"encrypted",()=>{let p=te("Attempting to play DRM-protected content without providing a DRM token."),g=new z(p,z.MEDIA_ERR_ENCRYPTED,!0);g.errorCategory=Ue.DRM,g.muxCode=ne.ENCRYPTED_MISSING_TOKEN,lr(e,g)},{once:!0}),e.setAttribute("src",a),i.startTime&&(((r=Xe.get(e))!=null?r:{}).startTime=i.startTime,e.addEventListener("durationchange",Qb,{once:!0}))}else e.removeAttribute("src");e.addEventListener("error",Xb),e.addEventListener("error",Ag),e.addEventListener("emptied",()=>{e.querySelectorAll("track[data-removeondestroy]").forEach(f=>{f.remove()})},{once:!0}),mt(e,"pause",l),mt(e,"seeked",l),mt(e,"play",()=>{e.ended||Wb(e.currentTime,e.duration)&&(e.currentTime=e.seekable.length?e.seekable.start(0):0)})}else t&&a?(t.once(_e.Events.LEVEL_LOADED,(h,f)=>{vw(f.details,e,t),c(),Hu(e)===we.LIVE&&!Number.isFinite(e.duration)&&(t.on(_e.Events.LEVEL_UPDATED,c),mt(e,"durationchange",()=>{Number.isFinite(e.duration)&&t.off(_e.Events.LEVELS_UPDATED,c)}))}),t.on(_e.Events.ERROR,(h,f)=>{var m,p;let g=Ow(f,i);if(g.muxCode===ne.NETWORK_NOT_READY){let v=(m=Xe.get(e))!=null?m:{},T=(p=v.retryCount)!=null?p:0;if(T<6){let y=T===0?5e3:6e4,b=new z(`Retrying in ${y/1e3} seconds...`,g.code,g.fatal);Object.assign(b,g),lr(e,b);let A=setTimeout(()=>{v.retryCount=T+1,f.details==="manifestLoadError"&&f.url&&t.loadSource(f.url)},y);e.addEventListener("teardown",()=>clearTimeout(A),{once:!0});return}else{v.retryCount=0;let y=new z('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),lr(e,y);return}}lr(e,g)}),t.on(_e.Events.MANIFEST_LOADED,()=>{let h=Xe.get(e);h&&h.error&&(h.error=null,h.retryCount=0,e.dispatchEvent(new Event("emptied")),e.dispatchEvent(new Event("loadstart")))}),e.addEventListener("error",Ag),mt(e,"waiting",l),qC(i,t),YC(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 Qb(i){var e;let t=i.target,s=(e=Xe.get(t))==null?void 0:e.startTime;if(s&&CC(t.seekable,t.duration,s)){let r=t.preload==="auto";r&&(t.preload="none"),t.currentTime=s,r&&(t.preload="auto")}}async function Xb(i){if(!i.isTrusted)return;i.stopImmediatePropagation();let e=i.target;if(!(e!=null&&e.error))return;let{message:t,code:s}=e.error,r=new z(t,s);if(e.src&&s===z.MEDIA_ERR_SRC_NOT_SUPPORTED&&e.readyState===HTMLMediaElement.HAVE_NOTHING){setTimeout(()=>{var n;let a=(n=Mg(e))!=null?n:e.error;(a==null?void 0:a.code)===z.MEDIA_ERR_SRC_NOT_SUPPORTED&&lr(e,r)},500);return}if(e.src&&(s!==z.MEDIA_ERR_DECODE||s!==void 0))try{let{status:n}=await fetch(e.src);r.data={response:{code:n}}}catch{}lr(e,r)}function lr(i,e){var t;e.fatal&&(((t=Xe.get(i))!=null?t:{}).error=e,i.dispatchEvent(new CustomEvent("error",{detail:e})))}function Ag(i){var e,t;if(!(i instanceof CustomEvent)||!(i.detail instanceof z))return;let s=i.target,r=i.detail;!r||!r.fatal||(((e=Xe.get(s))!=null?e:{}).error=r,(t=s.mux)==null||t.emit("error",{player_error_code:r.code,player_error_message:r.message,player_error_context:r.context}))}var Ow=(i,e)=>{var t,s,r;i.fatal?console.error("getErrorFromHlsErrorData()",i):e.debug&&console.warn("getErrorFromHlsErrorData() (non-fatal)",i);let n={[_e.ErrorTypes.NETWORK_ERROR]:z.MEDIA_ERR_NETWORK,[_e.ErrorTypes.MEDIA_ERROR]:z.MEDIA_ERR_DECODE,[_e.ErrorTypes.KEY_SYSTEM_ERROR]:z.MEDIA_ERR_ENCRYPTED},a=u=>[_e.ErrorDetails.KEY_SYSTEM_LICENSE_REQUEST_FAILED,_e.ErrorDetails.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED].includes(u.details)?z.MEDIA_ERR_NETWORK:n[u.type],o=u=>{if(u.type===_e.ErrorTypes.KEY_SYSTEM_ERROR)return Ue.DRM;if(u.type===_e.ErrorTypes.NETWORK_ERROR)return Ue.VIDEO},l,d=a(i);if(d===z.MEDIA_ERR_NETWORK&&i.response){let u=(t=o(i))!=null?t:Ue.VIDEO;l=(s=$u(i.response,u,e,i.fatal))!=null?s:new z("",d,i.fatal)}else if(d===z.MEDIA_ERR_ENCRYPTED)if(i.details===_e.ErrorDetails.KEY_SYSTEM_NO_CONFIGURED_LICENSE){let u=te("Attempting to play DRM-protected content without providing a DRM token.");l=new z(u,z.MEDIA_ERR_ENCRYPTED,i.fatal),l.errorCategory=Ue.DRM,l.muxCode=ne.ENCRYPTED_MISSING_TOKEN}else if(i.details===_e.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 z(u,z.MEDIA_ERR_ENCRYPTED,i.fatal),l.errorCategory=Ue.DRM,l.muxCode=ne.ENCRYPTED_UNSUPPORTED_KEY_SYSTEM}else if(i.details===_e.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 z(u,z.MEDIA_ERR_ENCRYPTED,!0),l.errorCategory=Ue.DRM,l.muxCode=ne.ENCRYPTED_GENERATE_REQUEST_FAILED}else if(i.details===_e.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 z(u,z.MEDIA_ERR_ENCRYPTED,i.fatal),l.errorCategory=Ue.DRM,l.muxCode=ne.ENCRYPTED_UPDATE_LICENSE_FAILED}else if(i.details===_e.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 z(u,z.MEDIA_ERR_ENCRYPTED,i.fatal),l.errorCategory=Ue.DRM,l.muxCode=ne.ENCRYPTED_UPDATE_SERVER_CERT_FAILED}else if(i.details===_e.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 z(u,z.MEDIA_ERR_ENCRYPTED,i.fatal),l.errorCategory=Ue.DRM,l.muxCode=ne.ENCRYPTED_CDM_ERROR}else if(i.details===_e.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 z(u,z.MEDIA_ERR_ENCRYPTED,!1),l.errorCategory=Ue.DRM,l.muxCode=ne.ENCRYPTED_OUTPUT_RESTRICTED}else l=new z(i.error.message,z.MEDIA_ERR_ENCRYPTED,i.fatal),l.errorCategory=Ue.DRM,l.muxCode=ne.ENCRYPTED_ERROR;else l=new z("",d,i.fatal);return l.context||(l.context=`${i.url?`url: ${i.url}
|
|
58
|
+
`),n=(t=((e=r.find(d=>d.startsWith("#EXT-X-PLAYLIST-TYPE")))!=null?e:"").split(":")[1])==null?void 0:t.trim(),a=xb(n),o=kb(n),l;if(a===we.LIVE){let d=r.find(u=>u.startsWith("#EXT-X-PART-INF"));if(d)l=+d.split(":")[1].split("=")[1]*2;else{let u=r.find(h=>h.startsWith("#EXT-X-TARGETDURATION")),c=(s=u==null?void 0:u.split(":"))==null?void 0:s[1];l=+(c!=null?c:6)*3}}return{streamType:a,targetLiveWindow:o,liveEdgeStartOffset:l}},mw=async(i,e)=>{if(e===Cs.MP4)return{streamType:we.ON_DEMAND,targetLiveWindow:Number.NaN,liveEdgeStartOffset:void 0,sessionData:void 0};if(e===Cs.M3U8){let t=await fetch(i);if(!t.ok)return Promise.reject(t);let s=await t.text(),r=await dw(s,t.url);return{...uw(s),...fw(r)}}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}},pw=async(i,e,t=Ku({src:i}))=>{var s,r,n,a;let{streamType:o,targetLiveWindow:l,liveEdgeStartOffset:d,sessionData:u}=await mw(i,t),c=u==null?void 0:u["com.apple.hls.chapters"];(c!=null&&c.URI||c!=null&&c.VALUE.toLocaleLowerCase().startsWith("http"))&&wg((s=c.URI)!=null?s:c.VALUE,e),((r=Xe.get(e))!=null?r:{}).liveEdgeStartOffset=d,((n=Xe.get(e))!=null?n:{}).targetLiveWindow=l,e.dispatchEvent(new CustomEvent("targetlivewindowchange",{composed:!0,bubbles:!0})),((a=Xe.get(e))!=null?a:{}).streamType=o,e.dispatchEvent(new CustomEvent("streamtypechange",{composed:!0,bubbles:!0}))},wg=async(i,e)=>{var t,s;try{let r=await fetch(i);if(!r.ok)throw new Error(`Failed to fetch Mux metadata: ${r.status} ${r.statusText}`);let n=await r.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);((s=Xe.get(e))!=null?s:{}).metadata=a;let o=new CustomEvent("muxmetadata");e.dispatchEvent(o)}catch(r){console.error(r)}},gw=i=>{var e;let t=i.type,s=xb(t),r=kb(t),n,a=!!((e=i.partList)!=null&&e.length);return s===we.LIVE&&(n=a?i.partTarget*2:i.targetduration*3),{streamType:s,targetLiveWindow:r,liveEdgeStartOffset:n,lowLatency:a}},vw=(i,e,t)=>{var s,r,n,a,o,l,d,u;let{streamType:c,targetLiveWindow:h,liveEdgeStartOffset:f,lowLatency:m}=gw(i);if(c===we.LIVE){m?(t.config.backBufferLength=(s=t.userConfig.backBufferLength)!=null?s:4,t.config.maxFragLookUpTolerance=(r=t.userConfig.maxFragLookUpTolerance)!=null?r:.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 v;return g>this.length||g<0||Number.isFinite(e.duration)?e.seekable.end(g):(v=t.liveSyncPosition)!=null?v:e.seekable.end(g)}});((o=Xe.get(e))!=null?o:{}).seekable=p}((l=Xe.get(e))!=null?l:{}).liveEdgeStartOffset=f,((d=Xe.get(e))!=null?d:{}).targetLiveWindow=h,e.dispatchEvent(new CustomEvent("targetlivewindowchange",{composed:!0,bubbles:!0})),((u=Xe.get(e))!=null?u:{}).streamType=c,e.dispatchEvent(new CustomEvent("streamtypechange",{composed:!0,bubbles:!0}))},bb,_b,Bb=(_b=(bb=globalThis==null?void 0:globalThis.navigator)==null?void 0:bb.userAgent)!=null?_b:"",Ab,Sb,Ib,Ew=(Ib=(Sb=(Ab=globalThis==null?void 0:globalThis.navigator)==null?void 0:Ab.userAgentData)==null?void 0:Sb.platform)!=null?Ib:"",yw=Bb.toLowerCase().includes("android")||["x11","android"].some(i=>Ew.toLowerCase().includes(i)),Tw=i=>/^((?!chrome|android).)*safari/i.test(Bb)&&!!i.canPlayType("application/vnd.apple.mpegurl"),Xe=new WeakMap,ws="mux.com",Lb,Rb,$b=(Rb=(Lb=_e).isSupported)==null?void 0:Rb.call(Lb),bw=i=>yw||!Tw(i),Wu=()=>{if(typeof window!="undefined")return Hd.utils.now()},_w=Hd.utils.generateUUID,sl=({playbackId:i,customDomain:e=ws,maxResolution:t,minResolution:s,renditionOrder:r,programStartTime:n,programEndTime:a,assetStartTime:o,assetEndTime:l,playbackToken:d,tokens:{playback:u=d}={},extraSourceParams:c={}}={})=>{if(!i)return;let[h,f=""]=Gu(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),s&&(m.searchParams.set("min_resolution",s),t&&+t.slice(0,-1)<+s.slice(0,-1)&&console.error("minResolution must be <= maxResolution","minResolution",s,"maxResolution",t)),r&&m.searchParams.set("rendition_order",r),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()},qu=i=>{if(!i)return;let[e]=i.split("?");return e||void 0},Yu=i=>{if(!i||!i.startsWith("https://stream."))return;let[e]=new URL(i).pathname.slice(1).split(/\.m3u8|\//);return e||void 0},Aw=i=>{var e,t,s;return(e=i==null?void 0:i.metadata)!=null&&e.video_id?i.metadata.video_id:zb(i)&&(s=(t=qu(i.playbackId))!=null?t:Yu(i.src))!=null?s:i.src},Mg=i=>{var e;return(e=Xe.get(i))==null?void 0:e.error},Hb=i=>{var e;return(e=Xe.get(i))==null?void 0:e.metadata},Hu=i=>{var e,t;return(t=(e=Xe.get(i))==null?void 0:e.streamType)!=null?t:we.UNKNOWN},Gb=i=>{var e,t;return(t=(e=Xe.get(i))==null?void 0:e.targetLiveWindow)!=null?t:Number.NaN},ju=i=>{var e,t;return(t=(e=Xe.get(i))==null?void 0:e.seekable)!=null?t:i.seekable},Kb=i=>{var e;let t=(e=Xe.get(i))==null?void 0:e.liveEdgeStartOffset;if(typeof t!="number")return Number.NaN;let s=ju(i);return s.length?s.end(s.length-1)-t:Number.NaN},Vb=i=>{var e;return(e=Xe.get(i))==null?void 0:e.coreReference},Pg=.034,Sw=(i,e,t=Pg)=>Math.abs(i-e)<=t,Wb=(i,e,t=Pg)=>i>e||Sw(i,e,t),Iw=(i,e=Pg)=>i.paused&&Wb(i.currentTime,i.duration,e),qb=(i,e)=>{var t,s,r;if(!e||!i.buffered.length)return;if(i.readyState>2)return!1;let n=e.currentLevel>=0?(s=(t=e.levels)==null?void 0:t[e.currentLevel])==null?void 0:s.details:(r=e.levels.find(c=>!!c.details))==null?void 0:r.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},Og=(i,e)=>i.ended||i.loop?i.ended:e&&qb(i,e)?!0:Iw(i),Ng=(i,e,t)=>{Ug(e,t,i);let{metadata:s={}}=i,{view_session_id:r=_w()}=s,n=Aw(i);s.view_session_id=r,s.video_id=n,i.metadata=s;let a=h=>{var f;(f=e.mux)==null||f.emit("hb",{view_drm_type:h})};i.drmTypeCb=a,i.fallbackToWebkitFairplay=async()=>{var h;let f=!e.paused,m=e.currentTime;i.useWebkitFairplay=!0;let p=i.muxDataKeepSession;i.muxDataKeepSession=!0;let g=(h=Xe.get(e))==null?void 0:h.coreReference;Ng(i,e,g),i.muxDataKeepSession=p,i.useWebkitFairplay=!1,f&&await e.play().then(()=>{e.currentTime=m}).catch(()=>{}),e.currentTime=m},Xe.set(e,{retryCount:0});let o=Lw(i,e),l=KC(i,e,o);i!=null&&i.muxDataKeepSession&&e!=null&&e.mux&&!e.mux.deleted?o&&e.mux.addHLSJS({hlsjs:o,Hls:o?_e:void 0}):Mw(i,e,o),Pw(i,e,o),jC(e),zC(e);let d=GC(i,e,o);VC(i,e,o),WC(i,e,o);let u={engine:o,setAutoplay:d,setPreload:l},c=Xe.get(e);return c&&(c.coreReference=u),u},Ug=(i,e,t)=>{let s=e==null?void 0:e.engine;i!=null&&i.mux&&!i.mux.deleted&&(t!=null&&t.muxDataKeepSession?s&&i.mux.removeHLSJS():(i.mux.destroy(),delete i.mux)),s&&(s.detachMedia(),s.destroy()),i&&(i.hasAttribute("src")&&(i.removeAttribute("src"),i.load()),i.removeEventListener("error",Xb),i.removeEventListener("error",Ag),i.removeEventListener("durationchange",Qb),Xe.delete(i),i.dispatchEvent(new Event("teardown")))};function Yb(i,e){var t;let s=Ku(i);if(s!==Cs.M3U8)return!0;let r=!s||((t=e.canPlayType(s))!=null?t:!0),{preferPlayback:n}=i,a=n===gi.MSE,o=n===gi.NATIVE,l=$b&&(a||bw(e));return r&&(o||!l)}var Lw=(i,e)=>{let{debug:t,streamType:s,startTime:r=-1,metadata:n,preferCmcd:a,_hlsConfig:o={},maxAutoResolution:l,initialBandwidthEstimateKbps:d}=i,u=Ku(i)===Cs.M3U8,c=Yb(i,e);if(u&&!c&&$b){let h={backBufferLength:30,renderTextTracksNatively:!1,liveDurationInfinity:!0,capLevelOnFPSDrop:!0,...d!=null?{abrEwmaDefaultEstimate:d*1e3}:{}},f=Rw(s),m=xw(i),p=[Jo.QUERY,Jo.HEADER].includes(a)?{useHeaders:a===Jo.HEADER,sessionId:n==null?void 0:n.view_session_id,contentId:n==null?void 0:n.video_id}:void 0,g=ww(i,o),v=new _e({debug:t,startPosition:r,cmcd:p,xhrSetup:(T,y)=>{var b,A;if(a&&a!==Jo.QUERY)return;let R=Ig(y);if(!R.searchParams.has("CMCD"))return;let I=((A=(b=R.searchParams.get("CMCD"))==null?void 0:b.split(","))!=null?A:[]).filter(x=>x.startsWith("sid")||x.startsWith("cid")).join(",");R.searchParams.set("CMCD",I),T.open("GET",R)},...h,...g,...f,...m,...o});return g.capLevelController===_g&&l!==void 0&&_g.setMaxAutoResolution(v,l),v.on(_e.Events.MANIFEST_PARSED,async function(T,y){var b,A;let R=(b=y.sessionData)==null?void 0:b["com.apple.hls.chapters"];(R!=null&&R.URI||R!=null&&R.VALUE.toLocaleLowerCase().startsWith("http"))&&wg((A=R==null?void 0:R.URI)!=null?A:R==null?void 0:R.VALUE,e)}),v}},Rw=i=>i===we.LIVE?{backBufferLength:8}:{},xw=i=>{let{tokens:{drm:e}={},playbackId:t,drmTypeCb:s}=i,r=qu(t);return!e||!r?{}:{emeEnabled:!0,drmSystems:{"com.apple.fps":{licenseUrl:Bu(i,"fairplay"),serverCertificateUrl:jb(i,"fairplay")},"com.widevine.alpha":{licenseUrl:Bu(i,"widevine")},"com.microsoft.playready":{licenseUrl:Bu(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=lw(n);return s==null||s(l),o}))}},kw=async i=>{let e=await fetch(i);return e.status!==200?Promise.reject(e):await e.arrayBuffer()},Dw=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 s=await t.arrayBuffer();return new Uint8Array(s)},Cw=(i,e)=>{let t={mediaEl:e,getAppCertificate:()=>kw(jb(i,"fairplay")).catch(s=>{if(s instanceof Response){let r=$u(s,Ue.DRM,i);return console.error("mediaError",r==null?void 0:r.message,r==null?void 0:r.context),r?Promise.reject(r):Promise.reject(new Error("Unexpected error in app cert request"))}return Promise.reject(s)}),getLicenseKey:s=>Dw(s,Bu(i,"fairplay")).catch(r=>{if(r instanceof Response){let n=$u(r,Ue.DRM,i);return console.error("mediaError",n==null?void 0:n.message,n==null?void 0:n.context),n?Promise.reject(n):Promise.reject(new Error("Unexpected error in license key request"))}return Promise.reject(r)}),saveAndDispatchError:lr,drmTypeCb:()=>{var s;(s=i.drmTypeCb)==null||s.call(i,Fu.FAIRPLAY)}};if(i.useWebkitFairplay)sw(t);else{let s={fallbackToWebkitFairplay:async()=>{var n;await r(),(n=i.fallbackToWebkitFairplay)==null||n.call(i)},...t},r=ow(s)}},Bu=({playbackId:i,tokens:{drm:e}={},customDomain:t=ws},s)=>{let r=qu(i);return`https://license.${t.toLocaleLowerCase().endsWith(ws)?t:ws}/license/${s}/${r}?token=${e}`},jb=({playbackId:i,tokens:{drm:e}={},customDomain:t=ws},s)=>{let r=qu(i);return`https://license.${t.toLocaleLowerCase().endsWith(ws)?t:ws}/appcert/${s}/${r}?token=${e}`},zb=({playbackId:i,src:e,customDomain:t})=>{if(i)return!0;if(typeof e!="string")return!1;let s=window==null?void 0:window.location.href,r=new URL(e,s).hostname.toLocaleLowerCase();return r.includes(ws)||!!t&&r.includes(t.toLocaleLowerCase())},ww=(i,e)=>{let t={};return t.capLevelToPlayerSize=i.capRenditionToPlayerSize,t.capLevelToPlayerSize==null?(t.capLevelController=_g,t.capLevelToPlayerSize=!0):t.capLevelController=Qo,t},Mw=(i,e,t)=>{var s;let{envKey:r,disableTracking:n,muxDataSDK:a=Hd,muxDataSDKOptions:o={}}=i,l=zb(i);if(!n&&(r||l)){let{playerInitTime:d,playerSoftwareName:u,playerSoftwareVersion:c,beaconCollectionDomain:h,debug:f,disableCookies:m}=i,p={...i.metadata,video_title:((s=i==null?void 0:i.metadata)==null?void 0:s.video_title)||void 0},g=v=>typeof v.player_error_code=="string"?!1:typeof i.errorTranslator=="function"?i.errorTranslator(v):v;a.monitor(e,{debug:f,beaconCollectionDomain:h,hlsjs:t,Hls:t?_e:void 0,automaticErrorTracking:!1,errorTranslator:g,disableCookies:m,...o,data:{...r?{env_key:r}:{},player_software_name:u,player_software:u,player_software_version:c,player_init_time:d,...p}})}},Pw=(i,e,t)=>{var s,r;let n=Yb(i,e),{src:a,customDomain:o=ws}=i,l=()=>{e.ended||i.disablePseudoEnded||!Og(e,t)||(qb(e,t)?e.currentTime=e.buffered.end(e.buffered.length-1):e.dispatchEvent(new Event("ended")))},d,u,c=()=>{let h=ju(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(mt(e,"durationchange",c),e&&n){let h=Ku(i);if(typeof a=="string"){if(a.endsWith(".mp4")&&a.includes(o)){let p=Yu(a),g=new URL(`https://stream.${o}/${p}/metadata.json`);wg(g.toString(),e)}let f=()=>{if(Hu(e)!==we.LIVE||Number.isFinite(e.duration))return;let p=setInterval(c,1e3);e.addEventListener("teardown",()=>{clearInterval(p)},{once:!0}),mt(e,"durationchange",()=>{Number.isFinite(e.duration)&&clearInterval(p)})},m=async()=>pw(a,e,h).then(f).catch(p=>{if(p instanceof Response){let g=$u(p,Ue.VIDEO,i);if(g){lr(e,g);return}}else p instanceof Error});if(e.preload==="none"){let p=()=>{m(),e.removeEventListener("loadedmetadata",g)},g=()=>{m(),e.removeEventListener("play",p)};mt(e,"play",p,{once:!0}),mt(e,"loadedmetadata",g,{once:!0})}else m();(s=i.tokens)!=null&&s.drm?Cw(i,e):mt(e,"encrypted",()=>{let p=te("Attempting to play DRM-protected content without providing a DRM token."),g=new z(p,z.MEDIA_ERR_ENCRYPTED,!0);g.errorCategory=Ue.DRM,g.muxCode=ne.ENCRYPTED_MISSING_TOKEN,lr(e,g)},{once:!0}),e.setAttribute("src",a),i.startTime&&(((r=Xe.get(e))!=null?r:{}).startTime=i.startTime,e.addEventListener("durationchange",Qb,{once:!0}))}else e.removeAttribute("src");e.addEventListener("error",Xb),e.addEventListener("error",Ag),e.addEventListener("emptied",()=>{e.querySelectorAll("track[data-removeondestroy]").forEach(f=>{f.remove()})},{once:!0}),mt(e,"pause",l),mt(e,"seeked",l),mt(e,"play",()=>{e.ended||Wb(e.currentTime,e.duration)&&(e.currentTime=e.seekable.length?e.seekable.start(0):0)})}else t&&a?(t.once(_e.Events.LEVEL_LOADED,(h,f)=>{vw(f.details,e,t),c(),Hu(e)===we.LIVE&&!Number.isFinite(e.duration)&&(t.on(_e.Events.LEVEL_UPDATED,c),mt(e,"durationchange",()=>{Number.isFinite(e.duration)&&t.off(_e.Events.LEVELS_UPDATED,c)}))}),t.on(_e.Events.ERROR,(h,f)=>{var m,p;let g=Ow(f,i);if(g.muxCode===ne.NETWORK_NOT_READY){let v=(m=Xe.get(e))!=null?m:{},T=(p=v.retryCount)!=null?p:0;if(T<6){let y=T===0?5e3:6e4,b=new z(`Retrying in ${y/1e3} seconds...`,g.code,g.fatal);Object.assign(b,g),lr(e,b);let A=setTimeout(()=>{v.retryCount=T+1,f.details==="manifestLoadError"&&f.url&&t.loadSource(f.url)},y);e.addEventListener("teardown",()=>clearTimeout(A),{once:!0});return}else{v.retryCount=0;let y=new z('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),lr(e,y);return}}lr(e,g)}),t.on(_e.Events.MANIFEST_LOADED,()=>{let h=Xe.get(e);h&&h.error&&(h.error=null,h.retryCount=0,e.dispatchEvent(new Event("emptied")),e.dispatchEvent(new Event("loadstart")))}),e.addEventListener("error",Ag),mt(e,"waiting",l),qC(i,t),YC(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 Qb(i){var e;let t=i.target,s=(e=Xe.get(t))==null?void 0:e.startTime;if(s&&CC(t.seekable,t.duration,s)){let r=t.preload==="auto";r&&(t.preload="none"),t.currentTime=s,r&&(t.preload="auto")}}async function Xb(i){if(!i.isTrusted)return;i.stopImmediatePropagation();let e=i.target;if(!(e!=null&&e.error))return;let{message:t,code:s}=e.error,r=new z(t,s);if(e.src&&s===z.MEDIA_ERR_SRC_NOT_SUPPORTED&&e.readyState===HTMLMediaElement.HAVE_NOTHING){setTimeout(()=>{var n;let a=(n=Mg(e))!=null?n:e.error;(a==null?void 0:a.code)===z.MEDIA_ERR_SRC_NOT_SUPPORTED&&lr(e,r)},500);return}if(e.src&&(s!==z.MEDIA_ERR_DECODE||s!==void 0))try{let{status:n}=await fetch(e.src);r.data={response:{code:n}}}catch{}lr(e,r)}function lr(i,e){var t;e.fatal&&(((t=Xe.get(i))!=null?t:{}).error=e,i.dispatchEvent(new CustomEvent("error",{detail:e})))}function Ag(i){var e,t;if(!(i instanceof CustomEvent)||!(i.detail instanceof z))return;let s=i.target,r=i.detail;!r||!r.fatal||(((e=Xe.get(s))!=null?e:{}).error=r,(t=s.mux)==null||t.emit("error",{player_error_code:r.code,player_error_message:r.message,player_error_context:r.context}))}var Ow=(i,e)=>{var t,s,r;i.fatal?console.error("getErrorFromHlsErrorData()",i):e.debug&&console.warn("getErrorFromHlsErrorData() (non-fatal)",i);let n={[_e.ErrorTypes.NETWORK_ERROR]:z.MEDIA_ERR_NETWORK,[_e.ErrorTypes.MEDIA_ERROR]:z.MEDIA_ERR_DECODE,[_e.ErrorTypes.KEY_SYSTEM_ERROR]:z.MEDIA_ERR_ENCRYPTED},a=u=>[_e.ErrorDetails.KEY_SYSTEM_LICENSE_REQUEST_FAILED,_e.ErrorDetails.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED].includes(u.details)?z.MEDIA_ERR_NETWORK:n[u.type],o=u=>{if(u.type===_e.ErrorTypes.KEY_SYSTEM_ERROR)return Ue.DRM;if(u.type===_e.ErrorTypes.NETWORK_ERROR)return Ue.VIDEO},l,d=a(i);if(d===z.MEDIA_ERR_NETWORK&&i.response){let u=(t=o(i))!=null?t:Ue.VIDEO;l=(s=$u(i.response,u,e,i.fatal))!=null?s:new z("",d,i.fatal)}else if(d===z.MEDIA_ERR_ENCRYPTED)if(i.details===_e.ErrorDetails.KEY_SYSTEM_NO_CONFIGURED_LICENSE){let u=te("Attempting to play DRM-protected content without providing a DRM token.");l=new z(u,z.MEDIA_ERR_ENCRYPTED,i.fatal),l.errorCategory=Ue.DRM,l.muxCode=ne.ENCRYPTED_MISSING_TOKEN}else if(i.details===_e.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 z(u,z.MEDIA_ERR_ENCRYPTED,i.fatal),l.errorCategory=Ue.DRM,l.muxCode=ne.ENCRYPTED_UNSUPPORTED_KEY_SYSTEM}else if(i.details===_e.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 z(u,z.MEDIA_ERR_ENCRYPTED,!0),l.errorCategory=Ue.DRM,l.muxCode=ne.ENCRYPTED_GENERATE_REQUEST_FAILED}else if(i.details===_e.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 z(u,z.MEDIA_ERR_ENCRYPTED,i.fatal),l.errorCategory=Ue.DRM,l.muxCode=ne.ENCRYPTED_UPDATE_LICENSE_FAILED}else if(i.details===_e.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 z(u,z.MEDIA_ERR_ENCRYPTED,i.fatal),l.errorCategory=Ue.DRM,l.muxCode=ne.ENCRYPTED_UPDATE_SERVER_CERT_FAILED}else if(i.details===_e.ErrorDetails.KEY_SYSTEM_STATUS_INTERNAL_ERROR){let u=te("The DRM Content Decryption Module system had an internal failure. Try reloading the page, updating your browser, or playing in another browser.");l=new z(u,z.MEDIA_ERR_ENCRYPTED,i.fatal),l.errorCategory=Ue.DRM,l.muxCode=ne.ENCRYPTED_CDM_ERROR}else if(i.details===_e.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 z(u,z.MEDIA_ERR_ENCRYPTED,!1),l.errorCategory=Ue.DRM,l.muxCode=ne.ENCRYPTED_OUTPUT_RESTRICTED}else l=new z(i.error.message,z.MEDIA_ERR_ENCRYPTED,i.fatal),l.errorCategory=Ue.DRM,l.muxCode=ne.ENCRYPTED_ERROR;else l=new z("",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}
|