@evercam/ui 0.0.53-beta.2 → 0.0.53-beta.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.mjs +2 -2
- package/dist/index.umd.js +1 -1
- package/dist/index.umd.js.map +1 -1
- package/dist/style.css +1 -1
- package/dist/web-types.json +1 -1
- package/package.json +1 -1
package/dist/index.umd.js
CHANGED
|
@@ -23,7 +23,7 @@
|
|
|
23
23
|
`),c=[],u=e?wc(e.baseTime,e.timescale):0;let h="00:00.000",d=0,f=0,g,m=!0;o.oncue=function(y){const v=t[i];let T=t.ccOffset;const x=(d-u)/9e4;if(v!=null&&v.new&&(f!==void 0?T=t.ccOffset=v.start:uu(t,i,x)),x){if(!e){g=new Error("Missing initPTS for VTT MPEGTS");return}T=x-t.presentationOffset}const L=y.endTime-y.startTime,E=be((y.startTime+T-f)*9e4,r*9e4)/9e4;y.startTime=Math.max(E,0),y.endTime=Math.max(E+L,0);const w=y.text.trim();y.text=decodeURIComponent(encodeURIComponent(w)),y.id||(y.id=is(y.startTime,y.endTime,w)),y.endTime>0&&c.push(y)},o.onparsingerror=function(y){g=y},o.onflush=function(){if(g){a(g);return}n(c)},l.forEach(y=>{if(m)if(es(y,"X-TIMESTAMP-MAP=")){m=!1,y.slice(16).split(",").forEach(v=>{es(v,"LOCAL:")?h=v.slice(6):es(v,"MPEGTS:")&&(d=parseInt(v.slice(7)))});try{f=cu(h)/1e3}catch(v){g=v}return}else y===""&&(m=!1);o.parse(y+`
|
|
24
24
|
`)}),o.flush()}const ss="stpp.ttml.im1t",Bn=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,Un=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,du={left:"start",center:"center",right:"end",start:"start",end:"end"};function $n(s,e,t,i){const r=X(new Uint8Array(s),["mdat"]);if(r.length===0){i(new Error("Could not parse IMSC1 mdat"));return}const n=r.map(o=>Ie(o)),a=Ic(e.baseTime,1,e.timescale);try{n.forEach(o=>t(fu(o,a)))}catch(o){i(o)}}function fu(s,e){const r=new DOMParser().parseFromString(s,"text/xml").getElementsByTagName("tt")[0];if(!r)throw new Error("Invalid ttml");const n={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:0},a=Object.keys(n).reduce((h,d)=>(h[d]=r.getAttribute(`ttp:${d}`)||n[d],h),{}),o=r.getAttribute("xml:space")!=="preserve",l=Gn(rs(r,"styling","style")),c=Gn(rs(r,"layout","region")),u=rs(r,"body","[begin]");return[].map.call(u,h=>{const d=Hn(h,o);if(!d||!h.hasAttribute("begin"))return null;const f=as(h.getAttribute("begin"),a),g=as(h.getAttribute("dur"),a);let m=as(h.getAttribute("end"),a);if(f===null)throw Vn(h);if(m===null){if(g===null)throw Vn(h);m=f+g}const y=new Qi(f-e,m-e,d);y.id=is(y.startTime,y.endTime,y.text);const v=c[h.getAttribute("region")],T=l[h.getAttribute("style")],x=gu(v,T,l),{textAlign:L}=x;if(L){const E=du[L];E&&(y.lineAlign=E),y.align=L}return oe(y,x),y}).filter(h=>h!==null)}function rs(s,e,t){const i=s.getElementsByTagName(e)[0];return i?[].slice.call(i.querySelectorAll(t)):[]}function Gn(s){return s.reduce((e,t)=>{const i=t.getAttribute("xml:id");return i&&(e[i]=t),e},{})}function Hn(s,e){return[].slice.call(s.childNodes).reduce((t,i,r)=>{var n;return i.nodeName==="br"&&r?t+`
|
|
25
25
|
`:(n=i.childNodes)!=null&&n.length?Hn(i,e):e?t+i.textContent.trim().replace(/\s+/g," "):t+i.textContent},"")}function gu(s,e,t){const i="http://www.w3.org/ns/ttml#styling";let r=null;const n=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],a=s!=null&&s.hasAttribute("style")?s.getAttribute("style"):null;return a&&t.hasOwnProperty(a)&&(r=t[a]),n.reduce((o,l)=>{const c=ns(e,i,l)||ns(s,i,l)||ns(r,i,l);return c&&(o[l]=c),o},{})}function ns(s,e,t){return s&&s.hasAttributeNS(e,t)?s.getAttributeNS(e,t):null}function Vn(s){return new Error(`Could not parse ttml timestamp ${s}`)}function as(s,e){if(!s)return null;let t=Fn(s);return t===null&&(Bn.test(s)?t=mu(s,e):Un.test(s)&&(t=pu(s,e))),t}function mu(s,e){const t=Bn.exec(s),i=(t[4]|0)+(t[5]|0)/e.subFrameRate;return(t[1]|0)*3600+(t[2]|0)*60+(t[3]|0)+i/e.frameRate}function pu(s,e){const t=Un.exec(s),i=Number(t[1]);switch(t[2]){case"h":return i*3600;case"m":return i*60;case"ms":return i*1e3;case"f":return i/e.frameRate;case"t":return i/e.tickRate}return i}class yu{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=zn(),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(p.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(p.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(p.FRAG_LOADING,this.onFragLoading,this),e.on(p.FRAG_LOADED,this.onFragLoaded,this),e.on(p.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.on(p.FRAG_DECRYPTED,this.onFragDecrypted,this),e.on(p.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(p.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.on(p.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){const{hls:e}=this;e.off(p.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(p.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(p.FRAG_LOADING,this.onFragLoading,this),e.off(p.FRAG_LOADED,this.onFragLoaded,this),e.off(p.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.off(p.FRAG_DECRYPTED,this.onFragDecrypted,this),e.off(p.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(p.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.off(p.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=null,this.cea608Parser1=this.cea608Parser2=void 0}initCea608Parsers(){if(this.config.enableCEA708Captions&&(!this.cea608Parser1||!this.cea608Parser2)){const e=new Xt(this,"textTrack1"),t=new Xt(this,"textTrack2"),i=new Xt(this,"textTrack3"),r=new Xt(this,"textTrack4");this.cea608Parser1=new kn(1,e,t),this.cea608Parser2=new kn(3,i,r)}}addCues(e,t,i,r,n){let a=!1;for(let o=n.length;o--;){const l=n[o],c=vu(l[0],l[1],t,i);if(c>=0&&(l[0]=Math.min(l[0],t),l[1]=Math.max(l[1],i),a=!0,c/(i-t)>.5))return}if(a||n.push([t,i]),this.config.renderTextTracksNatively){const o=this.captionsTracks[e];this.Cues.newCue(o,t,i,r)}else{const o=this.Cues.newCue(null,t,i,r);this.hls.trigger(p.CUES_PARSED,{type:"captions",cues:o,track:e})}}onInitPtsFound(e,{frag:t,id:i,initPTS:r,timescale:n}){const{unparsedVttFrags:a}=this;i==="main"&&(this.initPTS[t.cc]={baseTime:r,timescale:n}),a.length&&(this.unparsedVttFrags=[],a.forEach(o=>{this.onFragLoaded(p.FRAG_LOADED,o)}))}getExistingTrack(e,t){const{media:i}=this;if(i)for(let r=0;r<i.textTracks.length;r++){const n=i.textTracks[r];if(Wn(n,{name:e,lang:t,attrs:{}}))return n}return null}createCaptionsTrack(e){this.config.renderTextTracksNatively?this.createNativeTrack(e):this.createNonNativeTrack(e)}createNativeTrack(e){if(this.captionsTracks[e])return;const{captionsProperties:t,captionsTracks:i,media:r}=this,{label:n,languageCode:a}=t[e],o=this.getExistingTrack(n,a);if(o)i[e]=o,tt(i[e]),kr(i[e],r);else{const l=this.createTextTrack("captions",n,a);l&&(l[e]=!0,i[e]=l)}}createNonNativeTrack(e){if(this.nonNativeCaptionsTracks[e])return;const t=this.captionsProperties[e];if(!t)return;const i=t.label,r={_id:e,label:i,kind:"captions",default:t.media?!!t.media.default:!1,closedCaptions:t.media};this.nonNativeCaptionsTracks[e]=r,this.hls.trigger(p.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[r]})}createTextTrack(e,t,i){const r=this.media;if(r)return r.addTextTrack(e,t,i)}onMediaAttaching(e,t){this.media=t.media,this._cleanTracks()}onMediaDetaching(){const{captionsTracks:e}=this;Object.keys(e).forEach(t=>{tt(e[t]),delete e[t]}),this.nonNativeCaptionsTracks={}}onManifestLoading(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=zn(),this._cleanTracks(),this.tracks=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.textTracks=[],this.unparsedVttFrags=[],this.initPTS=[],this.cea608Parser1&&this.cea608Parser2&&(this.cea608Parser1.reset(),this.cea608Parser2.reset())}_cleanTracks(){const{media:e}=this;if(!e)return;const t=e.textTracks;if(t)for(let i=0;i<t.length;i++)tt(t[i])}onSubtitleTracksUpdated(e,t){const i=t.subtitleTracks||[],r=i.some(n=>n.textCodec===ss);if(this.config.enableWebVTT||r&&this.config.enableIMSC1){if(bn(this.tracks,i)){this.tracks=i;return}if(this.textTracks=[],this.tracks=i,this.config.renderTextTracksNatively){const a=this.media,o=a?Ft(a.textTracks):null;if(this.tracks.forEach((l,c)=>{let u;if(o){let h=null;for(let d=0;d<o.length;d++)if(o[d]&&Wn(o[d],l)){h=o[d],o[d]=null;break}h&&(u=h)}if(u)tt(u);else{const h=Kn(l);u=this.createTextTrack(h,l.name,l.lang),u&&(u.mode="disabled")}u&&this.textTracks.push(u)}),o!=null&&o.length){const l=o.filter(c=>c!==null).map(c=>c.label);l.length&&S.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){const a=this.tracks.map(o=>({label:o.name,kind:o.type.toLowerCase(),default:o.default,subtitleTrack:o}));this.hls.trigger(p.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:a})}}}onManifestLoaded(e,t){this.config.enableCEA708Captions&&t.captions&&t.captions.forEach(i=>{const r=/(?:CC|SERVICE)([1-4])/.exec(i.instreamId);if(!r)return;const n=`textTrack${r[1]}`,a=this.captionsProperties[n];a&&(a.label=i.name,i.lang&&(a.languageCode=i.lang),a.media=i)})}closedCaptionsForLevel(e){const t=this.hls.levels[e.level];return t==null?void 0:t.attrs["CLOSED-CAPTIONS"]}onFragLoading(e,t){this.initCea608Parsers();const{cea608Parser1:i,cea608Parser2:r,lastCc:n,lastSn:a,lastPartIndex:o}=this;if(!(!this.enabled||!i||!r)&&t.frag.type===j.MAIN){var l,c;const{cc:u,sn:h}=t.frag,d=(l=t==null||(c=t.part)==null?void 0:c.index)!=null?l:-1;h===a+1||h===a&&d===o+1||u===n||(i.reset(),r.reset()),this.lastCc=u,this.lastSn=h,this.lastPartIndex=d}}onFragLoaded(e,t){const{frag:i,payload:r}=t;if(i.type===j.SUBTITLE)if(r.byteLength){const n=i.decryptdata,a="stats"in t;if(n==null||!n.encrypted||a){const o=this.tracks[i.level],l=this.vttCCs;l[i.cc]||(l[i.cc]={start:i.start,prevCC:this.prevCC,new:!0},this.prevCC=i.cc),o&&o.textCodec===ss?this._parseIMSC1(i,r):this._parseVTTs(t)}}else this.hls.trigger(p.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,error:new Error("Empty subtitle payload")})}_parseIMSC1(e,t){const i=this.hls;$n(t,this.initPTS[e.cc],r=>{this._appendCues(r,e.level),i.trigger(p.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:e})},r=>{S.log(`Failed to parse IMSC1: ${r}`),i.trigger(p.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e,error:r})})}_parseVTTs(e){var t;const{frag:i,payload:r}=e,{initPTS:n,unparsedVttFrags:a}=this,o=n.length-1;if(!n[i.cc]&&o===-1){a.push(e);return}const l=this.hls,c=(t=i.initSegment)!=null&&t.data?Se(i.initSegment.data,new Uint8Array(r)):r;hu(c,this.initPTS[i.cc],this.vttCCs,i.cc,i.start,u=>{this._appendCues(u,i.level),l.trigger(p.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:i})},u=>{const h=u.message==="Missing initPTS for VTT MPEGTS";h?a.push(e):this._fallbackToIMSC1(i,r),S.log(`Failed to parse VTT cue: ${u}`),!(h&&o>i.cc)&&l.trigger(p.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,error:u})})}_fallbackToIMSC1(e,t){const i=this.tracks[e.level];i.textCodec||$n(t,this.initPTS[e.cc],()=>{i.textCodec=ss,this._parseIMSC1(e,t)},()=>{i.textCodec="wvtt"})}_appendCues(e,t){const i=this.hls;if(this.config.renderTextTracksNatively){const r=this.textTracks[t];if(!r||r.mode==="disabled")return;e.forEach(n=>Pr(r,n))}else{const r=this.tracks[t];if(!r)return;const n=r.default?"default":"subtitles"+t;i.trigger(p.CUES_PARSED,{type:"subtitles",cues:e,track:n})}}onFragDecrypted(e,t){const{frag:i}=t;i.type===j.SUBTITLE&&this.onFragLoaded(p.FRAG_LOADED,t)}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(e,t){this.initCea608Parsers();const{cea608Parser1:i,cea608Parser2:r}=this;if(!this.enabled||!i||!r)return;const{frag:n,samples:a}=t;if(!(n.type===j.MAIN&&this.closedCaptionsForLevel(n)==="NONE"))for(let o=0;o<a.length;o++){const l=a[o].bytes;if(l){const c=this.extractCea608Data(l);i.addData(a[o].pts,c[0]),r.addData(a[o].pts,c[1])}}}onBufferFlushing(e,{startOffset:t,endOffset:i,endOffsetSubtitles:r,type:n}){const{media:a}=this;if(!(!a||a.currentTime<i)){if(!n||n==="video"){const{captionsTracks:o}=this;Object.keys(o).forEach(l=>_i(o[l],t,i))}if(this.config.renderTextTracksNatively&&t===0&&r!==void 0){const{textTracks:o}=this;Object.keys(o).forEach(l=>_i(o[l],t,r))}}}extractCea608Data(e){const t=[[],[]],i=e[0]&31;let r=2;for(let n=0;n<i;n++){const a=e[r++],o=127&e[r++],l=127&e[r++];if(o===0&&l===0)continue;if((4&a)!==0){const u=3&a;(u===0||u===1)&&(t[u].push(o),t[u].push(l))}}return t}}function Kn(s){return s.characteristics&&/transcribes-spoken-dialog/gi.test(s.characteristics)&&/describes-music-and-sound/gi.test(s.characteristics)?"captions":"subtitles"}function Wn(s,e){return!!s&&s.kind===Kn(e)&&Xi(e,s)}function vu(s,e,t,i){return Math.min(e,i)-Math.max(s,t)}function zn(){return{ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}}}class os{constructor(e){this.hls=void 0,this.autoLevelCapping=void 0,this.firstLevel=void 0,this.media=void 0,this.restrictedLevels=void 0,this.timer=void 0,this.clientRect=void 0,this.streamController=void 0,this.hls=e,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.firstLevel=-1,this.media=null,this.restrictedLevels=[],this.timer=void 0,this.clientRect=null,this.registerListeners()}setStreamController(e){this.streamController=e}destroy(){this.hls&&this.unregisterListener(),this.timer&&this.stopCapping(),this.media=null,this.clientRect=null,this.hls=this.streamController=null}registerListeners(){const{hls:e}=this;e.on(p.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.on(p.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(p.MANIFEST_PARSED,this.onManifestParsed,this),e.on(p.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(p.BUFFER_CODECS,this.onBufferCodecs,this),e.on(p.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListener(){const{hls:e}=this;e.off(p.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.off(p.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(p.MANIFEST_PARSED,this.onManifestParsed,this),e.off(p.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(p.BUFFER_CODECS,this.onBufferCodecs,this),e.off(p.MEDIA_DETACHING,this.onMediaDetaching,this)}onFpsDropLevelCapping(e,t){const i=this.hls.levels[t.droppedLevel];this.isLevelAllowed(i)&&this.restrictedLevels.push({bitrate:i.bitrate,height:i.height,width:i.width})}onMediaAttaching(e,t){this.media=t.media instanceof HTMLVideoElement?t.media:null,this.clientRect=null,this.timer&&this.hls.levels.length&&this.detectPlayerSize()}onManifestParsed(e,t){const i=this.hls;this.restrictedLevels=[],this.firstLevel=t.firstLevel,i.config.capLevelToPlayerSize&&t.video&&this.startCapping()}onLevelsUpdated(e,t){this.timer&&K(this.autoLevelCapping)&&this.detectPlayerSize()}onBufferCodecs(e,t){this.hls.config.capLevelToPlayerSize&&t.video&&this.startCapping()}onMediaDetaching(){this.stopCapping()}detectPlayerSize(){if(this.media){if(this.mediaHeight<=0||this.mediaWidth<=0){this.clientRect=null;return}const e=this.hls.levels;if(e.length){const t=this.hls,i=this.getMaxLevel(e.length-1);i!==this.autoLevelCapping&&S.log(`Setting autoLevelCapping to ${i}: ${e[i].height}p@${e[i].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`),t.autoLevelCapping=i,t.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=t.autoLevelCapping}}}getMaxLevel(e){const t=this.hls.levels;if(!t.length)return-1;const i=t.filter((r,n)=>this.isLevelAllowed(r)&&n<=e);return this.clientRect=null,os.getMaxLevelByMediaSize(i,this.mediaWidth,this.mediaHeight)}startCapping(){this.timer||(this.autoLevelCapping=Number.POSITIVE_INFINITY,self.clearInterval(this.timer),this.timer=self.setInterval(this.detectPlayerSize.bind(this),1e3),this.detectPlayerSize())}stopCapping(){this.restrictedLevels=[],this.firstLevel=-1,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer&&(self.clearInterval(this.timer),this.timer=void 0)}getDimensions(){if(this.clientRect)return this.clientRect;const e=this.media,t={width:0,height:0};if(e){const i=e.getBoundingClientRect();t.width=i.width,t.height=i.height,!t.width&&!t.height&&(t.width=i.right-i.left||e.width||0,t.height=i.bottom-i.top||e.height||0)}return this.clientRect=t,t}get mediaWidth(){return this.getDimensions().width*this.contentScaleFactor}get mediaHeight(){return this.getDimensions().height*this.contentScaleFactor}get contentScaleFactor(){let e=1;if(!this.hls.config.ignoreDevicePixelRatio)try{e=self.devicePixelRatio}catch{}return e}isLevelAllowed(e){return!this.restrictedLevels.some(i=>e.bitrate===i.bitrate&&e.width===i.width&&e.height===i.height)}static getMaxLevelByMediaSize(e,t,i){if(!(e!=null&&e.length))return-1;const r=(o,l)=>l?o.width!==l.width||o.height!==l.height:!0;let n=e.length-1;const a=Math.max(t,i);for(let o=0;o<e.length;o+=1){const l=e[o];if((l.width>=a||l.height>=a)&&r(l,e[o+1])){n=o;break}}return n}}class xu{constructor(e){this.hls=void 0,this.isVideoPlaybackQualityAvailable=!1,this.timer=void 0,this.media=null,this.lastTime=void 0,this.lastDroppedFrames=0,this.lastDecodedFrames=0,this.streamController=void 0,this.hls=e,this.registerListeners()}setStreamController(e){this.streamController=e}registerListeners(){this.hls.on(p.MEDIA_ATTACHING,this.onMediaAttaching,this)}unregisterListeners(){this.hls.off(p.MEDIA_ATTACHING,this.onMediaAttaching,this)}destroy(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null}onMediaAttaching(e,t){const i=this.hls.config;if(i.capLevelOnFPSDrop){const r=t.media instanceof self.HTMLVideoElement?t.media:null;this.media=r,r&&typeof r.getVideoPlaybackQuality=="function"&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),i.fpsDroppedMonitoringPeriod)}}checkFPS(e,t,i){const r=performance.now();if(t){if(this.lastTime){const n=r-this.lastTime,a=i-this.lastDroppedFrames,o=t-this.lastDecodedFrames,l=1e3*a/n,c=this.hls;if(c.trigger(p.FPS_DROP,{currentDropped:a,currentDecoded:o,totalDroppedFrames:i}),l>0&&a>c.config.fpsDroppedMonitoringThreshold*o){let u=c.currentLevel;S.warn("drop FPS ratio greater than max allowed value for currentLevel: "+u),u>0&&(c.autoLevelCapping===-1||c.autoLevelCapping>=u)&&(u=u-1,c.trigger(p.FPS_DROP_LEVEL_CAPPING,{level:u,droppedLevel:c.currentLevel}),c.autoLevelCapping=u,this.streamController.nextLevelSwitch())}}this.lastTime=r,this.lastDroppedFrames=i,this.lastDecodedFrames=t}}checkFPSInterval(){const e=this.media;if(e)if(this.isVideoPlaybackQualityAvailable){const t=e.getVideoPlaybackQuality();this.checkFPS(e,t.totalVideoFrames,t.droppedVideoFrames)}else this.checkFPS(e,e.webkitDecodedFrameCount,e.webkitDroppedFrameCount)}}const Qt="[eme]";class ht{constructor(e){this.hls=void 0,this.config=void 0,this.media=null,this.keyFormatPromise=null,this.keySystemAccessPromises={},this._requestLicenseFailureCount=0,this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},this.setMediaKeysQueue=ht.CDMCleanupPromise?[ht.CDMCleanupPromise]:[],this.onMediaEncrypted=this._onMediaEncrypted.bind(this),this.onWaitingForKey=this._onWaitingForKey.bind(this),this.debug=S.debug.bind(S,Qt),this.log=S.log.bind(S,Qt),this.warn=S.warn.bind(S,Qt),this.error=S.error.bind(S,Qt),this.hls=e,this.config=e.config,this.registerListeners()}destroy(){this.unregisterListeners(),this.onMediaDetached();const e=this.config;e.requestMediaKeySystemAccessFunc=null,e.licenseXhrSetup=e.licenseResponseCallback=void 0,e.drmSystems=e.drmSystemOptions={},this.hls=this.onMediaEncrypted=this.onWaitingForKey=this.keyIdToKeySessionPromise=null,this.config=null}registerListeners(){this.hls.on(p.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(p.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(p.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(p.MANIFEST_LOADED,this.onManifestLoaded,this)}unregisterListeners(){this.hls.off(p.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(p.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(p.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(p.MANIFEST_LOADED,this.onManifestLoaded,this)}getLicenseServerUrl(e){const{drmSystems:t,widevineLicenseUrl:i}=this.config,r=t[e];if(r)return r.licenseUrl;if(e===ne.WIDEVINE&&i)return i;throw new Error(`no license server URL configured for key-system "${e}"`)}getServerCertificateUrl(e){const{drmSystems:t}=this.config,i=t[e];if(i)return i.serverCertificateUrl;this.log(`No Server Certificate in config.drmSystems["${e}"]`)}attemptKeySystemAccess(e){const t=this.hls.levels,i=(a,o,l)=>!!a&&l.indexOf(a)===o,r=t.map(a=>a.audioCodec).filter(i),n=t.map(a=>a.videoCodec).filter(i);return r.length+n.length===0&&n.push("avc1.42e01e"),new Promise((a,o)=>{const l=c=>{const u=c.shift();this.getMediaKeysPromise(u,r,n).then(h=>a({keySystem:u,mediaKeys:h})).catch(h=>{c.length?l(c):h instanceof Ae?o(h):o(new Ae({type:q.KEY_SYSTEM_ERROR,details:_.KEY_SYSTEM_NO_ACCESS,error:h,fatal:!0},h.message))})};l(e)})}requestMediaKeySystemAccess(e,t){const{requestMediaKeySystemAccessFunc:i}=this.config;if(typeof i!="function"){let r=`Configured requestMediaKeySystemAccess is not a function ${i}`;return sr===null&&self.location.protocol==="http:"&&(r=`navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`),Promise.reject(new Error(r))}return i(e,t)}getMediaKeysPromise(e,t,i){const r=Io(e,t,i,this.config.drmSystemOptions),n=this.keySystemAccessPromises[e];let a=n==null?void 0:n.keySystemAccess;if(!a){this.log(`Requesting encrypted media "${e}" key-system access with config: ${JSON.stringify(r)}`),a=this.requestMediaKeySystemAccess(e,r);const o=this.keySystemAccessPromises[e]={keySystemAccess:a};return a.catch(l=>{this.log(`Failed to obtain access to key-system "${e}": ${l}`)}),a.then(l=>{this.log(`Access for key-system "${l.keySystem}" obtained`);const c=this.fetchServerCertificate(e);return this.log(`Create media-keys for "${e}"`),o.mediaKeys=l.createMediaKeys().then(u=>(this.log(`Media-keys created for "${e}"`),c.then(h=>h?this.setMediaKeysServerCertificate(u,e,h):u))),o.mediaKeys.catch(u=>{this.error(`Failed to create media-keys for "${e}"}: ${u}`)}),o.mediaKeys})}return a.then(()=>n.mediaKeys)}createMediaKeySessionContext({decryptdata:e,keySystem:t,mediaKeys:i}){this.log(`Creating key-system session "${t}" keyId: ${we.hexDump(e.keyId||[])}`);const r=i.createSession(),n={decryptdata:e,keySystem:t,mediaKeys:i,mediaKeysSession:r,keyStatus:"status-pending"};return this.mediaKeySessions.push(n),n}renewKeySession(e){const t=e.decryptdata;if(t.pssh){const i=this.createMediaKeySessionContext(e),r=this.getKeyIdString(t),n="cenc";this.keyIdToKeySessionPromise[r]=this.generateRequestWithPreferredKeySession(i,n,t.pssh,"expired")}else this.warn("Could not renew expired session. Missing pssh initData.");this.removeSession(e)}getKeyIdString(e){if(!e)throw new Error("Could not read keyId of undefined decryptdata");if(e.keyId===null)throw new Error("keyId is null");return we.hexDump(e.keyId)}updateKeySession(e,t){var i;const r=e.mediaKeysSession;return this.log(`Updating key-session "${r.sessionId}" for keyID ${we.hexDump(((i=e.decryptdata)==null?void 0:i.keyId)||[])}
|
|
26
|
-
} (data length: ${t&&t.byteLength})`),r.update(t)}selectKeySystemFormat(e){const t=Object.keys(e.levelkeys||{});return this.keyFormatPromise||(this.log(`Selecting key-system from fragment (sn: ${e.sn} ${e.type}: ${e.level}) key formats ${t.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(t)),this.keyFormatPromise}getKeyFormatPromise(e){return new Promise((t,i)=>{const r=xi(this.config),n=e.map(er).filter(a=>!!a&&r.indexOf(a)!==-1);return this.getKeySystemSelectionPromise(n).then(({keySystem:a})=>{const o=ir(a);o?t(o):i(new Error(`Unable to find format for key-system "${a}"`))}).catch(i)})}loadKey(e){const t=e.keyInfo.decryptdata,i=this.getKeyIdString(t),r=`(keyId: ${i} format: "${t.keyFormat}" method: ${t.method} uri: ${t.uri})`;this.log(`Starting session for key ${r}`);let n=this.keyIdToKeySessionPromise[i];return n||(n=this.keyIdToKeySessionPromise[i]=this.getKeySystemForKeyPromise(t).then(({keySystem:a,mediaKeys:o})=>(this.throwIfDestroyed(),this.log(`Handle encrypted media sn: ${e.frag.sn} ${e.frag.type}: ${e.frag.level} using key ${r}`),this.attemptSetMediaKeys(a,o).then(()=>{this.throwIfDestroyed();const l=this.createMediaKeySessionContext({keySystem:a,mediaKeys:o,decryptdata:t}),c="cenc";return this.generateRequestWithPreferredKeySession(l,c,t.pssh,"playlist-key")}))),n.catch(a=>this.handleError(a))),n}throwIfDestroyed(e="Invalid state"){if(!this.hls)throw new Error("invalid state")}handleError(e){this.hls&&(this.error(e.message),e instanceof Ae?this.hls.trigger(p.ERROR,e.data):this.hls.trigger(p.ERROR,{type:q.KEY_SYSTEM_ERROR,details:_.KEY_SYSTEM_NO_KEYS,error:e,fatal:!0}))}getKeySystemForKeyPromise(e){const t=this.getKeyIdString(e),i=this.keyIdToKeySessionPromise[t];if(!i){const r=er(e.keyFormat),n=r?[r]:xi(this.config);return this.attemptKeySystemAccess(n)}return i}getKeySystemSelectionPromise(e){if(e.length||(e=xi(this.config)),e.length===0)throw new Ae({type:q.KEY_SYSTEM_ERROR,details:_.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${JSON.stringify({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(e)}_onMediaEncrypted(e){const{initDataType:t,initData:i}=e;if(this.debug(`"${e.type}" event: init data type: "${t}"`),i===null)return;let r,n;if(t==="sinf"&&this.config.drmSystems[ne.FAIRPLAY]){const u=ce(new Uint8Array(i));try{const h=yi(JSON.parse(u).sinf),d=dr(new Uint8Array(h));if(!d)return;r=d.subarray(8,24),n=ne.FAIRPLAY}catch{this.warn('Failed to parse sinf "encrypted" event message initData');return}}else{const u=tl(i);if(u===null)return;u.version===0&&u.systemId===tr.WIDEVINE&&u.data&&(r=u.data.subarray(8,24)),n=_o(u.systemId)}if(!n||!r)return;const a=we.hexDump(r),{keyIdToKeySessionPromise:o,mediaKeySessions:l}=this;let c=o[a];for(let u=0;u<l.length;u++){const h=l[u],d=h.decryptdata;if(d.pssh||!d.keyId)continue;const f=we.hexDump(d.keyId);if(a===f||d.uri.replace(/-/g,"").indexOf(a)!==-1){c=o[f],delete o[f],d.pssh=new Uint8Array(i),d.keyId=r,c=o[a]=c.then(()=>this.generateRequestWithPreferredKeySession(h,t,i,"encrypted-event-key-match"));break}}c||(c=o[a]=this.getKeySystemSelectionPromise([n]).then(({keySystem:u,mediaKeys:h})=>{var d;this.throwIfDestroyed();const f=new yt("ISO-23001-7",a,(d=ir(u))!=null?d:"");return f.pssh=new Uint8Array(i),f.keyId=r,this.attemptSetMediaKeys(u,h).then(()=>{this.throwIfDestroyed();const g=this.createMediaKeySessionContext({decryptdata:f,keySystem:u,mediaKeys:h});return this.generateRequestWithPreferredKeySession(g,t,i,"encrypted-event-no-match")})})),c.catch(u=>this.handleError(u))}_onWaitingForKey(e){this.log(`"${e.type}" event`)}attemptSetMediaKeys(e,t){const i=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${e}"`);const r=Promise.all(i).then(()=>{if(!this.media)throw new Error("Attempted to set mediaKeys without media element attached");return this.media.setMediaKeys(t)});return this.setMediaKeysQueue.push(r),r.then(()=>{this.log(`Media-keys set for "${e}"`),i.push(r),this.setMediaKeysQueue=this.setMediaKeysQueue.filter(n=>i.indexOf(n)===-1)})}generateRequestWithPreferredKeySession(e,t,i,r){var n,a;const o=(n=this.config.drmSystems)==null||(a=n[e.keySystem])==null?void 0:a.generateRequest;if(o)try{const g=o.call(this.hls,t,i,e);if(!g)throw new Error("Invalid response from configured generateRequest filter");t=g.initDataType,i=e.decryptdata.pssh=g.initData?new Uint8Array(g.initData):null}catch(g){var l;if(this.warn(g.message),(l=this.hls)!=null&&l.config.debug)throw g}if(i===null)return this.log(`Skipping key-session request for "${r}" (no initData)`),Promise.resolve(e);const c=this.getKeyIdString(e.decryptdata);this.log(`Generating key-session request for "${r}": ${c} (init data type: ${t} length: ${i?i.byteLength:null})`);const u=new qi,h=e._onmessage=g=>{const m=e.mediaKeysSession;if(!m){u.emit("error",new Error("invalid state"));return}const{messageType:y,message:v}=g;this.log(`"${y}" message event for session "${m.sessionId}" message size: ${v.byteLength}`),y==="license-request"||y==="license-renewal"?this.renewLicense(e,v).catch(T=>{this.handleError(T),u.emit("error",T)}):y==="license-release"?e.keySystem===ne.FAIRPLAY&&(this.updateKeySession(e,vi("acknowledged")),this.removeSession(e)):this.warn(`unhandled media key message type "${y}"`)},d=e._onkeystatuseschange=g=>{if(!e.mediaKeysSession){u.emit("error",new Error("invalid state"));return}this.onKeyStatusChange(e);const y=e.keyStatus;u.emit("keyStatus",y),y==="expired"&&(this.warn(`${e.keySystem} expired for key ${c}`),this.renewKeySession(e))};e.mediaKeysSession.addEventListener("message",h),e.mediaKeysSession.addEventListener("keystatuseschange",d);const f=new Promise((g,m)=>{u.on("error",m),u.on("keyStatus",y=>{y.startsWith("usable")?g():y==="output-restricted"?m(new Ae({type:q.KEY_SYSTEM_ERROR,details:_.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED,fatal:!1},"HDCP level output restricted")):y==="internal-error"?m(new Ae({type:q.KEY_SYSTEM_ERROR,details:_.KEY_SYSTEM_STATUS_INTERNAL_ERROR,fatal:!0},`key status changed to "${y}"`)):y==="expired"?m(new Error("key expired while generating request")):this.warn(`unhandled key status change "${y}"`)})});return e.mediaKeysSession.generateRequest(t,i).then(()=>{var g;this.log(`Request generated for key-session "${(g=e.mediaKeysSession)==null?void 0:g.sessionId}" keyId: ${c}`)}).catch(g=>{throw new Ae({type:q.KEY_SYSTEM_ERROR,details:_.KEY_SYSTEM_NO_SESSION,error:g,fatal:!1},`Error generating key-session request: ${g}`)}).then(()=>f).catch(g=>{throw u.removeAllListeners(),this.removeSession(e),g}).then(()=>(u.removeAllListeners(),e))}onKeyStatusChange(e){e.mediaKeysSession.keyStatuses.forEach((t,i)=>{this.log(`key status change "${t}" for keyStatuses keyId: ${we.hexDump("buffer"in i?new Uint8Array(i.buffer,i.byteOffset,i.byteLength):new Uint8Array(i))} session keyId: ${we.hexDump(new Uint8Array(e.decryptdata.keyId||[]))} uri: ${e.decryptdata.uri}`),e.keyStatus=t})}fetchServerCertificate(e){const t=this.config,i=t.loader,r=new i(t),n=this.getServerCertificateUrl(e);return n?(this.log(`Fetching server certificate for "${e}"`),new Promise((a,o)=>{const l={responseType:"arraybuffer",url:n},c=t.certLoadPolicy.default,u={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},h={onSuccess:(d,f,g,m)=>{a(d.data)},onError:(d,f,g,m)=>{o(new Ae({type:q.KEY_SYSTEM_ERROR,details:_.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:g,response:he({url:l.url,data:void 0},d)},`"${e}" certificate request failed (${n}). Status: ${d.code} (${d.text})`))},onTimeout:(d,f,g)=>{o(new Ae({type:q.KEY_SYSTEM_ERROR,details:_.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:g,response:{url:l.url,data:void 0}},`"${e}" certificate request timed out (${n})`))},onAbort:(d,f,g)=>{o(new Error("aborted"))}};r.load(l,u,h)})):Promise.resolve()}setMediaKeysServerCertificate(e,t,i){return new Promise((r,n)=>{e.setServerCertificate(i).then(a=>{this.log(`setServerCertificate ${a?"success":"not supported by CDM"} (${i==null?void 0:i.byteLength}) on "${t}"`),r(e)}).catch(a=>{n(new Ae({type:q.KEY_SYSTEM_ERROR,details:_.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:a,fatal:!0},a.message))})})}renewLicense(e,t){return this.requestLicense(e,new Uint8Array(t)).then(i=>this.updateKeySession(e,new Uint8Array(i)).catch(r=>{throw new Ae({type:q.KEY_SYSTEM_ERROR,details:_.KEY_SYSTEM_SESSION_UPDATE_FAILED,error:r,fatal:!0},r.message)}))}unpackPlayReadyKeyMessage(e,t){const i=String.fromCharCode.apply(null,new Uint16Array(t.buffer));if(!i.includes("PlayReadyKeyMessage"))return e.setRequestHeader("Content-Type","text/xml; charset=utf-8"),t;const r=new DOMParser().parseFromString(i,"application/xml"),n=r.querySelectorAll("HttpHeader");if(n.length>0){let u;for(let h=0,d=n.length;h<d;h++){var a,o;u=n[h];const f=(a=u.querySelector("name"))==null?void 0:a.textContent,g=(o=u.querySelector("value"))==null?void 0:o.textContent;f&&g&&e.setRequestHeader(f,g)}}const l=r.querySelector("Challenge"),c=l==null?void 0:l.textContent;if(!c)throw new Error("Cannot find <Challenge> in key message");return vi(atob(c))}setupLicenseXHR(e,t,i,r){const n=this.config.licenseXhrSetup;return n?Promise.resolve().then(()=>{if(!i.decryptdata)throw new Error("Key removed");return n.call(this.hls,e,t,i,r)}).catch(a=>{if(!i.decryptdata)throw a;return e.open("POST",t,!0),n.call(this.hls,e,t,i,r)}).then(a=>(e.readyState||e.open("POST",t,!0),{xhr:e,licenseChallenge:a||r})):(e.open("POST",t,!0),Promise.resolve({xhr:e,licenseChallenge:r}))}requestLicense(e,t){const i=this.config.keyLoadPolicy.default;return new Promise((r,n)=>{const a=this.getLicenseServerUrl(e.keySystem);this.log(`Sending license request to URL: ${a}`);const o=new XMLHttpRequest;o.responseType="arraybuffer",o.onreadystatechange=()=>{if(!this.hls||!e.mediaKeysSession)return n(new Error("invalid state"));if(o.readyState===4)if(o.status===200){this._requestLicenseFailureCount=0;let l=o.response;this.log(`License received ${l instanceof ArrayBuffer?l.byteLength:l}`);const c=this.config.licenseResponseCallback;if(c)try{l=c.call(this.hls,o,a,e)}catch(u){this.error(u)}r(l)}else{const l=i.errorRetry,c=l?l.maxNumRetry:0;if(this._requestLicenseFailureCount++,this._requestLicenseFailureCount>c||o.status>=400&&o.status<500)n(new Ae({type:q.KEY_SYSTEM_ERROR,details:_.KEY_SYSTEM_LICENSE_REQUEST_FAILED,fatal:!0,networkDetails:o,response:{url:a,data:void 0,code:o.status,text:o.statusText}},`License Request XHR failed (${a}). Status: ${o.status} (${o.statusText})`));else{const u=c-this._requestLicenseFailureCount+1;this.warn(`Retrying license request, ${u} attempts left`),this.requestLicense(e,t).then(r,n)}}},e.licenseXhr&&e.licenseXhr.readyState!==XMLHttpRequest.DONE&&e.licenseXhr.abort(),e.licenseXhr=o,this.setupLicenseXHR(o,a,e,t).then(({xhr:l,licenseChallenge:c})=>{e.keySystem==ne.PLAYREADY&&(c=this.unpackPlayReadyKeyMessage(l,c)),l.send(c)})})}onMediaAttached(e,t){if(!this.config.emeEnabled)return;const i=t.media;this.media=i,i.addEventListener("encrypted",this.onMediaEncrypted),i.addEventListener("waitingforkey",this.onWaitingForKey)}onMediaDetached(){const e=this.media,t=this.mediaKeySessions;e&&(e.removeEventListener("encrypted",this.onMediaEncrypted),e.removeEventListener("waitingforkey",this.onWaitingForKey),this.media=null),this._requestLicenseFailureCount=0,this.setMediaKeysQueue=[],this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},yt.clearKeyUriToKeyIdMap();const i=t.length;ht.CDMCleanupPromise=Promise.all(t.map(r=>this.removeSession(r)).concat(e==null?void 0:e.setMediaKeys(null).catch(r=>{this.log(`Could not clear media keys: ${r}`)}))).then(()=>{i&&(this.log("finished closing key sessions and clearing media keys"),t.length=0)}).catch(r=>{this.log(`Could not close sessions and clear media keys: ${r}`)})}onManifestLoading(){this.keyFormatPromise=null}onManifestLoaded(e,{sessionKeys:t}){if(!(!t||!this.config.emeEnabled)&&!this.keyFormatPromise){const i=t.reduce((r,n)=>(r.indexOf(n.keyFormat)===-1&&r.push(n.keyFormat),r),[]);this.log(`Selecting key-system from session-keys ${i.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(i)}}removeSession(e){const{mediaKeysSession:t,licenseXhr:i}=e;if(t){this.log(`Remove licenses and keys and close session ${t.sessionId}`),e._onmessage&&(t.removeEventListener("message",e._onmessage),e._onmessage=void 0),e._onkeystatuseschange&&(t.removeEventListener("keystatuseschange",e._onkeystatuseschange),e._onkeystatuseschange=void 0),i&&i.readyState!==XMLHttpRequest.DONE&&i.abort(),e.mediaKeysSession=e.decryptdata=e.licenseXhr=void 0;const r=this.mediaKeySessions.indexOf(e);return r>-1&&this.mediaKeySessions.splice(r,1),t.remove().catch(n=>{this.log(`Could not remove session: ${n}`)}).then(()=>t.close()).catch(n=>{this.log(`Could not close session: ${n}`)})}}}ht.CDMCleanupPromise=void 0;class Ae extends Error{constructor(e,t){super(t),this.data=void 0,e.error||(e.error=new Error(t)),this.data=e,e.err=e.error}}var ve;(function(s){s.MANIFEST="m",s.AUDIO="a",s.VIDEO="v",s.MUXED="av",s.INIT="i",s.CAPTION="c",s.TIMED_TEXT="tt",s.KEY="k",s.OTHER="o"})(ve||(ve={}));var ls;(function(s){s.DASH="d",s.HLS="h",s.SMOOTH="s",s.OTHER="o"})(ls||(ls={}));var Ze;(function(s){s.OBJECT="CMCD-Object",s.REQUEST="CMCD-Request",s.SESSION="CMCD-Session",s.STATUS="CMCD-Status"})(Ze||(Ze={}));const Tu={[Ze.OBJECT]:["br","d","ot","tb"],[Ze.REQUEST]:["bl","dl","mtp","nor","nrr","su"],[Ze.SESSION]:["cid","pr","sf","sid","st","v"],[Ze.STATUS]:["bs","rtp"]};class dt{constructor(e,t){this.value=void 0,this.params=void 0,Array.isArray(e)&&(e=e.map(i=>i instanceof dt?i:new dt(i))),this.value=e,this.params=t}}class jn{constructor(e){this.description=void 0,this.description=e}}const Eu="Dict";function Su(s){return Array.isArray(s)?JSON.stringify(s):s instanceof Map?"Map{}":s instanceof Set?"Set{}":typeof s=="object"?JSON.stringify(s):String(s)}function bu(s,e,t,i){return new Error(`failed to ${s} "${Su(e)}" as ${t}`,{cause:i})}const Yn="Bare Item",Au="Boolean",Lu="Byte Sequence",Ru="Decimal",Cu="Integer";function Du(s){return s<-999999999999999||999999999999999<s}const _u=/[\x00-\x1f\x7f]+/,Iu="Token",wu="Key";function Me(s,e,t){return bu("serialize",s,e,t)}function ku(s){if(typeof s!="boolean")throw Me(s,Au);return s?"?1":"?0"}function Pu(s){return btoa(String.fromCharCode(...s))}function Ou(s){if(ArrayBuffer.isView(s)===!1)throw Me(s,Lu);return`:${Pu(s)}:`}function qn(s){if(Du(s))throw Me(s,Cu);return s.toString()}function Fu(s){return`@${qn(s.getTime()/1e3)}`}function Xn(s,e){if(s<0)return-Xn(-s,e);const t=Math.pow(10,e);if(Math.abs(s*t%1-.5)<Number.EPSILON){const r=Math.floor(s*t);return(r%2===0?r:r+1)/t}else return Math.round(s*t)/t}function Mu(s){const e=Xn(s,3);if(Math.floor(Math.abs(e)).toString().length>12)throw Me(s,Ru);const t=e.toString();return t.includes(".")?t:`${t}.0`}const Nu="String";function Bu(s){if(_u.test(s))throw Me(s,Nu);return`"${s.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function Uu(s){return s.description||s.toString().slice(7,-1)}function Zn(s){const e=Uu(s);if(/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(e)===!1)throw Me(e,Iu);return e}function cs(s){switch(typeof s){case"number":if(!K(s))throw Me(s,Yn);return Number.isInteger(s)?qn(s):Mu(s);case"string":return Bu(s);case"symbol":return Zn(s);case"boolean":return ku(s);case"object":if(s instanceof Date)return Fu(s);if(s instanceof Uint8Array)return Ou(s);if(s instanceof jn)return Zn(s);default:throw Me(s,Yn)}}function us(s){if(/^[a-z*][a-z0-9\-_.*]*$/.test(s)===!1)throw Me(s,wu);return s}function hs(s){return s==null?"":Object.entries(s).map(([e,t])=>t===!0?`;${us(e)}`:`;${us(e)}=${cs(t)}`).join("")}function Qn(s){return s instanceof dt?`${cs(s.value)}${hs(s.params)}`:cs(s)}function $u(s){return`(${s.value.map(Qn).join(" ")})${hs(s.params)}`}function Gu(s,e={whitespace:!0}){if(typeof s!="object")throw Me(s,Eu);const t=s instanceof Map?s.entries():Object.entries(s),i=e!=null&&e.whitespace?" ":"";return Array.from(t).map(([r,n])=>{n instanceof dt||(n=new dt(n));let a=us(r);return n.value===!0?a+=hs(n.params):(a+="=",Array.isArray(n.value)?a+=$u(n):a+=Qn(n)),a}).join(`,${i}`)}function Hu(s,e){return Gu(s,e)}const Vu=s=>s==="ot"||s==="sf"||s==="st",Ku=s=>typeof s=="number"?K(s):s!=null&&s!==""&&s!==!1;function Wu(s,e){const t=new URL(s),i=new URL(e);if(t.origin!==i.origin)return s;const r=t.pathname.split("/").slice(1),n=i.pathname.split("/").slice(1,-1);for(;r[0]===n[0];)r.shift(),n.shift();for(;n.length;)n.shift(),r.unshift("..");return r.join("/")}function zu(){try{return crypto.randomUUID()}catch{try{const e=URL.createObjectURL(new Blob),t=e.toString();return URL.revokeObjectURL(e),t.slice(t.lastIndexOf("/")+1)}catch{let t=new Date().getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,r=>{const n=(t+Math.random()*16)%16|0;return t=Math.floor(t/16),(r=="x"?n:n&3|8).toString(16)})}}}const Jt=s=>Math.round(s),ju=(s,e)=>(e!=null&&e.baseUrl&&(s=Wu(s,e.baseUrl)),encodeURIComponent(s)),ei=s=>Jt(s/100)*100,Yu={br:Jt,d:Jt,bl:ei,dl:ei,mtp:ei,nor:ju,rtp:ei,tb:Jt};function qu(s,e){const t={};if(s==null||typeof s!="object")return t;const i=Object.keys(s).sort(),r=oe({},Yu,e==null?void 0:e.formatters),n=e==null?void 0:e.filter;return i.forEach(a=>{if(n!=null&&n(a))return;let o=s[a];const l=r[a];l&&(o=l(o,e)),!(a==="v"&&o===1)&&(a=="pr"&&o===1||Ku(o)&&(Vu(a)&&typeof o=="string"&&(o=new jn(o)),t[a]=o))}),t}function Jn(s,e={}){return s?Hu(qu(s,e),oe({whitespace:!1},e)):""}function Xu(s,e={}){if(!s)return{};const t=Object.entries(s),i=Object.entries(Tu).concat(Object.entries((e==null?void 0:e.customHeaderMap)||{})),r=t.reduce((n,a)=>{var o,l;const[c,u]=a,h=((o=i.find(d=>d[1].includes(c)))==null?void 0:o[0])||Ze.REQUEST;return(l=n[h])!=null||(n[h]={}),n[h][c]=u,n},{});return Object.entries(r).reduce((n,[a,o])=>(n[a]=Jn(o,e),n),{})}function Zu(s,e,t){return oe(s,Xu(e,t))}const Qu="CMCD";function Ju(s,e={}){if(!s)return"";const t=Jn(s,e);return`${Qu}=${encodeURIComponent(t)}`}const ea=/CMCD=[^&#]+/;function eh(s,e,t){const i=Ju(e,t);if(!i)return s;if(ea.test(s))return s.replace(ea,i);const r=s.includes("?")?"&":"?";return`${s}${r}${i}`}class th{constructor(e){this.hls=void 0,this.config=void 0,this.media=void 0,this.sid=void 0,this.cid=void 0,this.useHeaders=!1,this.includeKeys=void 0,this.initialized=!1,this.starved=!1,this.buffering=!0,this.audioBuffer=void 0,this.videoBuffer=void 0,this.onWaiting=()=>{this.initialized&&(this.starved=!0),this.buffering=!0},this.onPlaying=()=>{this.initialized||(this.initialized=!0),this.buffering=!1},this.applyPlaylistData=r=>{try{this.apply(r,{ot:ve.MANIFEST,su:!this.initialized})}catch(n){S.warn("Could not generate manifest CMCD data.",n)}},this.applyFragmentData=r=>{try{const n=r.frag,a=this.hls.levels[n.level],o=this.getObjectType(n),l={d:n.duration*1e3,ot:o};(o===ve.VIDEO||o===ve.AUDIO||o==ve.MUXED)&&(l.br=a.bitrate/1e3,l.tb=this.getTopBandwidth(o)/1e3,l.bl=this.getBufferLength(o)),this.apply(r,l)}catch(n){S.warn("Could not generate segment CMCD data.",n)}},this.hls=e;const t=this.config=e.config,{cmcd:i}=t;i!=null&&(t.pLoader=this.createPlaylistLoader(),t.fLoader=this.createFragmentLoader(),this.sid=i.sessionId||zu(),this.cid=i.contentId,this.useHeaders=i.useHeaders===!0,this.includeKeys=i.includeKeys,this.registerListeners())}registerListeners(){const e=this.hls;e.on(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(p.MEDIA_DETACHED,this.onMediaDetached,this),e.on(p.BUFFER_CREATED,this.onBufferCreated,this)}unregisterListeners(){const e=this.hls;e.off(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(p.MEDIA_DETACHED,this.onMediaDetached,this),e.off(p.BUFFER_CREATED,this.onBufferCreated,this)}destroy(){this.unregisterListeners(),this.onMediaDetached(),this.hls=this.config=this.audioBuffer=this.videoBuffer=null,this.onWaiting=this.onPlaying=null}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener("waiting",this.onWaiting),this.media.addEventListener("playing",this.onPlaying)}onMediaDetached(){this.media&&(this.media.removeEventListener("waiting",this.onWaiting),this.media.removeEventListener("playing",this.onPlaying),this.media=null)}onBufferCreated(e,t){var i,r;this.audioBuffer=(i=t.tracks.audio)==null?void 0:i.buffer,this.videoBuffer=(r=t.tracks.video)==null?void 0:r.buffer}createData(){var e;return{v:1,sf:ls.HLS,sid:this.sid,cid:this.cid,pr:(e=this.media)==null?void 0:e.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(e,t={}){oe(t,this.createData());const i=t.ot===ve.INIT||t.ot===ve.VIDEO||t.ot===ve.MUXED;this.starved&&i&&(t.bs=!0,t.su=!0,this.starved=!1),t.su==null&&(t.su=this.buffering);const{includeKeys:r}=this;r&&(t=Object.keys(t).reduce((n,a)=>(r.includes(a)&&(n[a]=t[a]),n),{})),this.useHeaders?(e.headers||(e.headers={}),Zu(e.headers,t)):e.url=eh(e.url,t)}getObjectType(e){const{type:t}=e;if(t==="subtitle")return ve.TIMED_TEXT;if(e.sn==="initSegment")return ve.INIT;if(t==="audio")return ve.AUDIO;if(t==="main")return this.hls.audioTracks.length?ve.VIDEO:ve.MUXED}getTopBandwidth(e){let t=0,i;const r=this.hls;if(e===ve.AUDIO)i=r.audioTracks;else{const n=r.maxAutoLevel,a=n>-1?n+1:r.levels.length;i=r.levels.slice(0,a)}for(const n of i)n.bitrate>t&&(t=n.bitrate);return t>0?t:NaN}getBufferLength(e){const t=this.hls.media,i=e===ve.AUDIO?this.audioBuffer:this.videoBuffer;return!i||!t?NaN:se.bufferInfo(i,t.currentTime,this.config.maxBufferHole).len*1e3}createPlaylistLoader(){const{pLoader:e}=this.config,t=this.applyPlaylistData,i=e||this.config.loader;return class{constructor(n){this.loader=void 0,this.loader=new i(n)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(n,a,o){t(n),this.loader.load(n,a,o)}}}createFragmentLoader(){const{fLoader:e}=this.config,t=this.applyFragmentData,i=e||this.config.loader;return class{constructor(n){this.loader=void 0,this.loader=new i(n)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(n,a,o){t(n),this.loader.load(n,a,o)}}}}const ih=3e5;class sh{constructor(e){this.hls=void 0,this.log=void 0,this.loader=null,this.uri=null,this.pathwayId=".",this.pathwayPriority=null,this.timeToLoad=300,this.reloadTimer=-1,this.updated=0,this.started=!1,this.enabled=!0,this.levels=null,this.audioTracks=null,this.subtitleTracks=null,this.penalizedPathways={},this.hls=e,this.log=S.log.bind(S,"[content-steering]:"),this.registerListeners()}registerListeners(){const e=this.hls;e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(p.MANIFEST_PARSED,this.onManifestParsed,this),e.on(p.ERROR,this.onError,this)}unregisterListeners(){const e=this.hls;e&&(e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(p.MANIFEST_PARSED,this.onManifestParsed,this),e.off(p.ERROR,this.onError,this))}startLoad(){if(this.started=!0,this.clearTimeout(),this.enabled&&this.uri){if(this.updated){const e=this.timeToLoad*1e3-(performance.now()-this.updated);if(e>0){this.scheduleRefresh(this.uri,e);return}}this.loadSteeringManifest(this.uri)}}stopLoad(){this.started=!1,this.loader&&(this.loader.destroy(),this.loader=null),this.clearTimeout()}clearTimeout(){this.reloadTimer!==-1&&(self.clearTimeout(this.reloadTimer),this.reloadTimer=-1)}destroy(){this.unregisterListeners(),this.stopLoad(),this.hls=null,this.levels=this.audioTracks=this.subtitleTracks=null}removeLevel(e){const t=this.levels;t&&(this.levels=t.filter(i=>i!==e))}onManifestLoading(){this.stopLoad(),this.enabled=!0,this.timeToLoad=300,this.updated=0,this.uri=null,this.pathwayId=".",this.levels=this.audioTracks=this.subtitleTracks=null}onManifestLoaded(e,t){const{contentSteering:i}=t;i!==null&&(this.pathwayId=i.pathwayId,this.uri=i.uri,this.started&&this.startLoad())}onManifestParsed(e,t){this.audioTracks=t.audioTracks,this.subtitleTracks=t.subtitleTracks}onError(e,t){const{errorAction:i}=t;if((i==null?void 0:i.action)===me.SendAlternateToPenaltyBox&&i.flags===Ce.MoveAllAlternatesMatchingHost){const r=this.levels;let n=this.pathwayPriority,a=this.pathwayId;if(t.context){const{groupId:o,pathwayId:l,type:c}=t.context;o&&r?a=this.getPathwayForGroupId(o,c,a):l&&(a=l)}a in this.penalizedPathways||(this.penalizedPathways[a]=performance.now()),!n&&r&&(n=r.reduce((o,l)=>(o.indexOf(l.pathwayId)===-1&&o.push(l.pathwayId),o),[])),n&&n.length>1&&(this.updatePathwayPriority(n),i.resolved=this.pathwayId!==a),i.resolved||S.warn(`Could not resolve ${t.details} ("${t.error.message}") with content-steering for Pathway: ${a} levels: ${r&&r.length} priorities: ${JSON.stringify(n)} penalized: ${JSON.stringify(this.penalizedPathways)}`)}}filterParsedLevels(e){this.levels=e;let t=this.getLevelsForPathway(this.pathwayId);if(t.length===0){const i=e[0].pathwayId;this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${i}"`),t=this.getLevelsForPathway(i),this.pathwayId=i}return t.length!==e.length?(this.log(`Found ${t.length}/${e.length} levels in Pathway "${this.pathwayId}"`),t):e}getLevelsForPathway(e){return this.levels===null?[]:this.levels.filter(t=>e===t.pathwayId)}updatePathwayPriority(e){this.pathwayPriority=e;let t;const i=this.penalizedPathways,r=performance.now();Object.keys(i).forEach(n=>{r-i[n]>ih&&delete i[n]});for(let n=0;n<e.length;n++){const a=e[n];if(a in i)continue;if(a===this.pathwayId)return;const o=this.hls.nextLoadLevel,l=this.hls.levels[o];if(t=this.getLevelsForPathway(a),t.length>0){this.log(`Setting Pathway to "${a}"`),this.pathwayId=a,Gr(t),this.hls.trigger(p.LEVELS_UPDATED,{levels:t});const c=this.hls.levels[o];l&&c&&this.levels&&(c.attrs["STABLE-VARIANT-ID"]!==l.attrs["STABLE-VARIANT-ID"]&&c.bitrate!==l.bitrate&&this.log(`Unstable Pathways change from bitrate ${l.bitrate} to ${c.bitrate}`),this.hls.nextLoadLevel=o);break}}}getPathwayForGroupId(e,t,i){const r=this.getLevelsForPathway(i).concat(this.levels||[]);for(let n=0;n<r.length;n++)if(t===ee.AUDIO_TRACK&&r[n].hasAudioGroup(e)||t===ee.SUBTITLE_TRACK&&r[n].hasSubtitleGroup(e))return r[n].pathwayId;return i}clonePathways(e){const t=this.levels;if(!t)return;const i={},r={};e.forEach(n=>{const{ID:a,"BASE-ID":o,"URI-REPLACEMENT":l}=n;if(t.some(u=>u.pathwayId===a))return;const c=this.getLevelsForPathway(o).map(u=>{const h=new ae(u.attrs);h["PATHWAY-ID"]=a;const d=h.AUDIO&&`${h.AUDIO}_clone_${a}`,f=h.SUBTITLES&&`${h.SUBTITLES}_clone_${a}`;d&&(i[h.AUDIO]=d,h.AUDIO=d),f&&(r[h.SUBTITLES]=f,h.SUBTITLES=f);const g=ia(u.uri,h["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",l),m=new it({attrs:h,audioCodec:u.audioCodec,bitrate:u.bitrate,height:u.height,name:u.name,url:g,videoCodec:u.videoCodec,width:u.width});if(u.audioGroups)for(let y=1;y<u.audioGroups.length;y++)m.addGroupId("audio",`${u.audioGroups[y]}_clone_${a}`);if(u.subtitleGroups)for(let y=1;y<u.subtitleGroups.length;y++)m.addGroupId("text",`${u.subtitleGroups[y]}_clone_${a}`);return m});t.push(...c),ta(this.audioTracks,i,l,a),ta(this.subtitleTracks,r,l,a)})}loadSteeringManifest(e){const t=this.hls.config,i=t.loader;this.loader&&this.loader.destroy(),this.loader=new i(t);let r;try{r=new self.URL(e)}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest URI: ${e}`);return}if(r.protocol!=="data:"){const u=(this.hls.bandwidthEstimate||t.abrEwmaDefaultEstimate)|0;r.searchParams.set("_HLS_pathway",this.pathwayId),r.searchParams.set("_HLS_throughput",""+u)}const n={responseType:"json",url:r.href},a=t.steeringManifestLoadPolicy.default,o=a.errorRetry||a.timeoutRetry||{},l={loadPolicy:a,timeout:a.maxLoadTimeMs,maxRetry:o.maxNumRetry||0,retryDelay:o.retryDelayMs||0,maxRetryDelay:o.maxRetryDelayMs||0},c={onSuccess:(u,h,d,f)=>{this.log(`Loaded steering manifest: "${r}"`);const g=u.data;if(g.VERSION!==1){this.log(`Steering VERSION ${g.VERSION} not supported!`);return}this.updated=performance.now(),this.timeToLoad=g.TTL;const{"RELOAD-URI":m,"PATHWAY-CLONES":y,"PATHWAY-PRIORITY":v}=g;if(m)try{this.uri=new self.URL(m,r).href}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest RELOAD-URI: ${m}`);return}this.scheduleRefresh(this.uri||d.url),y&&this.clonePathways(y);const T={steeringManifest:g,url:r.toString()};this.hls.trigger(p.STEERING_MANIFEST_LOADED,T),v&&this.updatePathwayPriority(v)},onError:(u,h,d,f)=>{if(this.log(`Error loading steering manifest: ${u.code} ${u.text} (${h.url})`),this.stopLoad(),u.code===410){this.enabled=!1,this.log(`Steering manifest ${h.url} no longer available`);return}let g=this.timeToLoad*1e3;if(u.code===429){const m=this.loader;if(typeof(m==null?void 0:m.getResponseHeader)=="function"){const y=m.getResponseHeader("Retry-After");y&&(g=parseFloat(y)*1e3)}this.log(`Steering manifest ${h.url} rate limited`);return}this.scheduleRefresh(this.uri||h.url,g)},onTimeout:(u,h,d)=>{this.log(`Timeout loading steering manifest (${h.url})`),this.scheduleRefresh(this.uri||h.url)}};this.log(`Requesting steering manifest: ${r}`),this.loader.load(n,l,c)}scheduleRefresh(e,t=this.timeToLoad*1e3){this.clearTimeout(),this.reloadTimer=self.setTimeout(()=>{var i;const r=(i=this.hls)==null?void 0:i.media;if(r&&!r.ended){this.loadSteeringManifest(e);return}this.scheduleRefresh(e,this.timeToLoad*1e3)},t)}}function ta(s,e,t,i){s&&Object.keys(e).forEach(r=>{const n=s.filter(a=>a.groupId===r).map(a=>{const o=oe({},a);return o.details=void 0,o.attrs=new ae(o.attrs),o.url=o.attrs.URI=ia(a.url,a.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",t),o.groupId=o.attrs["GROUP-ID"]=e[r],o.attrs["PATHWAY-ID"]=i,o});s.push(...n)})}function ia(s,e,t,i){const{HOST:r,PARAMS:n,[t]:a}=i;let o;e&&(o=a==null?void 0:a[e],o&&(s=o));const l=new self.URL(s);return r&&!o&&(l.host=r),n&&Object.keys(n).sort().forEach(c=>{c&&l.searchParams.set(c,n[c])}),l.href}const rh=/^age:\s*[\d.]+\s*$/im;class sa{constructor(e){this.xhrSetup=void 0,this.requestTimeout=void 0,this.retryTimeout=void 0,this.retryDelay=void 0,this.config=null,this.callbacks=null,this.context=null,this.loader=null,this.stats=void 0,this.xhrSetup=e&&e.xhrSetup||null,this.stats=new Ct,this.retryDelay=0}destroy(){this.callbacks=null,this.abortInternal(),this.loader=null,this.config=null,this.context=null,this.xhrSetup=null,this.stats=null}abortInternal(){const e=this.loader;self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),e&&(e.onreadystatechange=null,e.onprogress=null,e.readyState!==4&&(this.stats.aborted=!0,e.abort()))}abort(){var e;this.abortInternal(),(e=this.callbacks)!=null&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.loader)}load(e,t,i){if(this.stats.loading.start)throw new Error("Loader can only be used once.");this.stats.loading.start=self.performance.now(),this.context=e,this.config=t,this.callbacks=i,this.loadInternal()}loadInternal(){const{config:e,context:t}=this;if(!e||!t)return;const i=this.loader=new self.XMLHttpRequest,r=this.stats;r.loading.first=0,r.loaded=0,r.aborted=!1;const n=this.xhrSetup;n?Promise.resolve().then(()=>{if(!this.stats.aborted)return n(i,t.url)}).catch(a=>(i.open("GET",t.url,!0),n(i,t.url))).then(()=>{this.stats.aborted||this.openAndSendXhr(i,t,e)}).catch(a=>{this.callbacks.onError({code:i.status,text:a.message},t,i,r)}):this.openAndSendXhr(i,t,e)}openAndSendXhr(e,t,i){e.readyState||e.open("GET",t.url,!0);const r=t.headers,{maxTimeToFirstByteMs:n,maxLoadTimeMs:a}=i.loadPolicy;if(r)for(const 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),i.timeout=n&&K(n)?n:a,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),i.timeout),e.send()}readystatechange(){const{context:e,loader:t,stats:i}=this;if(!e||!t)return;const r=t.readyState,n=this.config;if(!i.aborted&&r>=2&&(i.loading.first===0&&(i.loading.first=Math.max(self.performance.now(),i.loading.start),n.timeout!==n.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),n.timeout=n.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),n.loadPolicy.maxLoadTimeMs-(i.loading.first-i.loading.start)))),r===4)){self.clearTimeout(this.requestTimeout),t.onreadystatechange=null,t.onprogress=null;const a=t.status,o=t.responseType!=="text";if(a>=200&&a<300&&(o&&t.response||t.responseText!==null)){i.loading.end=Math.max(self.performance.now(),i.loading.first);const l=o?t.response:t.responseText,c=t.responseType==="arraybuffer"?l.byteLength:l.length;if(i.loaded=i.total=c,i.bwEstimate=i.total*8e3/(i.loading.end-i.loading.first),!this.callbacks)return;const u=this.callbacks.onProgress;if(u&&u(i,e,l,t),!this.callbacks)return;const h={url:t.responseURL,data:l,code:a};this.callbacks.onSuccess(h,i,e,t)}else{const l=n.loadPolicy.errorRetry,c=i.retry,u={url:e.url,data:void 0,code:a};Ut(l,c,!1,u)?this.retry(l):(S.error(`${a} while loading ${e.url}`),this.callbacks.onError({code:a,text:t.statusText},e,t,i))}}}loadtimeout(){var e;const t=(e=this.config)==null?void 0:e.loadPolicy.timeoutRetry,i=this.stats.retry;if(Ut(t,i,!0))this.retry(t);else{var r;S.warn(`timeout while loading ${(r=this.context)==null?void 0:r.url}`);const n=this.callbacks;n&&(this.abortInternal(),n.onTimeout(this.stats,this.context,this.loader))}}retry(e){const{context:t,stats:i}=this;this.retryDelay=Fi(e,i.retry),i.retry++,S.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${t==null?void 0:t.url}, retrying ${i.retry}/${e.maxNumRetry} in ${this.retryDelay}ms`),this.abortInternal(),this.loader=null,self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(this.loadInternal.bind(this),this.retryDelay)}loadprogress(e){const t=this.stats;t.loaded=e.loaded,e.lengthComputable&&(t.total=e.total)}getCacheAge(){let e=null;if(this.loader&&rh.test(this.loader.getAllResponseHeaders())){const t=this.loader.getResponseHeader("age");e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.loader&&new RegExp(`^${e}:\\s*[\\d.]+\\s*$`,"im").test(this.loader.getAllResponseHeaders())?this.loader.getResponseHeader(e):null}}function nh(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch{}return!1}const ah=/(\d+)-(\d+)\/(\d+)/;class ra{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||uh,this.controller=new self.AbortController,this.stats=new Ct}destroy(){this.loader=this.callbacks=this.context=this.config=this.request=null,this.abortInternal(),this.response=null,this.fetchSetup=this.controller=this.stats=null}abortInternal(){this.controller&&!this.stats.loading.end&&(this.stats.aborted=!0,this.controller.abort())}abort(){var e;this.abortInternal(),(e=this.callbacks)!=null&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.response)}load(e,t,i){const r=this.stats;if(r.loading.start)throw new Error("Loader can only be used once.");r.loading.start=self.performance.now();const n=oh(e,this.controller.signal),a=i.onProgress,o=e.responseType==="arraybuffer",l=o?"byteLength":"length",{maxTimeToFirstByteMs:c,maxLoadTimeMs:u}=t.loadPolicy;this.context=e,this.config=t,this.callbacks=i,this.request=this.fetchSetup(e,n),self.clearTimeout(this.requestTimeout),t.timeout=c&&K(c)?c:u,this.requestTimeout=self.setTimeout(()=>{this.abortInternal(),i.onTimeout(r,e,this.response)},t.timeout),self.fetch(this.request).then(h=>{this.response=this.loader=h;const d=Math.max(self.performance.now(),r.loading.start);if(self.clearTimeout(this.requestTimeout),t.timeout=u,this.requestTimeout=self.setTimeout(()=>{this.abortInternal(),i.onTimeout(r,e,this.response)},u-(d-r.loading.start)),!h.ok){const{status:f,statusText:g}=h;throw new hh(g||"fetch, bad network response",f,h)}return r.loading.first=d,r.total=ch(h.headers)||r.total,a&&K(t.highWaterMark)?this.loadProgressively(h,r,e,t.highWaterMark,a):o?h.arrayBuffer():e.responseType==="json"?h.json():h.text()}).then(h=>{const d=this.response;if(!d)throw new Error("loader destroyed");self.clearTimeout(this.requestTimeout),r.loading.end=Math.max(self.performance.now(),r.loading.first);const f=h[l];f&&(r.loaded=r.total=f);const g={url:d.url,data:h,code:d.status};a&&!K(t.highWaterMark)&&a(r,e,h,d),i.onSuccess(g,r,e,d)}).catch(h=>{if(self.clearTimeout(this.requestTimeout),r.aborted)return;const d=h&&h.code||0,f=h?h.message:null;i.onError({code:d,text:f},e,h?h.details:null,r)})}getCacheAge(){let e=null;if(this.response){const t=this.response.headers.get("age");e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.response?this.response.headers.get(e):null}loadProgressively(e,t,i,r=0,n){const a=new Jr,o=e.body.getReader(),l=()=>o.read().then(c=>{if(c.done)return a.dataLength&&n(t,i,a.flush(),e),Promise.resolve(new ArrayBuffer(0));const u=c.value,h=u.length;return t.loaded+=h,h<r||a.dataLength?(a.push(u),a.dataLength>=r&&n(t,i,a.flush(),e)):n(t,i,u,e),l()}).catch(()=>Promise.reject());return l()}}function oh(s,e){const t={method:"GET",mode:"cors",credentials:"same-origin",signal:e,headers:new self.Headers(oe({},s.headers))};return s.rangeEnd&&t.headers.set("Range","bytes="+s.rangeStart+"-"+String(s.rangeEnd-1)),t}function lh(s){const e=ah.exec(s);if(e)return parseInt(e[2])-parseInt(e[1])+1}function ch(s){const e=s.get("Content-Range");if(e){const i=lh(e);if(K(i))return i}const t=s.get("Content-Length");if(t)return parseInt(t)}function uh(s,e){return new self.Request(s.url,e)}class hh extends Error{constructor(e,t,i){super(e),this.code=void 0,this.details=void 0,this.code=t,this.details=i}}const dh=/\s/,fh={newCue(s,e,t,i){const r=[];let n,a,o,l,c;const u=self.VTTCue||self.TextTrackCue;for(let d=0;d<i.rows.length;d++)if(n=i.rows[d],o=!0,l=0,c="",!n.isEmpty()){var h;for(let m=0;m<n.chars.length;m++)dh.test(n.chars[m].uchar)&&o?l++:(c+=n.chars[m].uchar,o=!1);n.cueStartTime=e,e===t&&(t+=1e-4),l>=16?l--:l++;const f=Nn(c.trim()),g=is(e,t,f);s!=null&&(h=s.cues)!=null&&h.getCueById(g)||(a=new u(e,t,f),a.id=g,a.line=d+1,a.align="left",a.position=10+Math.min(80,Math.floor(l*8/32)*10),r.push(a))}return s&&r.length&&(r.sort((d,f)=>d.line==="auto"||f.line==="auto"?0:d.line>8&&f.line>8?f.line-d.line:d.line-f.line),r.forEach(d=>Pr(s,d))),r}},gh={maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null},na=he(he({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,preferManagedMediaSource:!0,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,frontBufferFlushThreshold:1/0,maxBufferSize:60*1e3*1e3,maxBufferHole:.1,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,maxFragLookUpTolerance:.25,liveSyncDurationCount:3,liveMaxLatencyDurationCount:1/0,liveSyncDuration:void 0,liveMaxLatencyDuration:void 0,maxLiveSyncPlaybackRate:1,liveDurationInfinity:!1,liveBackBufferLength:null,maxMaxBufferLength:600,enableWorker:!0,workerPath:null,enableSoftwareAES:!0,startLevel:void 0,startFragPrefetch:!1,fpsDroppedMonitoringPeriod:5e3,fpsDroppedMonitoringThreshold:.2,appendErrorMaxRetry:3,loader:sa,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:Kl,bufferController:Yc,capLevelController:os,errorController:kl,fpsController:xu,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:sr,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableID3MetadataCues:!0,useMediaCapabilities:!0,certLoadPolicy:{default:gh},keyLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"},errorRetry:{maxNumRetry:8,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"}}},manifestLoadPolicy:{default:{maxTimeToFirstByteMs:1/0,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},playlistLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:2,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},fragLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:12e4,timeoutRetry:{maxNumRetry:4,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:6,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},steeringManifestLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},manifestLoadingTimeOut:1e4,manifestLoadingMaxRetry:1,manifestLoadingRetryDelay:1e3,manifestLoadingMaxRetryTimeout:64e3,levelLoadingTimeOut:1e4,levelLoadingMaxRetry:4,levelLoadingRetryDelay:1e3,levelLoadingMaxRetryTimeout:64e3,fragLoadingTimeOut:2e4,fragLoadingMaxRetry:6,fragLoadingRetryDelay:1e3,fragLoadingMaxRetryTimeout:64e3},mh()),{},{subtitleStreamController:Kc,subtitleTrackController:zc,timelineController:yu,audioStreamController:Hc,audioTrackController:Vc,emeController:ht,cmcdController:th,contentSteeringController:sh});function mh(){return{cueHandler:fh,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 ph(s,e){if((e.liveSyncDurationCount||e.liveMaxLatencyDurationCount)&&(e.liveSyncDuration||e.liveMaxLatencyDuration))throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");if(e.liveMaxLatencyDurationCount!==void 0&&(e.liveSyncDurationCount===void 0||e.liveMaxLatencyDurationCount<=e.liveSyncDurationCount))throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(e.liveMaxLatencyDuration!==void 0&&(e.liveSyncDuration===void 0||e.liveMaxLatencyDuration<=e.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');const t=ds(s),i=["manifest","level","frag"],r=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return i.forEach(n=>{const a=`${n==="level"?"playlist":n}LoadPolicy`,o=e[a]===void 0,l=[];r.forEach(c=>{const u=`${n}Loading${c}`,h=e[u];if(h!==void 0&&o){l.push(u);const d=t[a].default;switch(e[a]={default:d},c){case"TimeOut":d.maxLoadTimeMs=h,d.maxTimeToFirstByteMs=h;break;case"MaxRetry":d.errorRetry.maxNumRetry=h,d.timeoutRetry.maxNumRetry=h;break;case"RetryDelay":d.errorRetry.retryDelayMs=h,d.timeoutRetry.retryDelayMs=h;break;case"MaxRetryTimeout":d.errorRetry.maxRetryDelayMs=h,d.timeoutRetry.maxRetryDelayMs=h;break}}}),l.length&&S.warn(`hls.js config: "${l.join('", "')}" setting(s) are deprecated, use "${a}": ${JSON.stringify(e[a])}`)}),he(he({},t),e)}function ds(s){return s&&typeof s=="object"?Array.isArray(s)?s.map(ds):Object.keys(s).reduce((e,t)=>(e[t]=ds(s[t]),e),{}):s}function yh(s){const e=s.loader;e!==ra&&e!==sa?(S.log("[config]: Custom loader detected, cannot enable progressive streaming"),s.progressive=!1):nh()&&(s.loader=ra,s.progressive=!0,s.enableSoftwareAES=!0,S.log("[config]: Progressive streaming enabled, using FetchLoader"))}let fs;class vh extends Ni{constructor(e,t){super(e,"[level-controller]"),this._levels=[],this._firstLevel=-1,this._maxAutoLevel=-1,this._startLevel=void 0,this.currentLevel=null,this.currentLevelIndex=-1,this.manualLevelIndex=-1,this.steering=void 0,this.onParsedComplete=void 0,this.steering=t,this._registerListeners()}_registerListeners(){const{hls:e}=this;e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(p.LEVEL_LOADED,this.onLevelLoaded,this),e.on(p.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(p.FRAG_BUFFERED,this.onFragBuffered,this),e.on(p.ERROR,this.onError,this)}_unregisterListeners(){const{hls:e}=this;e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(p.LEVEL_LOADED,this.onLevelLoaded,this),e.off(p.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(p.FRAG_BUFFERED,this.onFragBuffered,this),e.off(p.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){const i=this.hls.config.preferManagedMediaSource,r=[],n={},a={};let o=!1,l=!1,c=!1;t.levels.forEach(u=>{var h,d;const f=u.attrs;let{audioCodec:g,videoCodec:m}=u;((h=g)==null?void 0:h.indexOf("mp4a.40.34"))!==-1&&(fs||(fs=/chrome|firefox/i.test(navigator.userAgent)),fs&&(u.audioCodec=g=void 0)),g&&(u.audioCodec=g=Ot(g,i)),((d=m)==null?void 0:d.indexOf("avc1"))===0&&(m=u.videoCodec=ol(m));const{width:y,height:v,unknownCodecs:T}=u;if(o||(o=!!(y&&v)),l||(l=!!m),c||(c=!!g),T!=null&&T.length||g&&!Ri(g,"audio",i)||m&&!Ri(m,"video",i))return;const{CODECS:x,"FRAME-RATE":L,"HDCP-LEVEL":E,"PATHWAY-ID":w,RESOLUTION:R,"VIDEO-RANGE":B}=f,b=`${`${w||"."}-`}${u.bitrate}-${R}-${L}-${x}-${B}-${E}`;if(n[b])if(n[b].uri!==u.url&&!u.attrs["PATHWAY-ID"]){const D=a[b]+=1;u.attrs["PATHWAY-ID"]=new Array(D+1).join(".");const k=new it(u);n[b]=k,r.push(k)}else n[b].addGroupId("audio",f.AUDIO),n[b].addGroupId("text",f.SUBTITLES);else{const D=new it(u);n[b]=D,a[b]=1,r.push(D)}}),this.filterAndSortMediaOptions(r,t,o,l,c)}filterAndSortMediaOptions(e,t,i,r,n){let a=[],o=[],l=e;if((i||r)&&n&&(l=l.filter(({videoCodec:g,videoRange:m,width:y,height:v})=>(!!g||!!(y&&v))&&Tl(m))),l.length===0){Promise.resolve().then(()=>{if(this.hls){t.levels.length&&this.warn(`One or more CODECS in variant not supported: ${JSON.stringify(t.levels[0].attrs)}`);const g=new Error("no level with compatible codecs found in manifest");this.hls.trigger(p.ERROR,{type:q.MEDIA_ERROR,details:_.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:t.url,error:g,reason:g.message})}});return}if(t.audioTracks){const{preferManagedMediaSource:g}=this.hls.config;a=t.audioTracks.filter(m=>!m.audioCodec||Ri(m.audioCodec,"audio",g)),aa(a)}t.subtitles&&(o=t.subtitles,aa(o));const c=l.slice(0);l.sort((g,m)=>{if(g.attrs["HDCP-LEVEL"]!==m.attrs["HDCP-LEVEL"])return(g.attrs["HDCP-LEVEL"]||"")>(m.attrs["HDCP-LEVEL"]||"")?1:-1;if(i&&g.height!==m.height)return g.height-m.height;if(g.frameRate!==m.frameRate)return g.frameRate-m.frameRate;if(g.videoRange!==m.videoRange)return Nt.indexOf(g.videoRange)-Nt.indexOf(m.videoRange);if(g.videoCodec!==m.videoCodec){const y=Tr(g.videoCodec),v=Tr(m.videoCodec);if(y!==v)return v-y}if(g.uri===m.uri&&g.codecSet!==m.codecSet){const y=Pt(g.codecSet),v=Pt(m.codecSet);if(y!==v)return v-y}return g.averageBitrate!==m.averageBitrate?g.averageBitrate-m.averageBitrate:0});let u=c[0];if(this.steering&&(l=this.steering.filterParsedLevels(l),l.length!==c.length)){for(let g=0;g<c.length;g++)if(c[g].pathwayId===l[0].pathwayId){u=c[g];break}}this._levels=l;for(let g=0;g<l.length;g++)if(l[g]===u){var h;this._firstLevel=g;const m=u.bitrate,y=this.hls.bandwidthEstimate;if(this.log(`manifest loaded, ${l.length} level(s) found, first bitrate: ${m}`),((h=this.hls.userConfig)==null?void 0:h.abrEwmaDefaultEstimate)===void 0){const v=Math.min(m,this.hls.config.abrEwmaDefaultEstimateMax);v>y&&y===na.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=v)}break}const d=n&&!r,f={levels:l,audioTracks:a,subtitleTracks:o,sessionData:t.sessionData,sessionKeys:t.sessionKeys,firstLevel:this._firstLevel,stats:t.stats,audio:n,video:r,altAudio:!d&&a.some(g=>!!g.url)};this.hls.trigger(p.MANIFEST_PARSED,f),(this.hls.config.autoStartLoad||this.hls.forceStartLoad)&&this.hls.startLoad(this.hls.config.startPosition)}get levels(){return this._levels.length===0?null:this._levels}get level(){return this.currentLevelIndex}set level(e){const t=this._levels;if(t.length===0)return;if(e<0||e>=t.length){const u=new Error("invalid level idx"),h=e<0;if(this.hls.trigger(p.ERROR,{type:q.OTHER_ERROR,details:_.LEVEL_SWITCH_ERROR,level:e,fatal:h,error:u,reason:u.message}),h)return;e=Math.min(e,t.length-1)}const i=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,i===e&&a.details&&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 ${i}${n?" with Pathway "+n:""}`);const 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(p.LEVEL_SWITCHING,l);const c=a.details;if(!c||c.live){const u=this.switchParams(a.uri,r==null?void 0:r.details);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){const e=this.hls.config.startLevel;return e!==void 0?e:this.hls.firstAutoLevel}return this._startLevel}set startLevel(e){this._startLevel=e}onError(e,t){t.fatal||!t.context||t.context.type===ee.LEVEL&&t.context.level===this.level&&this.checkRetry(t)}onFragBuffered(e,{frag:t}){if(t!==void 0&&t.type===j.MAIN){const i=t.elementaryStreams;if(!Object.keys(i).some(n=>!!i[n]))return;const 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 i;const{level:r,details:n}=t,a=this._levels[r];if(!a){var o;this.warn(`Invalid level index ${r}`),(o=t.deliveryDirectives)!=null&&o.skip&&(n.deltaUpdateFailed=!0);return}r===this.currentLevelIndex?(a.fragmentError===0&&(a.loadError=0),this.playlistLoaded(r,t,a.details)):(i=t.deliveryDirectives)!=null&&i.skip&&(n.deltaUpdateFailed=!0)}loadPlaylist(e){super.loadPlaylist();const t=this.currentLevelIndex,i=this.currentLevel;if(i&&this.shouldLoadPlaylist(i)){let r=i.uri;if(e)try{r=e.addDirectives(r)}catch(a){this.warn(`Could not construct new URL with HLS Delivery Directives: ${a}`)}const n=i.attrs["PATHWAY-ID"];this.log(`Loading level index ${t}${(e==null?void 0:e.msn)!==void 0?" at sn "+e.msn+" part "+e.part:""} with${n?" Pathway "+n:""} ${r}`),this.clearTimer(),this.hls.trigger(p.LEVEL_LOADING,{url:r,level:t,pathwayId:i.attrs["PATHWAY-ID"],id:0,deliveryDirectives:e||null})}}get nextLoadLevel(){return this.manualLevelIndex!==-1?this.manualLevelIndex:this.hls.nextAutoLevel}set nextLoadLevel(e){this.level=e,this.manualLevelIndex===-1&&(this.hls.nextAutoLevel=e)}removeLevel(e){var t;const i=this._levels.filter((r,n)=>n!==e?!0:(this.steering&&this.steering.removeLevel(r),r===this.currentLevel&&(this.currentLevel=null,this.currentLevelIndex=-1,r.details&&r.details.fragments.forEach(a=>a.level=-1)),!1));Gr(i),this._levels=i,this.currentLevelIndex>-1&&(t=this.currentLevel)!=null&&t.details&&(this.currentLevelIndex=this.currentLevel.details.fragments[0].level),this.hls.trigger(p.LEVELS_UPDATED,{levels:i})}onLevelsUpdated(e,{levels:t}){this._levels=t}checkMaxAutoUpdated(){const{autoLevelCapping:e,maxAutoLevel:t,maxHdcpLevel:i}=this.hls;this._maxAutoLevel!==t&&(this._maxAutoLevel=t,this.hls.trigger(p.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:e,levels:this.levels,maxAutoLevel:t,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:i}))}}function aa(s){const e={};s.forEach(t=>{const i=t.groupId||"";t.id=e[i]=e[i]||0,e[i]++})}class xh{constructor(e){this.config=void 0,this.keyUriToKeyInfo={},this.emeController=null,this.config=e}abort(e){for(const i in this.keyUriToKeyInfo){const r=this.keyUriToKeyInfo[i].loader;if(r){var t;if(e&&e!==((t=r.context)==null?void 0:t.frag.type))return;r.abort()}}}detach(){for(const e in this.keyUriToKeyInfo){const t=this.keyUriToKeyInfo[e];(t.mediaKeySessionContext||t.decryptdata.isCommonEncryption)&&delete this.keyUriToKeyInfo[e]}}destroy(){this.detach();for(const e in this.keyUriToKeyInfo){const t=this.keyUriToKeyInfo[e].loader;t&&t.destroy()}this.keyUriToKeyInfo={}}createKeyLoadError(e,t=_.KEY_LOAD_ERROR,i,r,n){return new $e({type:q.NETWORK_ERROR,details:t,fatal:!1,frag:e,response:n,error:i,networkDetails:r})}loadClear(e,t){if(this.emeController&&this.config.emeEnabled){const{sn:i,cc:r}=e;for(let n=0;n<t.length;n++){const a=t[n];if(r<=a.cc&&(i==="initSegment"||a.sn==="initSegment"||i<a.sn)){this.emeController.selectKeySystemFormat(a).then(o=>{a.setKeyFormat(o)});break}}}}load(e){return!e.decryptdata&&e.encrypted&&this.emeController?this.emeController.selectKeySystemFormat(e).then(t=>this.loadInternal(e,t)):this.loadInternal(e)}loadInternal(e,t){var i,r;t&&e.setKeyFormat(t);const n=e.decryptdata;if(!n){const c=new Error(t?`Expected frag.decryptdata to be defined after setting format ${t}`:"Missing decryption data on fragment in onKeyLoading");return Promise.reject(this.createKeyLoadError(e,_.KEY_LOAD_ERROR,c))}const a=n.uri;if(!a)return Promise.reject(this.createKeyLoadError(e,_.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${a}"`)));let o=this.keyUriToKeyInfo[a];if((i=o)!=null&&i.decryptdata.key)return n.key=o.decryptdata.key,Promise.resolve({frag:e,keyInfo:o});if((r=o)!=null&&r.keyLoadPromise){var l;switch((l=o.mediaKeySessionContext)==null?void 0:l.keyStatus){case void 0:case"status-pending":case"usable":case"usable-in-future":return o.keyLoadPromise.then(c=>(n.key=c.keyInfo.decryptdata.key,{frag:e,keyInfo:o}))}}switch(o=this.keyUriToKeyInfo[a]={decryptdata:n,keyLoadPromise:null,loader:null,mediaKeySessionContext:null},n.method){case"ISO-23001-7":case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return n.keyFormat==="identity"?this.loadKeyHTTP(o,e):this.loadKeyEME(o,e);case"AES-128":return this.loadKeyHTTP(o,e);default:return Promise.reject(this.createKeyLoadError(e,_.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${n.method}"`)))}}loadKeyEME(e,t){const i={frag:t,keyInfo:e};if(this.emeController&&this.config.emeEnabled){const r=this.emeController.loadKey(i);if(r)return(e.keyLoadPromise=r.then(n=>(e.mediaKeySessionContext=n,i))).catch(n=>{throw e.keyLoadPromise=null,n})}return Promise.resolve(i)}loadKeyHTTP(e,t){const i=this.config,r=i.loader,n=new r(i);return t.keyLoader=e.loader=n,e.keyLoadPromise=new Promise((a,o)=>{const l={keyInfo:e,frag:t,responseType:"arraybuffer",url:e.decryptdata.uri},c=i.keyLoadPolicy.default,u={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},h={onSuccess:(d,f,g,m)=>{const{frag:y,keyInfo:v,url:T}=g;if(!y.decryptdata||v!==this.keyUriToKeyInfo[T])return o(this.createKeyLoadError(y,_.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),m));v.decryptdata.key=y.decryptdata.key=new Uint8Array(d.data),y.keyLoader=null,v.loader=null,a({frag:y,keyInfo:v})},onError:(d,f,g,m)=>{this.resetLoader(f),o(this.createKeyLoadError(t,_.KEY_LOAD_ERROR,new Error(`HTTP Error ${d.code} loading key ${d.text}`),g,he({url:l.url,data:void 0},d)))},onTimeout:(d,f,g)=>{this.resetLoader(f),o(this.createKeyLoadError(t,_.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),g))},onAbort:(d,f,g)=>{this.resetLoader(f),o(this.createKeyLoadError(t,_.INTERNAL_ABORTED,new Error("key loading aborted"),g))}};n.load(l,u,h)})}resetLoader(e){const{frag:t,keyInfo:i,url:r}=e,n=i.loader;t.keyLoader===n&&(t.keyLoader=null,i.loader=null),delete this.keyUriToKeyInfo[r],n&&n.destroy()}}function oa(){return self.SourceBuffer||self.WebKitSourceBuffer}function la(){if(!et())return!1;const e=oa();return!e||e.prototype&&typeof e.prototype.appendBuffer=="function"&&typeof e.prototype.remove=="function"}function Th(){if(!la())return!1;const s=et();return typeof(s==null?void 0:s.isTypeSupported)=="function"&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some(e=>s.isTypeSupported(vt(e,"video")))||["mp4a.40.2","fLaC"].some(e=>s.isTypeSupported(vt(e,"audio"))))}function Eh(){var s;const e=oa();return typeof(e==null||(s=e.prototype)==null?void 0:s.changeType)=="function"}const Sh=250,ti=2,bh=.1,Ah=.05;class Lh{constructor(e,t,i,r){this.config=void 0,this.media=null,this.fragmentTracker=void 0,this.hls=void 0,this.nudgeRetry=0,this.stallReported=!1,this.stalled=null,this.moved=!1,this.seeking=!1,this.config=e,this.media=t,this.fragmentTracker=i,this.hls=r}destroy(){this.media=null,this.hls=this.fragmentTracker=null}poll(e,t){const{config:i,media:r,stalled:n}=this;if(r===null)return;const{currentTime:a,seeking:o}=r,l=this.seeking&&!o,c=!this.seeking&&o;if(this.seeking=o,a!==e){if(this.moved=!0,o||(this.nudgeRetry=0),n!==null){if(this.stallReported){const y=self.performance.now()-n;S.warn(`playback not stuck anymore @${a}, after ${Math.round(y)}ms`),this.stallReported=!1}this.stalled=null}return}if(c||l){this.stalled=null;return}if(r.paused&&!o||r.ended||r.playbackRate===0||!se.getBuffered(r).length){this.nudgeRetry=0;return}const u=se.bufferInfo(r,a,0),h=u.nextStart||0;if(o){const y=u.len>ti,v=!h||t&&t.start<=a||h-a>ti&&!this.fragmentTracker.getPartialFragment(a);if(y||v)return;this.moved=!1}if(!this.moved&&this.stalled!==null){var d;if(!(u.len>0)&&!h)return;const v=Math.max(h,u.start||0)-a,T=this.hls.levels?this.hls.levels[this.hls.currentLevel]:null,L=(T==null||(d=T.details)==null?void 0:d.live)?T.details.targetduration*2:ti,E=this.fragmentTracker.getPartialFragment(a);if(v>0&&(v<=L||E)){r.paused||this._trySkipBufferHole(E);return}}const f=self.performance.now();if(n===null){this.stalled=f;return}const g=f-n;if(!o&&g>=Sh&&(this._reportStall(u),!this.media))return;const m=se.bufferInfo(r,a,i.maxBufferHole);this._tryFixBufferStall(m,g)}_tryFixBufferStall(e,t){const{config:i,fragmentTracker:r,media:n}=this;if(n===null)return;const a=n.currentTime,o=r.getPartialFragment(a);o&&(this._trySkipBufferHole(o)||!this.media)||(e.len>i.maxBufferHole||e.nextStart&&e.nextStart-a<i.maxBufferHole)&&t>i.highBufferWatchdogPeriod*1e3&&(S.warn("Trying to nudge playhead over buffer-hole"),this.stalled=null,this._tryNudgeBuffer())}_reportStall(e){const{hls:t,media:i,stallReported:r}=this;if(!r&&i){this.stallReported=!0;const n=new Error(`Playback stalling at @${i.currentTime} due to low buffer (${JSON.stringify(e)})`);S.warn(n.message),t.trigger(p.ERROR,{type:q.MEDIA_ERROR,details:_.BUFFER_STALLED_ERROR,fatal:!1,error:n,buffer:e.len})}}_trySkipBufferHole(e){const{config:t,hls:i,media:r}=this;if(r===null)return 0;const n=r.currentTime,a=se.bufferInfo(r,n,0),o=n<a.start?a.start:a.nextStart;if(o){const l=a.len<=t.maxBufferHole,c=a.len>0&&a.len<1&&r.readyState<3,u=o-n;if(u>0&&(l||c)){if(u>t.maxBufferHole){const{fragmentTracker:d}=this;let f=!1;if(n===0){const g=d.getAppendedFrag(0,j.MAIN);g&&o<g.end&&(f=!0)}if(!f){const g=e||d.getAppendedFrag(n,j.MAIN);if(g){let m=!1,y=g.end;for(;y<o;){const v=d.getPartialFragment(y);if(v)y+=v.duration;else{m=!0;break}}if(m)return 0}}}const h=Math.max(o+Ah,n+bh);if(S.warn(`skipping hole, adjusting currentTime from ${n} to ${h}`),this.moved=!0,this.stalled=null,r.currentTime=h,e&&!e.gap){const d=new Error(`fragment loaded with buffer holes, seeking from ${n} to ${h}`);i.trigger(p.ERROR,{type:q.MEDIA_ERROR,details:_.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:d,reason:d.message,frag:e})}return h}}return 0}_tryNudgeBuffer(){const{config:e,hls:t,media:i,nudgeRetry:r}=this;if(i===null)return;const n=i.currentTime;if(this.nudgeRetry++,r<e.nudgeMaxRetry){const a=n+(r+1)*e.nudgeOffset,o=new Error(`Nudging 'currentTime' from ${n} to ${a}`);S.warn(o.message),i.currentTime=a,t.trigger(p.ERROR,{type:q.MEDIA_ERROR,details:_.BUFFER_NUDGE_ON_STALL,error:o,fatal:!1})}else{const a=new Error(`Playhead still not moving while enough data buffered @${n} after ${e.nudgeMaxRetry} nudges`);S.error(a.message),t.trigger(p.ERROR,{type:q.MEDIA_ERROR,details:_.BUFFER_STALLED_ERROR,error:a,fatal:!0})}}}const Rh=100;class Ch extends $i{constructor(e,t,i){super(e,t,i,"[stream-controller]",j.MAIN),this.audioCodecSwap=!1,this.gapController=null,this.level=-1,this._forceStartLoad=!1,this.altAudio=!1,this.audioOnly=!1,this.fragPlaying=null,this.onvplaying=null,this.onvseeked=null,this.fragLastKbps=0,this.couldBacktrack=!1,this.backtrackFragment=null,this.audioCodecSwitch=!1,this.videoBuffer=null,this._registerListeners()}_registerListeners(){const{hls:e}=this;e.on(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.MANIFEST_PARSED,this.onManifestParsed,this),e.on(p.LEVEL_LOADING,this.onLevelLoading,this),e.on(p.LEVEL_LOADED,this.onLevelLoaded,this),e.on(p.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.on(p.ERROR,this.onError,this),e.on(p.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(p.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.on(p.BUFFER_CREATED,this.onBufferCreated,this),e.on(p.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(p.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(p.FRAG_BUFFERED,this.onFragBuffered,this)}_unregisterListeners(){const{hls:e}=this;e.off(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.MANIFEST_PARSED,this.onManifestParsed,this),e.off(p.LEVEL_LOADED,this.onLevelLoaded,this),e.off(p.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.off(p.ERROR,this.onError,this),e.off(p.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(p.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.off(p.BUFFER_CREATED,this.onBufferCreated,this),e.off(p.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(p.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(p.FRAG_BUFFERED,this.onFragBuffered,this)}onHandlerDestroying(){this._unregisterListeners(),super.onHandlerDestroying()}startLoad(e){if(this.levels){const{lastCurrentTime:t,hls:i}=this;if(this.stopLoad(),this.setInterval(Rh),this.level=-1,!this.startFragRequested){let r=i.startLevel;r===-1&&(i.config.testBandwidth&&this.levels.length>1?(r=0,this.bitrateTest=!0):r=i.firstAutoLevel),i.nextLoadLevel=r,this.level=i.loadLevel,this.loadedmetadata=!1}t>0&&e===-1&&(this.log(`Override startPosition with lastCurrentTime @${t.toFixed(3)}`),e=t),this.state=F.IDLE,this.nextLoadPosition=this.startPosition=this.lastCurrentTime=e,this.tick()}else this._forceStartLoad=!0,this.state=F.STOPPED}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case F.WAITING_LEVEL:{const{levels:t,level:i}=this,r=t==null?void 0:t[i],n=r==null?void 0:r.details;if(n&&(!n.live||this.levelLastLoaded===r)){if(this.waitForCdnTuneIn(n))break;this.state=F.IDLE;break}else if(this.hls.nextLoadLevel!==this.level){this.state=F.IDLE;break}break}case F.FRAG_LOADING_WAITING_RETRY:{var e;const t=self.performance.now(),i=this.retryDate;if(!i||t>=i||(e=this.media)!=null&&e.seeking){const{levels:r,level:n}=this,a=r==null?void 0:r[n];this.resetStartWhenNotLoaded(a||null),this.state=F.IDLE}}break}this.state===F.IDLE&&this.doTickIdle(),this.onTickEnd()}onTickEnd(){super.onTickEnd(),this.checkBuffer(),this.checkFragmentChanged()}doTickIdle(){const{hls:e,levelLastLoaded:t,levels:i,media:r}=this;if(t===null||!r&&(this.startFragRequested||!e.config.startFragPrefetch)||this.altAudio&&this.audioOnly)return;const n=e.nextLoadLevel;if(!(i!=null&&i[n]))return;const a=i[n],o=this.getMainFwdBufferInfo();if(o===null)return;const l=this.getLevelDetails();if(l&&this._streamEnded(o,l)){const m={};this.altAudio&&(m.type="video"),this.hls.trigger(p.BUFFER_EOS,m),this.state=F.ENDED;return}e.loadLevel!==n&&e.manualLevel===-1&&this.log(`Adapting to level ${n} from level ${this.level}`),this.level=e.nextLoadLevel=n;const c=a.details;if(!c||this.state===F.WAITING_LEVEL||c.live&&this.levelLastLoaded!==a){this.level=n,this.state=F.WAITING_LEVEL;return}const u=o.len,h=this.getMaxBufferLength(a.maxBitrate);if(u>=h)return;this.backtrackFragment&&this.backtrackFragment.start>o.end&&(this.backtrackFragment=null);const d=this.backtrackFragment?this.backtrackFragment.start:o.end;let f=this.getNextFragment(d,c);if(this.couldBacktrack&&!this.fragPrevious&&f&&f.sn!=="initSegment"&&this.fragmentTracker.getState(f)!==de.OK){var g;const y=((g=this.backtrackFragment)!=null?g:f).sn-c.startSN,v=c.fragments[y-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,d)){if(!f.gap){const y=this.audioOnly&&!this.altAudio?te.AUDIO:te.VIDEO,v=(y===te.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;v&&this.afterBufferFlushed(v,y,j.MAIN)}f=this.getNextFragmentLoopLoading(f,c,o,j.MAIN,h)}f&&(f.initSegment&&!f.initSegment.data&&!this.bitrateTest&&(f=f.initSegment),this.loadFragment(f,a,d))}loadFragment(e,t,i){const r=this.fragmentTracker.getState(e);this.fragCurrent=e,r===de.NOT_LOADED||r===de.PARTIAL?e.sn==="initSegment"?this._loadInitSegment(e,t):this.bitrateTest?(this.log(`Fragment ${e.sn} of level ${e.level} is being downloaded to test bitrate and will not be buffered`),this._loadBitrateTestFrag(e,t)):(this.startFragRequested=!0,super.loadFragment(e,t,i)):this.clearTrackerIfNeeded(e)}getBufferedFrag(e){return this.fragmentTracker.getBufferedFrag(e,j.MAIN)}followingBufferedFrag(e){return e?this.getBufferedFrag(e.end+.5):null}immediateLevelSwitch(){this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY)}nextLevelSwitch(){const{levels:e,media:t}=this;if(t!=null&&t.readyState){let i;const r=this.getAppendedFrag(t.currentTime);r&&r.start>1&&this.flushMainBuffer(0,r.start-1);const n=this.getLevelDetails();if(n!=null&&n.live){const o=this.getMainFwdBufferInfo();if(!o||o.len<n.targetduration*2)return}if(!t.paused&&e){const o=this.hls.nextLoadLevel,l=e[o],c=this.fragLastKbps;c&&this.fragCurrent?i=this.fragCurrent.duration*l.maxBitrate/(1e3*c)+1:i=0}else i=0;const a=this.getBufferedFrag(t.currentTime+i);if(a){const o=this.followingBufferedFrag(a);if(o){this.abortCurrentFrag();const l=o.maxStartPTS?o.maxStartPTS:o.start,c=o.duration,u=Math.max(a.end,l+Math.min(Math.max(c-this.config.maxFragLookUpTolerance,c*(this.couldBacktrack?.5:.125)),c*(this.couldBacktrack?.75:.25)));this.flushMainBuffer(u,Number.POSITIVE_INFINITY)}}}}abortCurrentFrag(){const e=this.fragCurrent;switch(this.fragCurrent=null,this.backtrackFragment=null,e&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.state){case F.KEY_LOADING:case F.FRAG_LOADING:case F.FRAG_LOADING_WAITING_RETRY:case F.PARSING:case F.PARSED:this.state=F.IDLE;break}this.nextLoadPosition=this.getLoadPosition()}flushMainBuffer(e,t){super.flushMainBuffer(e,t,this.altAudio?"video":null)}onMediaAttached(e,t){super.onMediaAttached(e,t);const i=t.media;this.onvplaying=this.onMediaPlaying.bind(this),this.onvseeked=this.onMediaSeeked.bind(this),i.addEventListener("playing",this.onvplaying),i.addEventListener("seeked",this.onvseeked),this.gapController=new Lh(this.config,i,this.fragmentTracker,this.hls)}onMediaDetaching(){const{media:e}=this;e&&this.onvplaying&&this.onvseeked&&(e.removeEventListener("playing",this.onvplaying),e.removeEventListener("seeked",this.onvseeked),this.onvplaying=this.onvseeked=null,this.videoBuffer=null),this.fragPlaying=null,this.gapController&&(this.gapController.destroy(),this.gapController=null),super.onMediaDetaching()}onMediaPlaying(){this.tick()}onMediaSeeked(){const e=this.media,t=e?e.currentTime:null;K(t)&&this.log(`Media seeked to ${t.toFixed(3)}`);const i=this.getMainFwdBufferInfo();if(i===null||i.len===0){this.warn(`Main forward buffer length on "seeked" event ${i?i.len:"empty"})`);return}this.tick()}onManifestLoading(){this.log("Trigger BUFFER_RESET"),this.hls.trigger(p.BUFFER_RESET,void 0),this.fragmentTracker.removeAllFragments(),this.couldBacktrack=!1,this.startPosition=this.lastCurrentTime=this.fragLastKbps=0,this.levels=this.fragPlaying=this.backtrackFragment=this.levelLastLoaded=null,this.altAudio=this.audioOnly=this.startFragRequested=!1}onManifestParsed(e,t){let i=!1,r=!1;t.levels.forEach(n=>{const a=n.audioCodec;a&&(i=i||a.indexOf("mp4a.40.2")!==-1,r=r||a.indexOf("mp4a.40.5")!==-1)}),this.audioCodecSwitch=i&&r&&!Eh(),this.audioCodecSwitch&&this.log("Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC"),this.levels=t.levels,this.startFragRequested=!1}onLevelLoading(e,t){const{levels:i}=this;if(!i||this.state!==F.IDLE)return;const r=i[t.level];(!r.details||r.details.live&&this.levelLastLoaded!==r||this.waitForCdnTuneIn(r.details))&&(this.state=F.WAITING_LEVEL)}onLevelLoaded(e,t){var i;const{levels:r}=this,n=t.level,a=t.details,o=a.totalduration;if(!r){this.warn(`Levels were reset while loading level ${n}`);return}this.log(`Level ${n} loaded [${a.startSN},${a.endSN}]${a.lastPartSn?`[part-${a.lastPartSn}-${a.lastPartIndex}]`:""}, cc [${a.startCC}, ${a.endCC}] duration:${o}`);const l=r[n],c=this.fragCurrent;c&&(this.state===F.FRAG_LOADING||this.state===F.FRAG_LOADING_WAITING_RETRY)&&c.level!==t.level&&c.loader&&this.abortCurrentFrag();let u=0;if(a.live||(i=l.details)!=null&&i.live){var h;if(this.checkLiveUpdate(a),a.deltaUpdateFailed)return;u=this.alignPlaylists(a,l.details,(h=this.levelLastLoaded)==null?void 0:h.details)}if(l.details=a,this.levelLastLoaded=l,this.hls.trigger(p.LEVEL_UPDATED,{details:a,level:n}),this.state===F.WAITING_LEVEL){if(this.waitForCdnTuneIn(a))return;this.state=F.IDLE}this.startFragRequested?a.live&&this.synchronizeToLiveEdge(a):this.setStartPosition(a,u),this.tick()}_handleFragmentLoadProgress(e){var t;const{frag:i,part:r,payload:n}=e,{levels:a}=this;if(!a){this.warn(`Levels were reset while fragment load was in progress. Fragment ${i.sn} of level ${i.level} will not be buffered`);return}const o=a[i.level],l=o.details;if(!l){this.warn(`Dropping fragment ${i.sn} of level ${i.level} after level details were reset`),this.fragmentTracker.removeFragment(i);return}const c=o.videoCodec,u=l.PTSKnown||!l.live,h=(t=i.initSegment)==null?void 0:t.data,d=this._getAudioCodec(o),f=this.transmuxer=this.transmuxer||new Sn(this.hls,j.MAIN,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),g=r?r.index:-1,m=g!==-1,y=new Bi(i.level,i.sn,i.stats.chunkCount,n.byteLength,g,m),v=this.initPTS[i.cc];f.push(n,h,d,c,i,r,l.totalduration,u,y,v)}onAudioTrackSwitching(e,t){const i=this.altAudio;if(!!!t.url){if(this.mediaBuffer!==this.media){this.log("Switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;const 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();const n=this.hls;i&&(n.trigger(p.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null}),this.fragmentTracker.removeAllFragments()),n.trigger(p.AUDIO_TRACK_SWITCHED,t)}}onAudioTrackSwitched(e,t){const i=t.id,r=!!this.hls.audioTracks[i].url;if(r){const n=this.videoBuffer;n&&this.mediaBuffer!==n&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=n)}this.altAudio=r,this.tick()}onBufferCreated(e,t){const i=t.tracks;let r,n,a=!1;for(const o in i){const l=i[o];if(l.id==="main"){if(n=o,r=l,o==="video"){const c=i[o];c&&(this.videoBuffer=c.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){const{frag:i,part:r}=t;if(i&&i.type!==j.MAIN)return;if(this.fragContextChanged(i)){this.warn(`Fragment ${i.sn}${r?" p: "+r.index:""} of level ${i.level} finished buffering, but was aborted. state: ${this.state}`),this.state===F.PARSED&&(this.state=F.IDLE);return}const n=r?r.stats:i.stats;this.fragLastKbps=Math.round(8*n.total/(n.buffering.end-n.loading.first)),i.sn!=="initSegment"&&(this.fragPrevious=i),this.fragBufferedComplete(i,r)}onError(e,t){var i;if(t.fatal){this.state=F.ERROR;return}switch(t.details){case _.FRAG_GAP:case _.FRAG_PARSING_ERROR:case _.FRAG_DECRYPT_ERROR:case _.FRAG_LOAD_ERROR:case _.FRAG_LOAD_TIMEOUT:case _.KEY_LOAD_ERROR:case _.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(j.MAIN,t);break;case _.LEVEL_LOAD_ERROR:case _.LEVEL_LOAD_TIMEOUT:case _.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===F.WAITING_LEVEL&&((i=t.context)==null?void 0:i.type)===ee.LEVEL&&(this.state=F.IDLE);break;case _.BUFFER_APPEND_ERROR:case _.BUFFER_FULL_ERROR:if(!t.parent||t.parent!=="main")return;if(t.details===_.BUFFER_APPEND_ERROR){this.resetLoadingState();return}this.reduceLengthAndFlushBuffer(t)&&this.flushMainBuffer(0,Number.POSITIVE_INFINITY);break;case _.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}checkBuffer(){const{media:e,gapController:t}=this;if(!(!e||!t||!e.readyState)){if(this.loadedmetadata||!se.getBuffered(e).length){const i=this.state!==F.IDLE?this.fragCurrent:null;t.poll(this.lastCurrentTime,i)}this.lastCurrentTime=e.currentTime}}onFragLoadEmergencyAborted(){this.state=F.IDLE,this.loadedmetadata||(this.startFragRequested=!1,this.nextLoadPosition=this.startPosition),this.tickImmediate()}onBufferFlushed(e,{type:t}){if(t!==te.AUDIO||this.audioOnly&&!this.altAudio){const i=(t===te.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;this.afterBufferFlushed(i,t,j.MAIN),this.tick()}}onLevelsUpdated(e,t){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level),this.levels=t.levels}swapAudioCodec(){this.audioCodecSwap=!this.audioCodecSwap}seekToStartPos(){const{media:e}=this;if(!e)return;const t=e.currentTime;let i=this.startPosition;if(i>=0&&t<i){if(e.seeking){this.log(`could not seek to ${i}, already seeking at ${t}`);return}const r=se.getBuffered(e),a=(r.length?r.start(0):0)-i;a>0&&(a<this.config.maxBufferHole||a<this.config.maxFragLookUpTolerance)&&(this.log(`adjusting start position by ${a} to match buffer start`),i+=a,this.startPosition=i),this.log(`seek to target start position ${i} from current time ${t}`),e.currentTime=i}}_getAudioCodec(e){let t=this.config.defaultAudioCodec||e.audioCodec;return this.audioCodecSwap&&t&&(this.log("Swapping audio codec"),t.indexOf("mp4a.40.5")!==-1?t="mp4a.40.2":t="mp4a.40.5"),t}_loadBitrateTestFrag(e,t){e.bitrateTest=!0,this._doFragLoad(e,t).then(i=>{const{hls:r}=this;if(!i||this.fragContextChanged(e))return;t.fragmentError=0,this.state=F.IDLE,this.startFragRequested=!1,this.bitrateTest=!1;const n=e.stats;n.parsing.start=n.parsing.end=n.buffering.start=n.buffering.end=self.performance.now(),r.trigger(p.FRAG_LOADED,i),e.bitrateTest=!1})}_handleTransmuxComplete(e){var t;const i="main",{hls:r}=this,{remuxResult:n,chunkMeta:a}=e,o=this.getCurrentContext(a);if(!o){this.resetWhenMissingContext(a);return}const{frag:l,part:c,level:u}=o,{video:h,text:d,id3:f,initSegment:g}=n,{details:m}=u,y=this.altAudio?void 0:n.audio;if(this.fragContextChanged(l)){this.fragmentTracker.removeFragment(l);return}if(this.state=F.PARSING,g){if(g!=null&&g.tracks){const x=l.initSegment||l;this._bufferInitSegment(u,g.tracks,x,a),r.trigger(p.FRAG_PARSING_INIT_SEGMENT,{frag:x,id:i,tracks:g.tracks})}const v=g.initPTS,T=g.timescale;K(v)&&(this.initPTS[l.cc]={baseTime:v,timescale:T},r.trigger(p.INIT_PTS_FOUND,{frag:l,id:i,initPTS:v,timescale:T}))}if(h&&m&&l.sn!=="initSegment"){const v=m.fragments[l.sn-1-m.startSN],T=l.sn===m.startSN,x=!v||l.cc>v.cc;if(n.independent!==!1){const{startPTS:L,endPTS:E,startDTS:w,endDTS:R}=h;if(c)c.elementaryStreams[h.type]={startPTS:L,endPTS:E,startDTS:w,endDTS:R};else if(h.firstKeyFrame&&h.independent&&a.id===1&&!x&&(this.couldBacktrack=!0),h.dropped&&h.independent){const B=this.getMainFwdBufferInfo(),C=(B?B.end:this.getLoadPosition())+this.config.maxBufferHole,b=h.firstKeyFramePTS?h.firstKeyFramePTS:L;if(!T&&C<b-this.config.maxBufferHole&&!x){this.backtrack(l);return}else x&&(l.gap=!0);l.setElementaryStreamInfo(h.type,l.start,E,l.start,R,!0)}else T&&L>ti&&(l.gap=!0);l.setElementaryStreamInfo(h.type,L,E,w,R),this.backtrackFragment&&(this.backtrackFragment=l),this.bufferFragmentData(h,l,c,a,T||x)}else if(T||x)l.gap=!0;else{this.backtrack(l);return}}if(y){const{startPTS:v,endPTS:T,startDTS:x,endDTS:L}=y;c&&(c.elementaryStreams[te.AUDIO]={startPTS:v,endPTS:T,startDTS:x,endDTS:L}),l.setElementaryStreamInfo(te.AUDIO,v,T,x,L),this.bufferFragmentData(y,l,c,a)}if(m&&f!=null&&(t=f.samples)!=null&&t.length){const v={id:i,frag:l,details:m,samples:f.samples};r.trigger(p.FRAG_PARSING_METADATA,v)}if(m&&d){const v={id:i,frag:l,details:m,samples:d.samples};r.trigger(p.FRAG_PARSING_USERDATA,v)}}_bufferInitSegment(e,t,i,r){if(this.state!==F.PARSING)return;this.audioOnly=!!t.audio&&!t.video,this.altAudio&&!this.audioOnly&&delete t.audio;const{audio:n,video:a,audiovideo:o}=t;if(n){let l=e.audioCodec;const c=navigator.userAgent.toLowerCase();this.audioCodecSwitch&&(l&&(l.indexOf("mp4a.40.5")!==-1?l="mp4a.40.2":l="mp4a.40.5"),n.metadata.channelCount!==1&&c.indexOf("firefox")===-1&&(l="mp4a.40.5")),l&&l.indexOf("mp4a.40.5")!==-1&&c.indexOf("android")!==-1&&n.container!=="audio/mpeg"&&(l="mp4a.40.2",this.log(`Android: force audio codec to ${l}`)),e.audioCodec&&e.audioCodec!==l&&this.log(`Swapping manifest audio codec "${e.audioCodec}" for "${l}"`),n.levelCodec=l,n.id="main",this.log(`Init audio buffer, container:${n.container}, codecs[selected/level/parsed]=[${l||""}/${e.audioCodec||""}/${n.codec}]`)}a&&(a.levelCodec=e.videoCodec,a.id="main",this.log(`Init video buffer, container:${a.container}, codecs[level/parsed]=[${e.videoCodec||""}/${a.codec}]`)),o&&this.log(`Init audiovideo buffer, container:${o.container}, codecs[level/parsed]=[${e.codecs}/${o.codec}]`),this.hls.trigger(p.BUFFER_CODECS,t),Object.keys(t).forEach(l=>{const u=t[l].initSegment;u!=null&&u.byteLength&&this.hls.trigger(p.BUFFER_APPENDING,{type:l,data:u,frag:i,part:null,chunkMeta:r,parent:i.type})}),this.tickImmediate()}getMainFwdBufferInfo(){return this.getFwdBufferInfo(this.mediaBuffer?this.mediaBuffer:this.media,j.MAIN)}backtrack(e){this.couldBacktrack=!0,this.backtrackFragment=e,this.resetTransmuxer(),this.flushBufferGap(e),this.fragmentTracker.removeFragment(e),this.fragPrevious=null,this.nextLoadPosition=e.start,this.state=F.IDLE}checkFragmentChanged(){const e=this.media;let t=null;if(e&&e.readyState>1&&e.seeking===!1){const i=e.currentTime;if(se.isBuffered(e,i)?t=this.getAppendedFrag(i):se.isBuffered(e,i+.1)&&(t=this.getAppendedFrag(i+.1)),t){this.backtrackFragment=null;const r=this.fragPlaying,n=t.level;(!r||t.sn!==r.sn||r.level!==n)&&(this.fragPlaying=t,this.hls.trigger(p.FRAG_CHANGED,{frag:t}),(!r||r.level!==n)&&this.hls.trigger(p.LEVEL_SWITCHED,{level:n}))}}}get nextLevel(){const e=this.nextBufferedFrag;return e?e.level:-1}get currentFrag(){const e=this.media;return e?this.fragPlaying||this.getAppendedFrag(e.currentTime):null}get currentProgramDateTime(){const e=this.media;if(e){const t=e.currentTime,i=this.currentFrag;if(i&&K(t)&&K(i.programDateTime)){const r=i.programDateTime+(t-i.start)*1e3;return new Date(r)}}return null}get currentLevel(){const e=this.currentFrag;return e?e.level:-1}get nextBufferedFrag(){const e=this.currentFrag;return e?this.followingBufferedFrag(e):null}get forceStartLoad(){return this._forceStartLoad}}class Ne{static get version(){return"1.5.6"}static isMSESupported(){return la()}static isSupported(){return Th()}static getMediaSource(){return et()}static get Events(){return p}static get ErrorTypes(){return q}static get ErrorDetails(){return _}static get DefaultConfig(){return Ne.defaultConfig?Ne.defaultConfig:na}static set DefaultConfig(e){Ne.defaultConfig=e}constructor(e={}){this.config=void 0,this.userConfig=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this.started=!1,this._emitter=new qi,this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.abrController=void 0,this.bufferController=void 0,this.capLevelController=void 0,this.latencyController=void 0,this.levelController=void 0,this.streamController=void 0,this.audioTrackController=void 0,this.subtitleTrackController=void 0,this.emeController=void 0,this.cmcdController=void 0,this._media=null,this.url=null,this.triggeringException=void 0,xo(e.debug||!1,"Hls instance");const t=this.config=ph(Ne.DefaultConfig,e);this.userConfig=e,t.progressive&&yh(t);const{abrController:i,bufferController:r,capLevelController:n,errorController:a,fpsController:o}=t,l=new a(this),c=this.abrController=new i(this),u=this.bufferController=new r(this),h=this.capLevelController=new n(this),d=new o(this),f=new dl(this),g=new yl(this),m=t.contentSteeringController,y=m?new m(this):null,v=this.levelController=new vh(this,y),T=new zl(this),x=new xh(this.config),L=this.streamController=new Ch(this,T,x);h.setStreamController(L),d.setStreamController(L);const E=[f,v,L];y&&E.splice(1,0,y),this.networkControllers=E;const w=[c,u,h,d,g,T];this.audioTrackController=this.createController(t.audioTrackController,E);const R=t.audioStreamController;R&&E.push(new R(this,T,x)),this.subtitleTrackController=this.createController(t.subtitleTrackController,E);const B=t.subtitleStreamController;B&&E.push(new B(this,T,x)),this.createController(t.timelineController,w),x.emeController=this.emeController=this.createController(t.emeController,w),this.cmcdController=this.createController(t.cmcdController,w),this.latencyController=this.createController(vl,w),this.coreComponents=w,E.push(l);const C=l.onErrorOut;typeof C=="function"&&this.on(p.ERROR,C,l)}createController(e,t){if(e){const i=new e(this);return t&&t.push(i),i}return null}on(e,t,i=this){this._emitter.on(e,t,i)}once(e,t,i=this){this._emitter.once(e,t,i)}removeAllListeners(e){this._emitter.removeAllListeners(e)}off(e,t,i=this,r){this._emitter.off(e,t,i,r)}listeners(e){return this._emitter.listeners(e)}emit(e,t,i){return this._emitter.emit(e,t,i)}trigger(e,t){if(this.config.debug)return this.emit(e,e,t);try{return this.emit(e,e,t)}catch(i){if(S.error("An internal error happened while handling event "+e+'. Error message: "'+i.message+'". Here is a stacktrace:',i),!this.triggeringException){this.triggeringException=!0;const r=e===p.ERROR;this.trigger(p.ERROR,{type:q.OTHER_ERROR,details:_.INTERNAL_EXCEPTION,fatal:r,event:e,error:i}),this.triggeringException=!1}}return!1}listenerCount(e){return this._emitter.listenerCount(e)}destroy(){S.log("destroy"),this.trigger(p.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;const e=this.config;e.xhrSetup=e.fetchSetup=void 0,this.userConfig=null}attachMedia(e){S.log("attachMedia"),this._media=e,this.trigger(p.MEDIA_ATTACHING,{media:e})}detachMedia(){S.log("detachMedia"),this.trigger(p.MEDIA_DETACHING,void 0),this._media=null}loadSource(e){this.stopLoad();const t=this.media,i=this.url,r=this.url=gi.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,S.log(`loadSource:${r}`),t&&i&&(i!==r||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(t)),this.trigger(p.MANIFEST_LOADING,{url:e})}startLoad(e=-1){S.log(`startLoad(${e})`),this.started=!0,this.networkControllers.forEach(t=>{t.startLoad(e)})}stopLoad(){S.log("stopLoad"),this.started=!1,this.networkControllers.forEach(e=>{e.stopLoad()})}resumeBuffering(){this.started&&this.networkControllers.forEach(e=>{"fragmentLoader"in e&&e.startLoad(-1)})}pauseBuffering(){this.networkControllers.forEach(e=>{"fragmentLoader"in e&&e.stopLoad()})}swapAudioCodec(){S.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){S.log("recoverMediaError");const e=this._media;this.detachMedia(),e&&this.attachMedia(e)}removeLevel(e){this.levelController.removeLevel(e)}get levels(){const e=this.levelController.levels;return e||[]}get currentLevel(){return this.streamController.currentLevel}set currentLevel(e){S.log(`set currentLevel:${e}`),this.levelController.manualLevel=e,this.streamController.immediateLevelSwitch()}get nextLevel(){return this.streamController.nextLevel}set nextLevel(e){S.log(`set nextLevel:${e}`),this.levelController.manualLevel=e,this.streamController.nextLevelSwitch()}get loadLevel(){return this.levelController.level}set loadLevel(e){S.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){S.log(`set firstLevel:${e}`),this.levelController.firstLevel=e}get startLevel(){const e=this.levelController.startLevel;return e===-1&&this.abrController.forcedAutoLevel>-1?this.abrController.forcedAutoLevel:e}set startLevel(e){S.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){const t=!!e;t!==this.config.capLevelToPlayerSize&&(t?this.capLevelController.startCapping():(this.capLevelController.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=t)}get autoLevelCapping(){return this._autoLevelCapping}get bandwidthEstimate(){const{bwEstimator:e}=this.abrController;return e?e.getEstimate():NaN}set bandwidthEstimate(e){this.abrController.resetEstimator(e)}get ttfbEstimate(){const{bwEstimator:e}=this.abrController;return e?e.getEstimateTTFB():NaN}set autoLevelCapping(e){this._autoLevelCapping!==e&&(S.log(`set autoLevelCapping:${e}`),this._autoLevelCapping=e,this.levelController.checkMaxAutoUpdated())}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(e){xl(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(){const{levels:e,config:{minAutoBitrate:t}}=this;if(!e)return 0;const i=e.length;for(let r=0;r<i;r++)if(e[r].maxBitrate>=t)return r;return 0}get maxAutoLevel(){const{levels:e,autoLevelCapping:t,maxHdcpLevel:i}=this;let r;if(t===-1&&e!=null&&e.length?r=e.length-1:r=t,i)for(let n=r;n--;){const a=e[n].attrs["HDCP-LEVEL"];if(a&&a<=i)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()}setAudioOption(e){var t;return(t=this.audioTrackController)==null?void 0:t.setAudioOption(e)}setSubtitleOption(e){var t;return(t=this.subtitleTrackController)==null||t.setSubtitleOption(e),null}get allAudioTracks(){const e=this.audioTrackController;return e?e.allAudioTracks:[]}get audioTracks(){const e=this.audioTrackController;return e?e.audioTracks:[]}get audioTrack(){const e=this.audioTrackController;return e?e.audioTrack:-1}set audioTrack(e){const t=this.audioTrackController;t&&(t.audioTrack=e)}get allSubtitleTracks(){const e=this.subtitleTrackController;return e?e.allSubtitleTracks:[]}get subtitleTracks(){const e=this.subtitleTrackController;return e?e.subtitleTracks:[]}get subtitleTrack(){const e=this.subtitleTrackController;return e?e.subtitleTrack:-1}get media(){return this._media}set subtitleTrack(e){const t=this.subtitleTrackController;t&&(t.subtitleTrack=e)}get subtitleDisplay(){const e=this.subtitleTrackController;return e?e.subtitleDisplay:!1}set subtitleDisplay(e){const t=this.subtitleTrackController;t&&(t.subtitleDisplay=e)}get lowLatencyMode(){return this.config.lowLatencyMode}set lowLatencyMode(e){this.config.lowLatencyMode=e}get liveSyncPosition(){return this.latencyController.liveSyncPosition}get latency(){return this.latencyController.latency}get maxLatency(){return this.latencyController.maxLatency}get targetLatency(){return this.latencyController.targetLatency}get drift(){return this.latencyController.drift}get forceStartLoad(){return this.streamController.forceStartLoad}}Ne.defaultConfig=void 0;function gs(){const s=document;return!!(s.fullscreenElement||s.mozFullScreenElement||s.webkitFullscreenElement||s.msFullscreenElement)}function ca(s){if(gs())return new Promise(t=>t(null));const e=s;if(e.requestFullscreen)return e==null?void 0:e.requestFullscreen();if(e.mozRequestFullScreen)return e==null?void 0:e.mozRequestFullScreen();if(e.webkitRequestFullScreen)return e==null?void 0:e.webkitRequestFullScreen();if(e.msRequestFullscreen)return e==null?void 0:e.msRequestFullscreen()}function ua(){if(!gs())return new Promise(e=>e(null));const s=document;if(s.exitFullscreen)return s.exitFullscreen();if(s.mozCancelFullScreen)return s.mozCancelFullScreen();if(s.webkitCancelFullScreen)return s.webkitCancelFullScreen();if(s.msExitFullscreen)return s.msExitFullscreen()}function ha(s,e){let t=null;return function(...i){const r=this;t!==null&&clearTimeout(t),t=setTimeout(()=>{t=null,s.apply(r,i)},e||1e3)}}const ms=new Intl.NumberFormat(void 0,{minimumIntegerDigits:2}),da=["play","pause","ended","loadeddata","waiting","playing","timeupdate","canplay","canplaythrough","statechanged","error"],ps=s=>{const e=Math.floor(s%60),t=Math.floor(s/60)%60,i=Math.floor(s/3600);return i===0?`${t}:${ms.format(e)}`:`${i}:${ms.format(t)}:${ms.format(e)}`},Dh=Ee.extend({name:"VideoPlayer",components:{ESpinner:fi},props:{sources:{type:[Array,String],required:!0},videoListeners:{type:Object,default:()=>({})},videoOptions:{type:Object,default:()=>({})},isHls:{type:Boolean,default:!1},streamingToken:{type:String,default:""},isLiveView:{type:Boolean,default:!1}},data(){return{playing:!1,percentagePlayed:0,videoLength:"0:00",duration:0,videoDuration:0,currentTime:"0:00",realtime:0,isScrubbing:!1,wasPaused:!1,isFullscreen:!1,isFinished:!1,isLoading:!0,isError:!1,player:new Ne}},computed:{sourceItems(){return Array.isArray(this.sources)?this.sources:[{src:this.sources}]},hasStartedOrFinished(){return(this.isFinished||this.realtime<=.1)&&!this.isLoading&&!this.isLooped()},withControls(){const s=this.videoOptions;return(s==null?void 0:s.controls)===!1?"hide":""}},mounted(){this.isHls&&this.initHls(),this.bindEvents(),this.initializePlayer(),this.initializeFullscreenListeners()},beforeDestroy(){this.unbindEvents(),this.destroyPlayer(),this.removeFullscreenListeners()},methods:{initHls(){var e,t,i,r;const s=this.$refs.player;(e=this.player)!=null&&e.stopLoad&&this.player.stopLoad(),Ne.isSupported()&&(this.isLoading=!0,this.player=new Ne({startPosition:0,xhrSetup:n=>{this.streamingToken&&n.setRequestHeader("Authorization",`Bearer ${this.streamingToken}`)}}),(t=this.player)==null||t.loadSource(this.sources[0].src),(i=this.player)==null||i.attachMedia(s),(r=this.player)==null||r.on(Ne.Events.MANIFEST_PARSED,()=>{this.playing&&s.play()}))},handle404Error(){this.isError=!0,this.isLoading=!1,this.playing=!1},bindEvents(){const s=this.$refs.player;da.forEach(e=>{s.addEventListener(e,()=>this.bindVideoEvent(e),!0)})},unbindEvents(){const s=this.$refs.player;da.forEach(e=>{s.removeEventListener(e,()=>this.bindVideoEvent(e),!0)})},bindVideoEvent(s){const e=this.$refs.player,t=this.$refs.timelineContainer;s==="loadeddata"&&(this.videoLength=ps(e.duration)),s==="timeupdate"&&(this.percentagePlayed=(e==null?void 0:e.currentTime)/e.duration*100,t.style.setProperty("--progress-position",this.percentagePlayed.toString())),this.$emit(s,{event,player:e})},initializePlayer(){const s=this.$refs.player;s&&(s.autoplay&&this.setPlaying(!0),document.addEventListener("mouseup",this.handleScrubbingOnMouseEnd),document.addEventListener("keydown",this.handleKeyDown))},destroyPlayer(){window.removeEventListener("keydown",this.handleKeyDown),document.removeEventListener("mouseup",this.handleScrubbingOnMouseEnd)},removeFullscreenListeners(){document.fullscreenEnabled||document.webkitFullscreenEnabled||document.mozFullScreenEnabled||document.msFullscreenEnabled?(document.removeEventListener("fullscreenchange",this.handleFullscreenChange),document.removeEventListener("webkitfullscreenchange",this.handleFullscreenChange),document.removeEventListener("mozfullscreenchange",this.handleFullscreenChange),document.removeEventListener("MSFullscreenChange",this.handleFullscreenChange)):console.log("Fullscreen API is not supported in this browser.")},initializeFullscreenListeners(){document.fullscreenEnabled||document.webkitFullscreenEnabled||document.mozFullScreenEnabled||document.msFullscreenEnabled?(document.addEventListener("fullscreenchange",this.handleFullscreenChange),document.addEventListener("webkitfullscreenchange",this.handleFullscreenChange),document.addEventListener("mozfullscreenchange",this.handleFullscreenChange),document.addEventListener("MSFullscreenChange",this.handleFullscreenChange)):console.log("Fullscreen API is not supported in this browser.")},handleFullscreenChange(){this.isFullscreen=document.fullscreenElement||document.mozFullScreenElement||document.webkitFullscreenElement||document.msFullscreenElement||window.innerWidth==screen.width&&window.innerHeight==screen.height},isLooped(){return this.$refs.player.loop},handleScrubbingOnMouseEnd(s){this.isScrubbing&&this.toggleScrubbing(s)},handleEnded(){this.isFinished=!0,this.playing=!1},handleLoading(){this.isLoading=!1},play(){const s=this.$refs.player;if(!s)return;s.play()!==void 0&&s.play().then(()=>this.setPlaying(!0)).catch(console.error)},pause(){const s=this.$refs.player;s&&(s.pause(),this.setPlaying(!1))},togglePlay(){this.playing?this.pause():this.play()},setPlaying(s){this.playing=s},seekToPercentage(s){const e=this.$refs.player;if(!e)return;const t=s/100*e.duration;e.currentTime=t},convertTimeToDuration(s){return[parseInt(s/60%60,10),parseInt(s%60,10)].join(":").replace(/\b(\d)\b/g,"0$1")},closeFullscreenMode(){document.fullscreenElement&&(ua().then(()=>{this.isFullscreen=!1,console.log("Exited fullscreen")}),this.isFullscreen=!1)},openFullscreenMode(){const s=this.$refs.videoContainer;s&&(ca(s).then(()=>{this.isFullscreen=!0}),this.isFullscreen=!0)},toggleFullscreenMode(){this.isFullscreen?this.closeFullscreenMode():this.openFullscreenMode()},getDuration(){const s=this.$refs.player;this.videoLength=ps(s.duration),this.videoDuration=s.duration},handleTimeUpdate(){const s=this.$refs.player,e=this.$refs.timelineContainer;if(!s||!e)return;this.currentTime=ps(s.currentTime),this.realtime=s.currentTime;const t=Number(this.realtime)/Number(this.videoDuration);e.style.setProperty("--progress-position",t.toString())},handleTimelineUpdate(s){const e=this.$refs.player;if(!document.body.contains(e))return;const t=this.$refs.timelineContainer,i=t.getBoundingClientRect(),r=Math.min(Math.max(0,s.x-i.x),i.width)/i.width;t.style.setProperty("--preview-position",r.toString()),this.isScrubbing&&(s.preventDefault(),t.style.setProperty("--progress-position",r.toString()))},skip(s=5){const e=this.$refs.player;e.currentTime+=s},async toggleScrubbing(s){const e=this.$refs.timelineContainer,t=this.$refs.videoContainer,i=this.$refs.player;if(!i)return;const r=e.getBoundingClientRect(),n=Math.min(Math.max(0,s.x-r.x),r.width)/r.width;if(this.isScrubbing=(s.buttons&1)===1,t.classList.toggle("scrubbing",this.isScrubbing),this.isScrubbing){this.wasPaused=i.paused,await i.pause(),this.handleTimelineUpdate(s);return}if(this.realtime=n*this.videoDuration,i.currentTime=n*this.videoDuration,this.wasPaused)return;const a=i.play();a!==void 0&&a.then(()=>this.handleTimelineUpdate(s)).catch(console.error)},handleKeyDown(s){var t;const e=(t=document.activeElement)==null?void 0:t.tagName.toLowerCase();if(e!=="input")switch(s.key.toLowerCase()){case" ":if(e==="button")return;this.togglePlay();break;case"k":this.togglePlay();break;case"escape":s.preventDefault(),this.closeFullscreenMode(),this.isFullscreen=!1;break;case"f":this.openFullscreenMode(),this.isFullscreen=!0;break}}}}),zh="";var _h=function(){var e=this,t=e._self._c;return t("div",{ref:"videoContainer",staticClass:"video-container paused",attrs:{"data-volume-level":"high"}},[t("video",e._g(e._b({ref:"player",attrs:{controls:!1,preload:"auto"},on:{ended:e.handleEnded,click:e.togglePlay,loadedmetadata:e.getDuration,timeupdate:e.handleTimeUpdate,loadeddata:e.handleLoading}},"video",e.videoOptions,!1),e.videoListeners),e._l(e.sourceItems,function(i){return t("source",e._g({key:i.src,attrs:{src:i.src,type:i.type},on:{error:e.handle404Error}},e.videoListeners))}),0),e.isLoading?t("div",{staticClass:"spinner-container"},[t("ESpinner",{attrs:{size:"9xl",opacity:"0.6",dark:!0}})],1):e._e(),e.isError?t("div",{staticClass:"spinner-container e-gap-3"},[t("i",{staticClass:"fa-solid fa-video-slash fa-2xl e-align-middle"}),t("span",[e._v("This video file cannot be played.")])]):e._e(),t("div",{class:["video-controls-container",e.withControls]},[t("div",{staticClass:"controls"},[t("button",{ref:"playPauseBtn",staticClass:"play-pause-btn fa-lg fa-solid",class:{"fa-play":!e.playing,"fa-pause":e.playing},attrs:{title:e.playing?"pause":"play"},on:{click:e.togglePlay}}),t("div",{staticClass:"duration-container"},[t("div",{ref:"currentTimeElem",staticClass:"current-time"},[e._v(" "+e._s(e.currentTime)+" ")]),e._v(" / "),t("div",{ref:"totalTimeElem",staticClass:"total-time"},[e._v(e._s(e.videoLength))])]),t("div",{ref:"timelineContainer",staticClass:"timeline-container",on:{mousemove:e.handleTimelineUpdate,mousedown:e.toggleScrubbing}},[e._m(0)]),t("button",{ref:"fullScreenBtn",staticClass:"full-screen-btn fa-solid",class:{"fa-expand":!e.isFullscreen,"fa-compress":e.isFullscreen},on:{click:e.toggleFullscreenMode}})])])])},Ih=[function(){var s=this,e=s._self._c;return e("div",{staticClass:"timeline"},[e("div",{staticClass:"thumb-indicator"})])}],wh=Be(Dh,_h,Ih,!1,null,"cffc31d4",null,null);const fa=wh.exports,ii=s=>{const e=N.utcFormat("%_d")(s),i={1:"st",2:"nd",3:"rd"}[e.charAt(1)]||"th";return`${e}${i}`},ga=s=>new Date(Date.UTC(s.getUTCFullYear(),s.getUTCMonth(),s.getUTCDate()+1)).getUTCDate()===1?"":N.utcFormat("%-d")(s),Et=s=>["0"," 0","00"].includes(N.utcFormat("%H")(s))?"":`${N.utcFormat("%H")(s)}h`,ze=s=>{const e=N.utcFormat("%H:%M")(s);return e==="00:00"?"":e},ys=s=>N.utcFormat("%M:%S")(s),ma=s=>`${N.utcFormat("%Hh%Mm")(s)}`,vs=s=>{const e=ze(s),t=ii(s),i=N.utcFormat("%B")(s);return e||`${i} ${t}`},xs=s=>{const e=ze(s),t=Number.parseInt(N.utcFormat("%H")(s)),i=ii(s),r=N.utcFormat("%B")(s);return e&&t%6===0?`${r} ${i} ${e}`:vs(s)},St=s=>e=>{const t=N.utcFormat("%H")(e);return!(N.utcFormat("%M")(e)==="00"&&Number.parseInt(t)%s===0)},Ts=s=>e=>{const t=N.utcFormat("%M")(e);return Number.parseInt(t)%s!==0},pa=s=>e=>{const t=N.utcFormat("%M")(e),i=N.utcFormat("%S")(e);return Number.parseInt(t)%s!==0&&Number.parseInt(i)===0},Y={_10_seconds:25e-6,_20_seconds:1e-4,_30_seconds:15e-5,_1_minute:3e-4,_2_minutes:75e-5,_5_minutes:.002,_15_minutes:.005,_30_minutes:.01,_1_hour:.025,_2_hours:.05,_3_hours:.1,_4_hours:.15,_6_hours:.25,_1_day:1,_2_days:2,_1_month:8,_1_month_abbr:13,_1_month_letter:22,_3_months:33,infinity:1/0},kh={[ft.overview]:[{precision:Y._30_seconds,interval:N.utcMinute.every(2),format:ma},{precision:Y._1_minute,interval:N.utcMinute.every(5),format:ma},{precision:Y._2_minutes,interval:N.utcMinute.every(10),format:vs},{precision:Y._5_minutes,interval:N.utcMinute.every(20),format:xs},{precision:Y._15_minutes,interval:N.utcHour,format:xs},{precision:Y._30_minutes,interval:N.utcHour.every(2),format:xs},{precision:Y._2_hours,interval:N.utcHour.every(6),format:s=>{const e=ze(s),t=ii(s),i=N.utcFormat("%B")(s);return e||`${i} ${t}`}},{precision:Y._3_hours,interval:N.utcHour.every(12),format:vs},{precision:Y._6_hours,interval:N.utcHour.every(24),format:s=>{const e=ii(s);return`${N.utcFormat("%b")(s)} ${e}`}},{precision:Y._2_days,interval:N.utcMonth,format:s=>{const t=s.getUTCMonth()===0&&s.getUTCDate()===1?"%Y – %B":"%B";return N.utcFormat(t)(s)}},{precision:Y.infinity,interval:N.utcYear,format:"%Y"}],[ft.detailed]:[{precision:Y._10_seconds,interval:N.utcSecond.every(10),format:ys},{precision:Y._20_seconds,interval:(Ta=N.utcSecond.every(20))==null?void 0:Ta.filter(pa(2)),format:ys},{precision:Y._30_seconds,interval:(Ea=N.utcSecond.every(30))==null?void 0:Ea.filter(pa(2)),format:ys},{precision:Y._1_minute,interval:N.utcMinute.filter(Ts(5)),format:ze},{precision:Y._2_minutes,interval:(Sa=N.utcMinute.every(2))==null?void 0:Sa.filter(Ts(10)),format:ze},{precision:Y._5_minutes,interval:(ba=N.utcMinute.every(5))==null?void 0:ba.filter(Ts(20)),format:ze},{precision:Y._15_minutes,interval:(Aa=N.utcMinute.every(15))==null?void 0:Aa.filter(St(1)),format:ze},{precision:Y._30_minutes,interval:(La=N.utcMinute.every(30))==null?void 0:La.filter(St(2)),format:ze},{precision:Y._1_hour,interval:N.utcHour.filter(St(6)),format:Et},{precision:Y._2_hours,interval:(Ra=N.utcHour.every(2))==null?void 0:Ra.filter(St(6)),format:Et},{precision:Y._3_hours,interval:(Ca=N.utcHour.every(3))==null?void 0:Ca.filter(St(12)),format:Et},{precision:Y._4_hours,interval:N.utcHour.every(4),format:Et},{precision:Y._6_hours,interval:N.utcHour.every(6),format:Et},{precision:Y._1_day,interval:N.utcDay,format:ga},{precision:Y._2_days,interval:N.utcDay.every(2),format:ga},{precision:Y._1_month,interval:N.utcMonth,format:"%B"},{precision:Y._1_month_abbr,interval:N.utcMonth,format:"%b"},{precision:Y._1_month_letter,interval:N.utcMonth,format:s=>N.utcFormat("%B")(s).charAt(0)},{precision:Y._3_months,interval:N.utcMonth.every(3),format:"Q%q"},{precision:Y.infinity,interval:N.utcMonth.every(3),format:""}],[ft.detailedBackground]:[{precision:Y._10_seconds,interval:N.utcSecond,format:""},{precision:Y._20_seconds,interval:N.utcSecond.every(5),format:""},{precision:Y._30_seconds,interval:N.utcSecond.every(10),format:""},{precision:Y._1_minute,interval:N.utcSecond.every(20),format:""},{precision:Y._2_minutes,interval:N.utcSecond.every(30),format:""},{precision:Y._5_minutes,interval:N.utcMinute,format:""},{precision:Y._15_minutes,interval:N.utcMinute.every(3),format:""},{precision:Y._30_minutes,interval:N.utcMinute.every(6),format:""},{precision:Y._1_hour,interval:N.utcMinute.every(15),format:""},{precision:Y._2_hours,interval:N.utcMinute.every(30),format:""},{precision:Y._3_hours,interval:N.utcHour,format:""},{precision:Y._4_hours,interval:N.utcHour,format:""},{precision:Y._6_hours,interval:N.utcMinute.every(120),format:""},{precision:Y._1_day,interval:N.utcHour.every(8),format:""},{precision:Y._2_days,interval:N.utcHour.every(12),format:""},{precision:Y._1_month,interval:N.utcDay.filter(s=>{const e=s.getUTCDate(),t=new Date(s.getUTCFullYear(),s.getUTCMonth()+1,0).getUTCDate(),i=Math.ceil(t/5);return e===i||e===2*i||e===3*i||e===4*i}),format:""},{precision:Y._1_month_abbr,interval:N.utcDay.filter(s=>{const e=s.getUTCDate(),t=new Date(s.getUTCFullYear(),s.getUTCMonth()+1,0).getUTCDate(),i=Math.ceil(t/4);return e===i||e===2*i||e===3*i}),format:""},{precision:Y._1_month_letter,interval:N.utcDay.filter(s=>{const e=s.getUTCDate(),t=new Date(s.getUTCFullYear(),s.getUTCMonth()+1,0).getUTCDate(),i=Math.ceil(t/2);return e===i}),format:""},{precision:Y._3_months,interval:N.utcMonth,format:""},{precision:Y.infinity,interval:N.utcMonth,format:""}]},Es={bind(s,e){const{value:t}=e;if(typeof t!="function"){console.error("Invalid callback function provided to v-resize-observer");return}const i=new ResizeObserver(r=>{r[0]&&t(r[0])});i.observe(s),s.__resizeObserver__=i},unbind(s){s.__resizeObserver__&&(s.__resizeObserver__.disconnect(),delete s.__resizeObserver__)}},ya=[{name:"resize-observer",definition:Es}],V={eventGroup:"event-group",eventGroupBg:"event-group-bg",eventRect:"event-rect",eventBarContainer:"event-bar-container",eventBarContainerHovered:"event-bar-container--hovered",eventBarContainerSelected:"event-bar-container--selected",eventBar:"event-bar",eventBarHoverZone:"event-bar-hover-zone",eventBarCap:"event-bar-cap",eventRectText:"event-rect-text",eventRectHovered:"event-rect--hovered",eventRectSelected:"event-rect--selected",labelGroup:"label-g",labelBg:"label-bg",labelBgFill:"label-bg-fill",labelText:"label-text",loadingIndicator:"loading-indicator",xAxis:"x-axis",selectedTimestampCursor:"selected-timestamp-cursor",marker:"marker",markerLabel:"marker-label",markerLine:"marker-line",barChartGroup:"bar-chart-group",lineGraphGroup:"line-graph-group",lineGraphPath:"line-graph-path",lineGraphHoverZone:"line-graph-hover-zone",lineGraphDot:"line-graph-dot",curtain:"curtain"},Qe={transparencyGradient:"transparency-gradient",transparencyGradientLight:"transparency-gradient-light",loadingGradient:"loading-gradient"},Ph=Ee.extend({name:"ETimeline",directives:{resizeObserver:Es},props:{eventsGroups:{type:Object,default:()=>({})},xAxesConfig:{type:Object,default:()=>kh},dark:{type:Boolean,default:!1},startDate:{type:String,default:void 0},endDate:{type:String,default:void 0},selectedTimestamp:{type:String,default:void 0},showEventTooltip:{type:Boolean,default:!0},disableZoom:{type:Boolean,default:!1},insertZerosAtInterval:{type:String,default:void 0},flattenLineGraphEnds:{type:Boolean,default:!0},curtains:{type:Boolean,default:!1},showLabels:{type:Boolean,default:!0},rectMinWidth:{type:Number,default:1},barHeight:{type:Number,default:18},barYPadding:{type:Number,default:0},barXPadding:{type:Number,default:0},chartMinHeight:{type:Number,default:60},minZoom:{type:Number,default:1e-4},maxZoom:{type:Number,default:85e4},cursorTimestamp:{type:[String,void 0],default:void 0},selectedClass:{type:[String,void 0],default:void 0},panOnDateClick:{type:Boolean,default:!1},panTransitionDuration:{type:Number,default:500},selectedDate:{type:String,default:""},autoResize:{type:Boolean,default:!0},markers:{type:Array,default:()=>[]},stickyMarkers:{type:Boolean,default:!0}},data(){return{tooltip:null,cursor:null,timeline:null,selectedTimestampCursor:null,svg:null,axesContainer:null,xAxes:{},timeScale:null,initialTimeScale:null,currentTimeScaleDensity:null,zoomBehavior:null,isMouseDown:!1,axisHeight:22,isHoveringEvent:!1,hoveredEvent:null,isHoveringTimeline:!1,hoveredTimestamp:null,eventTooltipStyle:{},hoveredEventType:null,utcOffset:0,lastTransform:{x:0,k:1},transformDiff:{translation:0,scale:1},yScale:null,hoveredCounts:[],countsByTimestamp:{},dotsByTimestamp:{},visibleFrom:null,visibleTo:null,curtainHandleWidth:5,leftCurtainWidth:50,rightCurtainWidth:50,isHoveringCurtain:!1,isDraggingCurtain:!1,characterWidth:7.5,textPadding:5,debouncedOnResize:()=>{},isFirstPaint:!0,timeouts:[],groupsVisibility:{},markersPositions:{}}},computed:{barChartHeight(){return this.barHeight+this.barYPadding},classes(){return{wrapper:{"e-border-gray-700 e-timeline--dark":this.dark,"e-border-gray-300":!this.dark,"e-timeline--dragging":this.isInteractingWithCurtain},background:this.dark?"e-bg-gray-900":"e-bg-gray-50",tooltipSlot:this.dark?"e-bg-gray-900 e-text-white e-border-gray-700":"e-bg-gray-100 e-text-gray-700 e-border-gray-300",eventTooltipSlot:this.dark?"e-bg-gray-900 e-text-white e-border-gray-700":"e-bg-gray-100 e-text-gray-700 e-border-gray-300"}},lineGraphGroups(){return Object.entries(this.filteredEventsGroups).reduce((s,[e,t])=>t.chartType===je.lineGraph?{...s,[e]:t}:s,{})},chartHeight(){if(!this.showLabels)return this.chartMinHeight;const e=(Object.keys(this.lineGraphGroups).length+Object.keys(this.barChartGroups).length)*this.barChartHeight;return Math.max(this.chartMinHeight,e)},barGroups(){return Object.entries(this.filteredEventsGroups).reduce((s,[e,t])=>!t.chartType||t.chartType===je.bars?{...s,[e]:t}:s,{})},barChartGroups(){return Object.entries(this.filteredEventsGroups).reduce((s,[e,t])=>t.chartType===je.barChart?{...s,[e]:t}:s,{})},hasChart(){return Object.keys(this.lineGraphGroups).length+Object.keys(this.barChartGroups).length>0},labelRectWidth(){return Object.values(this.eventsGroups).reduce((t,i)=>{var r;return Math.max(t,(r=i.label)==null?void 0:r.length)},0)*this.characterWidth+2*this.textPadding},combinedXAxesHeight(){const s=Object.keys(this.xAxesConfig).length-1;return this.axisHeight*s},timelineHeight(){const s=Object.keys(this.barGroups).length,e=this.barChartHeight*s,t=this.hasChart?this.chartHeight:0;return this.combinedXAxesHeight+t+e},filteredEventsGroups(){const s=Object.entries(this.eventsGroups).filter(([e,t])=>this.getCurrentGroupVisibility(e));return Object.fromEntries(s)},allEventsSorted(){return Object.values(this.filteredEventsGroups).map(e=>e.events).flat().sort((e,t)=>new Date(e.timestamp||e.startDate)>new Date(t.timestamp||t.startDate)?1:-1)},oldestEvent(){let s;return this.allEventsSorted.length>1?s=this.allEventsSorted[0]:s={timestamp:new Date(new Date().getTime()-864e5)},s},latestEvent(){let s;return this.allEventsSorted.length>1?s=this.allEventsSorted[this.allEventsSorted.length-1]:s={timestamp:new Date},s},allLineChartTimestamps(){const s=new Set;return Object.values(this.lineGraphGroups).forEach(e=>{e.events.forEach(t=>{s.add(t.timestamp)})}),Array.from(s).sort()},placeholderLineChartGroup(){return this.fillTimeGaps(this.allLineChartTimestamps.map(s=>({timestamp:s,count:0})))},filledGapsLineGraphGroups(){return Object.entries(this.lineGraphGroups).reduce((s,[e,t])=>({...s,[e]:{...t,events:this.fillEvents(t.events)}}),{})},isInteractingWithCurtain(){return this.isHoveringCurtain||this.isDraggingCurtain},flattenedCounts(){return[...Object.values(this.lineGraphGroups),...Object.values(this.barChartGroups)].map(s=>s.events).flat()},hiddenGroupsLabels(){return Object.entries(this.groupsVisibility).reduce((s,[e,t])=>t?s:[...s,e],[])},minHoverZone(){return this.showLabels?this.labelRectWidth:0},sortedMarkers(){return[...this.markers].sort((s,e)=>new Date(s.timestamp).getTime()>new Date(e.timestamp).getTime()?1:-1)}},watch:{dark(){this.handleDarkModeChange()},selectedTimestamp(){this.repositionSelectedTimestampCursor()},markers(){this.updateMarkersPositions()},startDate(){this.zoomToStartAndEndDates()},endDate(){this.zoomToStartAndEndDates()},eventsGroups(){this.updateAndRedrawTimeline()},cursorTimestamp(){if(this.cursorTimestamp){this.hoveredTimestamp=this.cursorTimestamp;const s=this.tzStringToDate(this.hoveredTimestamp),e=this.timeScale(s);this.cursor.style.left=e+"px",this.isHoveringTimeline=!0}else this.isHoveringTimeline=!1},selectedDate(s){s&&this.panToTimestamp(s)},groupsVisibility(){this.updateAndRedrawTimeline()}},created(){this.debouncedOnResize=ha(this.handleResize,100)},mounted(){this.initTimeline()},beforeDestroy(){this.clearTimeline(),document.removeEventListener("mouseup",this.handleDocumentMouseUp)},methods:{initTimeline(s,e){if(this.initRefs(),!this.timeline||this.timeline.offsetWidth===0){this.timeouts.push(setTimeout(this.initTimeline,500));return}this.initSvg(),this.initDefs(),this.initUtcOffset(),this.initTimeScale(s,e),this.initXAxes(),this.initYScale(),this.initZoomBehavior(),this.drawEventsGroups(),this.curtains&&(this.initCurtains(),this.emitCurtainChange()),this.initSelectedTimestampCursor(),this.updateMarkersPositions(),this.registerEventsListeners(),this.emitVisibleInterval(gt.initial),this.selectedDate&&this.panOnDateClick&&this.panToTimestamp(this.selectedDate)},initRefs(){this.tooltip=this.$refs.tooltip,this.cursor=this.$refs.cursor,this.timeline=this.$refs.timelineContainer,this.selectedTimestampCursor=this.$refs.selectedTimestamp},initSvg(){this.svg=N.select(this.timeline).append("svg").attr("width",this.timeline.offsetWidth).attr("height",this.timelineHeight)},initDefs(){const s=this.svg.append("defs");Object.entries(this.filteredEventsGroups).forEach(([e,t])=>{const{color:i,chartType:r}=t,n=s.append("linearGradient").attr("id",`${Qe.loadingGradient}-${e}`).attr("x1","0%").attr("y1","0%").attr("x2","100%").attr("y2","0%");n.append("stop").attr("offset","0%").attr("stop-color",i).attr("stop-opacity","0"),n.append("stop").attr("offset","50%").attr("stop-color",i).attr("stop-opacity","0.6"),n.append("stop").attr("offset","100%").attr("stop-color",i).attr("stop-opacity","0"),[je.lineGraph,je.barChart].includes(r)&&[{id:Qe.transparencyGradientLight,stop:38,opacity:.3},{id:Qe.transparencyGradient,stop:130,opacity:.4}].forEach(({id:o,stop:l,opacity:c})=>{const u=s.append("linearGradient").attr("id",`${o}-${e}`).attr("x1","0%").attr("x2","0%").attr("y1","0%").attr("y2","100%");u.append("stop").attr("offset","0%").style("stop-color",i).style("stop-opacity",c),u.append("stop").attr("offset",`${l}%`).style("stop-color",i).style("stop-opacity",0)})})},initUtcOffset(){const s=this.startDate||this.oldestEvent.timestamp||this.oldestEvent.startDate;this.utcOffset=Ve.parseZone(s).utcOffset()},initTimeScale(s,e){const t=s||this.startDate||this.oldestEvent.timestamp||this.oldestEvent.startDate,i=e||this.endDate||this.latestEvent.timestamp||this.latestEvent.endDate;this.timeScale=N.scaleTime().domain([this.tzStringToDate(t),this.tzStringToDate(i)]).range([0,this.timeline.offsetWidth]),this.initialTimeScale=this.timeScale.copy(),this.updateCurrentTimeScaleDensity()},initXAxes(){let s=0;const e=5;for(const t in this.xAxesConfig){const i=this.createAxis(t);this.xAxes[t]=i,this.svg.append("g").classed(V.xAxis,!0).classed(`${V.xAxis}-${t}`,!0).attr("transform",`translate(0, ${s||e})`).call(i),this.translateTicksText(t),s+=this.axisHeight}},initYScale(){this.yScale=N.scaleLinear().range([this.chartHeight,0]),this.updateYScaleDomain()},updateYScaleDomain(){const[s,e]=this.timeScale.domain(),t=this.flattenedCounts.filter(r=>{const n=new Date(r.startDate||r.timestamp),a=new Date(r.endDate||r.timestamp);return a>=s&&a<=e||n>=s&&n<=e}),i=N.max(t,r=>r.count);this.yScale.domain([0,i])},initZoomBehavior(){this.disableZoom||(this.zoomBehavior=N.zoom().on("zoom",this.handleZoom).scaleExtent([this.minZoom,this.maxZoom]),this.svg.call(this.zoomBehavior))},initSelectedTimestampCursor(){this.svg.append("line").attr("class",V.selectedTimestampCursor).style("stroke","red").style("stroke-width","1px").style("opacity",0).attr("x1",0).attr("x2",0).attr("y1",0).attr("y2",this.timelineHeight),this.repositionSelectedTimestampCursor()},updateMarkersPositions(){this.sortedMarkers.forEach((t,i,r)=>{const n=typeof t.timestamp=="string"?this.tzStringToDate(t.timestamp):t.timestamp,a=this.timeScale(n);let o=!1;const l=this.stickyMarkers?Math.max(a,i*12):a;if(i<r.length-1){const c=r[i+1],u=typeof c.timestamp=="string"?this.tzStringToDate(c.timestamp):c.timestamp,h=this.timeScale(u);o=(this.stickyMarkers?Math.max(h,(i+1)*12):a)-l<200+12}this.markersPositions={...this.markersPositions,[t.id]:{isHidden:o,position:l}}})},updateAndRedrawTimeline(){const{startDate:s,endDate:e}=this.getCurrentTimeBounds();this.clearTimeline(),this.initTimeline(s,e)},clearTimeline(){this.svg&&this.svg.remove(),this.countsByTimestamp={}},repositionSelectedTimestampCursor(){const s=this.svg.select(`.${V.selectedTimestampCursor}`);if(!this.selectedTimestamp){s.style("opacity",0);return}const e=this.tzStringToDate(this.selectedTimestamp),t=this.timeScale(e);isNaN(t)?s.style("opacity",0):s.attr("x1",t).attr("x2",t).style("opacity",.5)},updateCurrentTimeScaleDensity(){const s=this.timeScale.invert(0).getTime(),e=this.timeScale.invert(1).getTime(),t=36e5;this.currentTimeScaleDensity=(e-s)/t},registerEventsListeners(){document.addEventListener("mouseup",this.handleDocumentMouseUp),this.svg.on("mousedown",this.handleMouseDown),this.svg.on("mousemove",this.handleMouseMove),this.svg.on("click",this.handleClick),this.svg.on("mouseleave",this.handleMouseLeave)},emitVisibleInterval(s){const e=this.timeScale.invert(0),t=this.timeScale.invert(this.timeline.offsetWidth);if(this.visibleFrom&&this.visibleFrom.getTime()===e.getTime()&&this.visibleTo&&this.visibleTo.getTime()===t.getTime())return;this.visibleFrom=e,this.visibleTo=t;const i=this.dateToTzString(this.visibleFrom),r=this.dateToTzString(this.visibleTo);this.$emit("visible-interval-change",{fromDate:i,toDate:r,trigger:s,transform:this.transformDiff})},createAxis(s){const e=this.xAxesConfig[s],t=this.getAxisTicksConfig(e);return N.axisBottom(this.timeScale).ticks(t.interval).tickFormat(t.formatFn).tickSizeOuter(0).tickSizeInner(this.timelineHeight)},getAxisTicksConfig(s){const{interval:e,format:t}=s.find(r=>r.precision>=this.currentTimeScaleDensity&&r.interval);return{formatFn:r=>typeof t=="function"?t(r):N.timeFormat(t)(r),interval:e}},onResize(s){this.isFirstPaint?(this.handleResize(s),this.isFirstPaint=!1):this.debouncedOnResize(s)},handleResize({contentRect:s}){this.svg&&(this.svg.attr("width",s.width),this.updateAndRedrawTimeline())},handleDarkModeChange(){if(!this.showLabels)return;const s=this;this.svg.selectAll(`.${V.labelBg}`).each(function(){N.select(this).style("fill",s.dark?"black":"white")}),this.svg.selectAll(`.${V.labelBgFill}`).each(function(){const e=N.select(this),t=e.node().dataset.color;e.style("fill",s.getLabelBackgroundColor(t)).style("stroke",s.getTextFillColor(t)).style("stroke-width",.25)}),this.svg.selectAll(`.${V.labelText}`).each(function(){const e=N.select(this),t=e.node().dataset.color;e.style("fill",s.getTextFillColor(t))})},handleMouseDown(){this.isMouseDown=!0},handleDocumentMouseUp(){this.isMouseDown=!1},handleMouseLeave(){this.isHoveringTimeline=!1,this.$emit("hovered-timestamp",void 0)},handleMouseMove(s){if(this.isMouseDown)return;const e=s.offsetX;if(e<=this.minHoverZone){this.isHoveringTimeline=!1;return}const t=this.timeScale.invert(e);this.hoveredTimestamp=this.dateToTzString(t),this.isHoveringTimeline=!0,this.$emit("hovered-timestamp",this.hoveredTimestamp),this.cursor.style.left=e+"px",this.tooltip&&(this.eventTooltipStyle={left:`${e}px`,bottom:`${this.timeline.getBoundingClientRect().height}px`,zIndex:100})},handleClick(s){const e=s.offsetX;if(e<=this.minHoverZone)return;const t=this.timeScale.invert(e),i=this.dateToTzString(t);this.$emit("date-clicked",i),this.isHoveringEvent&&this.$emit("event-clicked",{event:this.hoveredEvent,type:this.hoveredEventType}),this.panOnDateClick&&this.panToTimestamp(i)},handleMarkerClick(s){this.$emit("marker-clicked",s),this.panToTimestamp(s.timestamp)},handleLineMouseOver(s,e,t){this.hoveredCounts=Object.entries(this.countsByTimestamp[`${e.timestamp}`]).reduce((i,r)=>{const[n,a]=r;return[...i,{type:n,count:a}]},[]),this.hoveredEvent=e,this.isHoveringEvent=!0,this.$emit("event-mouseover",{eventData:e,eventType:t,hoveredCounts:this.hoveredCounts})},handleLineMouseOut(){this.isHoveringEvent=!1,this.hoveredCounts=[],this.$emit("event-mouseout")},handleBarMouseOver(s,e,t){s.offsetX<=this.minHoverZone||(this.hoveredEvent=e,this.hoveredEventType=t,this.isHoveringEvent=!0,this.$emit("event-mouseover",{eventData:e,eventType:t}))},handleBarMouseOut(){this.isHoveringEvent=!1,this.hoveredEvent=null,this.$emit("event-mouseout")},handleLabelMouseOver(s){N.selectAll(`.${V.lineGraphGroup}-${s}`).classed(`${V.lineGraphGroup}--highlighted`,!0),N.selectAll(`.${V.lineGraphGroup}-label`).classed(`${V.lineGraphGroup}-label--highlighted`,!0)},handleLabelMouseLeave(s){N.selectAll(`.${V.lineGraphGroup}-${s}`).classed(`${V.lineGraphGroup}--highlighted`,!1),N.selectAll(`.${V.lineGraphGroup}-label`).classed(`${V.lineGraphGroup}-label--highlighted`,!1)},handleZoom(s){const e=s.transform.rescaleX(this.initialTimeScale);this.timeScale.domain(e.domain()),this.updateCurrentTimeScaleDensity(),this.updateYScaleDomain();const t=s.transform.k/this.lastTransform.k;this.transformDiff={scale:t,translation:s.transform.x-this.lastTransform.x},this.lastTransform={...s.transform};for(const i in this.xAxes)this.rescaleAxis(i,e),this.translateTicksText(i);this.updateEventsBars(),this.updateLineGraphs(),this.updateBarChart(),this.updateLineGraphHoverZones(),this.repositionSelectedTimestampCursor(),this.updateMarkersPositions(),this.emitVisibleInterval(gt.zoom),this.curtains&&this.emitCurtainChange()},panToTimestamp(s){const e=this.tzStringToDate(s),t=this.timeScale(e),i=N.zoomTransform(this.svg.node()),r=i.x-t+this.timeline.offsetWidth/2;this.svg.transition().duration(this.panTransitionDuration).call(this.zoomBehavior.transform,N.zoomIdentity.translate(r,0).scale(i.k)),this.emitVisibleInterval(gt.autoPan)},emitCurtainChange(){const{startDate:s,endDate:e}=this.calculateDateRangeFromCurtains();this.$emit("curtain-range-change",{startDate:new Date(s).toISOString(),endDate:new Date(e).toISOString()})},calculateDateRangeFromCurtains(){const s=this.timeline.offsetWidth,e=this.timeScale.domain(),t=e[1].getTime()-e[0].getTime(),i=(this.leftCurtainWidth-this.curtainHandleWidth*2)/s*t,r=(this.rightCurtainWidth+this.curtainHandleWidth*2)/s*t,n=new Date(e[0].getTime()+i),a=new Date(e[1].getTime()-r);return{startDate:n,endDate:a}},handleDragStart(){this.isDraggingCurtain=!0},handleDragEnd(){this.isDraggingCurtain=!1},handleLeftDrag(s){s.sourceEvent.stopPropagation();const e=Math.min(s.x,this.timeline.offsetWidth-this.rightCurtainWidth);this.leftCurtainWidth=Math.max(0,e),this.svg.select(`.${V.curtain}--left`).attr("width",this.leftCurtainWidth),this.emitCurtainChange()},handleRightDrag(s){s.sourceEvent.stopPropagation();const e=this.timeline.offsetWidth,t=Math.min(this.timeline.offsetWidth-s.x,this.timeline.offsetWidth-this.leftCurtainWidth),i=e-t;this.rightCurtainWidth=Math.max(0,t),this.svg.select(`.${V.curtain}--right`).attr("width",this.rightCurtainWidth).attr("x",i),this.emitCurtainChange()},zoomToStartAndEndDates(){const s=this.startDate||this.oldestEvent.timestamp||this.oldestEvent.startDate,e=this.endDate||this.latestEvent.timestamp||this.latestEvent.endDate,t=this.tzStringToDate(s),i=this.tzStringToDate(e),r=this.timeline.offsetWidth,n=[t,i],a=[0,r];this.timeScale=N.scaleTime().domain(n).range(a),this.initialTimeScale=this.timeScale.copy(),this.updateCurrentTimeScaleDensity();for(const o in this.xAxes)this.rescaleAxis(o,this.timeScale),this.translateTicksText(o);this.updateEventsBars(),this.updateLineGraphs(),this.updateLineGraphHoverZones(),this.repositionSelectedTimestampCursor(),this.updateMarkersPositions()},rescaleAxis(s,e){const t=this.xAxes[s],i=this.getAxisTicksConfig(this.xAxesConfig[s]);t.scale(e).ticks(i.interval).tickFormat(i.formatFn).tickSizeOuter(0),this.svg.select(`.${V.xAxis}-${s}`).call(t)},translateTicksText(s){this.svg.select(`.${V.xAxis}-${s}`).selectAll(".tick text").each(function(){let e=N.select(this),t=e.node().getBBox();e.attr("x",t.height/2).attr("y",0).style("text-anchor","start")})},updateEventsBars(){const s=`.${V.eventGroup} > rect.${V.eventRect}`;this.svg.selectAll(s).attr("x",this.getEventRectX).attr("width",this.getEventRectWidth);const e=`.${V.eventGroup} > text.${V.eventRectText}`;this.svg.selectAll(e).attr("x",t=>this.getEventRectX(t)+this.textPadding).text(this.getEventText)},updateBarChart(){const s=Object.keys(this.barChartGroups).length;Object.keys(this.barChartGroups).forEach((e,t)=>{const i=d=>(this.getEventRectWidth(d)-this.barXPadding*2)/s,r=d=>this.yScale.range()[0]-this.yScale(d.count),n=d=>this.getEventRectX(d)+this.barXPadding+t*i(d),a=d=>this.yScale(d.count),o=`.${V.eventBarContainer}-${e}`,l=this.svg.selectAll(o),c=`.${V.barChartGroup} rect.${V.eventBarHoverZone}`;l.selectAll(c).attr("x",n).attr("width",i);const u=`.${V.barChartGroup} rect.${V.eventBar}`;l.selectAll(u).attr("x",n).attr("width",i).attr("y",a).attr("height",r);const h=`.${V.barChartGroup} rect.${V.eventBarCap}`;l.selectAll(h).attr("x",n).attr("width",i).attr("y",a)})},updateLineGraphs(){Object.entries(this.lineGraphGroups).forEach(([s])=>{const e=N.area().x(t=>this.timeScale(this.tzStringToDate(t.timestamp))).y0(this.timelineHeight).y1(t=>this.yScale(t.count)).curve(N.curveMonotoneX);this.svg.selectAll(`.${V.lineGraphPath}-${s}`).attr("d",t=>e(t))})},updateLineGraphHoverZones(){Object.keys(this.lineGraphGroups).forEach(s=>{const e=this;this.svg.selectAll(`.${V.lineGraphDot}-${s}`).each(function(t){N.select(this).attr("cx",e.timeScale(e.tzStringToDate(t.timestamp))).attr("cy",e.yScale(t.count))}),this.svg.selectAll(`.${V.lineGraphHoverZone}-${s}`).each(function(t){const i=e.timeScale(e.tzStringToDate(t.timestamp).getTime())-15;N.select(this).attr("x",i).attr("y",0).attr("width",30).attr("height",e.chartHeight)})})},getEventRectX(s){return this.timeScale(this.tzStringToDate(s.startDate||s.timestamp))},getEventRectWidth(s){if(!s)return 0;if(s.startDate&&s.endDate){const e=new Date(s.startDate),t=new Date(s.endDate),i=this.timeScale(t)-this.timeScale(e);return Math.max(i,this.rectMinWidth)}else{const e=1/(this.currentTimeScaleDensity*3600);return Math.max(e,this.rectMinWidth)}},getEventText(s){var i;const t=(this.getEventRectWidth(s)-this.textPadding)/this.characterWidth;return t<4?"":((i=s.text)==null?void 0:i.length)<=t?s.text:`${s.text.slice(0,t-3)}...`},initCurtains(){if(!this.curtains)return;const s=this.timeline.offsetWidth,e=this.timelineHeight;this.svg.append("rect").classed(`${V.curtain} ${V.curtain}--left`,!0).attr("width",this.leftCurtainWidth).attr("height",e+this.curtainHandleWidth*2).attr("y",-this.curtainHandleWidth).attr("x",-this.curtainHandleWidth).attr("fill","rgba(0, 0, 0, 0.5)").on("mouseenter",()=>this.isHoveringCurtain=!0).on("mouseleave",()=>this.isHoveringCurtain=!1).call(N.drag().on("start",this.handleDragStart).on("drag",this.handleLeftDrag).on("end",this.handleDragEnd)),this.svg.append("rect").classed(`${V.curtain} ${V.curtain}--right`,!0).attr("x",s-this.rightCurtainWidth+this.curtainHandleWidth*2).attr("y",-this.curtainHandleWidth).attr("width",this.rightCurtainWidth+this.curtainHandleWidth*2).attr("height",e+this.curtainHandleWidth*2).attr("fill","rgba(0, 0, 0, 0.5)").on("mouseenter",()=>this.isHoveringCurtain=!0).on("mouseleave",()=>this.isHoveringCurtain=!1).call(N.drag().on("start",this.handleDragStart).on("drag",this.handleRightDrag).on("end",this.handleDragEnd))},drawEventsGroups(){this.svg.selectAll(`g.${V.eventGroup}`).remove(),this.drawLineGraphEventsGroups(),this.drawBarEventsGroups(),this.drawBarChartEventsGroups()},drawLineGraphEventsGroups(){const s=this.combinedXAxesHeight,e=this.insertZerosAtInterval?this.filledGapsLineGraphGroups:this.lineGraphGroups;Object.entries(e).forEach(([t,i])=>{const r=this.svg.append("g").classed(`${V.lineGraphGroup} ${V.lineGraphGroup}-${t}`,!0).attr("transform",`translate(0,${s})`),{color:n,events:a}=i;this.drawLineGraph({events:a,gElement:r,color:n,type:t}),this.drawLineGraphHoverZones({events:a,gElement:r,color:n,type:t})}),Object.entries(this.lineGraphGroups).forEach(([t,i],r)=>{const{color:n,isLoading:a,label:o}=i,l=this.chartHeight-this.barChartHeight*(r+1),c=s+this.chartHeight-this.barChartHeight,u=this.svg.append("g").classed(`${V.lineGraphGroup}-label`,!0).attr("transform",`translate(0,${s})`).on("mouseover",()=>this.handleLabelMouseOver(t)).on("mouseleave",()=>this.handleLabelMouseLeave(t));this.drawProgressIndicator({type:t,color:n,isLoading:a,yPosition:c}),this.drawTextLabel({color:n,label:o,type:t,yPosition:l,gElement:u})})},drawLineGraph({events:s,gElement:e,color:t,type:i}){const r=N.area().x(a=>this.timeScale(this.tzStringToDate(a.timestamp))).y0(this.timelineHeight).y1(a=>this.yScale(a.count)).curve(N.curveMonotoneX),n=`clip-${i}`;e.append("defs").append("clipPath").attr("id",n).append("rect").attr("width",this.timeline.offsetWidth).attr("height",this.chartHeight),e.append("path").datum(s).classed(`${V.lineGraphPath}-${i}`,!0).attr("fill",`url(#${Qe.transparencyGradientLight}-${i})`).attr("stroke",t).attr("stroke-linejoin","round").attr("stroke-linecap","round").attr("stroke-width",1).attr("d",a=>r(a)).attr("clip-path",`url(#${n})`)},drawLineGraphHoverZones({events:s,gElement:e,color:t,type:i}){s.forEach(r=>{const n=`${r.timestamp}`;this.countsByTimestamp[n]={...this.countsByTimestamp[n]||{},[i]:r.count};const a=e.append("circle").classed(`${V.lineGraphDot} ${V.lineGraphDot}-${i}`,!0).attr("cx",this.timeScale(this.tzStringToDate(r.timestamp))).attr("cy",this.yScale(r.count)).attr("r",1.5).attr("fill",t).attr("stroke-width",0).datum(r);this.dotsByTimestamp[n]=[...this.dotsByTimestamp[n]||[],a],e.append("rect").classed(`${V.lineGraphHoverZone}-${i}`,!0).attr("x",this.timeScale(this.tzStringToDate(r.timestamp))-15).attr("y",0).attr("width",30).attr("height",this.chartHeight).attr("fill","transparent").datum(r).on("mouseover",o=>{this.handleLineMouseOver(o,r,i),this.dotsByTimestamp[n].forEach(l=>l.classed(`${V.lineGraphDot}--active`,!0))}).on("mouseout",()=>{this.handleLineMouseOut(),this.dotsByTimestamp[n].forEach(o=>o.classed(`${V.lineGraphDot}--active`,!1))})})},drawBarEventsGroups(){Object.entries(this.barGroups).forEach(([s,e],t)=>{const{color:i,bgColor:r,label:n,events:a,isLoading:o}=e,l=this.hasChart?this.chartHeight:0,c=t*this.barChartHeight+this.combinedXAxesHeight+l;this.drawProgressIndicator({yPosition:c,type:s,color:i,isLoading:o});const u=this.svg.append("g").attr("data-color",i).classed(V.eventGroup,!0).classed(`${V.eventGroup}-${s}`,!0);this.drawBackground({color:r||i,gElement:u,yPosition:c}),this.drawBars({events:a,color:i,gElement:u,yPosition:c,type:s}),this.drawTextLabel({color:i,label:n,type:s,gElement:u,yPosition:c})})},drawBarChartEventsGroups(){const s=this.combinedXAxesHeight,e=this.barChartGroups;Object.entries(e).forEach(([t,i],r)=>{const n=this.svg.append("g").classed(`${V.barChartGroup} ${V.barChartGroup}-${t}`,!0).attr("transform",`translate(0,${s})`),{color:a,events:o}=i;this.drawBarsChart({events:o,color:a,gElement:n,yOffset:s,type:t,index:r})})},drawProgressIndicator({yPosition:s,type:e,isLoading:t}){this.svg.append("rect").classed(`${V.loadingIndicator} ${V.loadingIndicator}-${e}`,!0).attr("x",0).attr("y",s).attr("width",this.timeline.offsetWidth/3).attr("height",this.barChartHeight).attr("fill",`url(#${Qe.loadingGradient}-${e})`).style("visibility",t?"visible":"hidden")},drawBackground({color:s,yPosition:e,gElement:t}){t.append("rect").attr("class",V.eventGroupBg).attr("x",0).attr("y",e).attr("width",this.timeline.offsetWidth).attr("height",this.barChartHeight).attr("fill",N.color(s).toString()).style("opacity",.1)},drawBars({events:s,gElement:e,yPosition:t,color:i,type:r}){const n=this;e.selectAll(V.eventRect).data(s).enter().append("rect").attr("class",a=>V.eventRect+(a.className?` ${a.className}`:"")).attr("x",this.getEventRectX).attr("y",t+this.barYPadding/2).attr("ry",1.5).attr("rx",1.5).attr("width",this.getEventRectWidth).attr("height",this.barChartHeight-this.barYPadding).attr("stroke-width",5).attr("cursor","pointer").attr("stroke","#0000").style("fill",a=>a.color||i).on("mouseover",function(a,o){N.select(this).classed(V.eventRectHovered,!0),n.handleBarMouseOver(a,o,r)}).on("mouseout",function(){N.select(this).classed(V.eventRectHovered,!1),n.handleBarMouseOut()}),e.selectAll(V.eventRectText).data(s.filter(a=>!!a.text)).enter().append("text").attr("class",V.eventRectText).attr("x",a=>this.getEventRectX(a)+this.textPadding).attr("y",t+this.barChartHeight/2).attr("dy","0.35em").style("text-anchor","start").style("font-size","12px").style("font-weight",600).style("stroke-linejoin","round").style("paint-order","stroke").style("pointer-events","none").style("fill",a=>this.getTextFillColor(a.color||i,.75)).text(this.getEventText)},drawBarsChart({events:s,gElement:e,color:t,yOffset:i,type:r,index:n}){const a=this,o=Object.keys(this.barChartGroups).length,l=f=>(this.getEventRectWidth(f)-this.barXPadding*2)/o,c=f=>this.yScale.range()[0]-this.yScale(f.count),u=f=>this.getEventRectX(f)+this.barXPadding+n*l(f),h=f=>this.yScale(f.count),d=e.selectAll(V.eventBarContainer).data(s).enter().append("g").attr("class",`${V.eventBarContainer} ${V.eventBarContainer}-${r}`);d.append("rect").attr("class",f=>V.eventBarHoverZone+(f.className?` ${f.className}`:"")).attr("x",u).attr("y",-i).attr("width",l).attr("height",this.yScale.range()[0]+i).attr("fill",f=>f.color||t).attr("fill-opacity",0),d.append("rect").attr("class",f=>V.eventBar+(f.className?` ${f.className}`:"")).attr("x",u).attr("y",h).attr("width",l).attr("height",c).attr("stroke-width",5).attr("cursor","pointer").attr("stroke","#0000").attr("fill",`url(#${Qe.transparencyGradient}-${r})`),d.append("rect").attr("class",f=>V.eventBarCap+(f.className?` ${f.className}`:"")).attr("x",u).attr("y",h).attr("width",l).attr("height",2).attr("stroke-width",0).style("fill",f=>f.color||t),d.on("mouseover",function(f,g){const m=N.select(this);a.onBarChartBarMouseOver(m,t),a.handleBarMouseOver(f,g,r)}).on("mouseout",function(){const f=N.select(this);a.onBarChartBarMouseOut(f,r),a.handleBarMouseOut()}).on("click",function(){e.selectAll(`.${V.eventBarContainerSelected}`).classed(V.eventBarContainerSelected,!1),N.select(this).classed(V.eventBarContainerSelected,!0)})},onBarChartBarMouseOver(s,e){s.classed(V.eventBarContainerHovered,!0),s.selectAll(`.${V.eventBarHoverZone}`).attr("fill-opacity",.2);const i=s.selectAll(`.${V.eventBar}`);i.attr("fill",e),i.attr("fill-opacity",.5)},onBarChartBarMouseOut(s,e){s.classed(V.eventBarContainerHovered,!1),s.selectAll(`.${V.eventBarHoverZone}`).attr("fill-opacity",0);const i=s.selectAll(`.${V.eventBar}`);i.attr("fill",`url(#${Qe.transparencyGradient}-${e})`),i.attr("fill-opacity",1)},drawTextLabel({gElement:s,yPosition:e,color:t,label:i,type:r}){if(!this.showLabels)return;const n={x:-5,y:e,w:this.labelRectWidth,h:this.barChartHeight,radius:3},a=s.append("g").attr("class",`${V.labelGroup} ${V.labelGroup}-${r}`).style("cursor","pointer").on("click",()=>this.toggleGroupVisibility(r));a.append("rect").attr("class",V.labelBg).attr("data-color",t).attr("x",n.x).attr("y",n.y).attr("width",n.w).attr("height",n.h).attr("rx",n.radius).attr("ry",n.radius).style("fill",this.dark?"#131a29":"white"),a.append("rect").attr("class",V.labelBgFill).attr("data-color",t).attr("x",n.x).attr("y",n.y).attr("width",n.w).attr("height",n.h).attr("rx",n.radius).attr("ry",n.radius).style("fill",this.getLabelBackgroundColor(t)).style("stroke",this.getTextFillColor(t)).style("stroke-width",.25),a.append("text").attr("class",V.labelText).attr("data-color",t).attr("x",5).attr("y",e+this.barChartHeight/2).attr("dy","0.35em").style("text-anchor","start").style("font-size","12px").style("font-weight",500).style("stroke-linejoin","round").style("paint-order","stroke").style("fill",this.getTextFillColor(t)).text(i)},getTextFillColor(s,e=0){var t,i;return(this.dark?(t=N.color(s))==null?void 0:t.brighter(1.5+e):(i=N.color(s))==null?void 0:i.darker(2+e)).toString()},getLabelBackgroundColor(s){let e=N.color(s);return e.opacity=this.dark?.2:.5,e.toString()},getCurrentGroupVisibility(s){var i;const e=this.groupsVisibility[s];if(e!==void 0)return e;const t=(i=this.eventsGroups[s])==null?void 0:i.isHidden;return t!==void 0?!t:!0},toggleGroupVisibility(s){this.groupsVisibility={...this.groupsVisibility,[s]:!this.getCurrentGroupVisibility(s)}},getExternalLabelStyles(s){const e=this.eventsGroups[s].color;return{background:this.getLabelBackgroundColor(e),color:this.getTextFillColor(e)}},getExternalLabelWrapperStyles(s){const e=this.eventsGroups[s].color;return{borderColor:this.getTextFillColor(e)}},getMarkerClass(s){var e;return{"marker--hidden":(e=this.markersPositions[s==null?void 0:s.id])==null?void 0:e.isHidden}},getMarkerContainerStyle(s){var e;return{top:"0",left:`${(e=this.markersPositions[s.id])==null?void 0:e.position}px`}},getMarkerLabelStyle(s){return{background:s.color,color:s.textColor||""}},getMarkerLineStyle(s){return{background:s.color,height:`${this.timelineHeight+24}px`}},tzStringToDate(s){return Ve(s).add(this.utcOffset,"minutes").toDate()},dateToTzString(s){const e=new Date(s).getTimezoneOffset();return Ve(s).add(e,"minutes").utcOffset(this.utcOffset,!0).format()},getCurrentTimeBounds(){const s=this.timeScale.domain();return{startDate:s[0],endDate:s[1]}},getFormattedTimestamp(s){return Ve.parseZone(s).format("YYYY-MM-DDTHH:mm:ss")},fillTimeGaps(s){if(s.length<=1)return s;const e=this.insertZerosAtInterval,t=n=>n.clone().add(1,e),i=n=>n.clone().subtract(1,e);let r=[];for(let n=0;n<s.length;n++){const a=s[n];if(r.push(a),n===s.length-1)break;const o=s[n+1],l=Ve(a.timestamp),c=Ve(o.timestamp);if(c.diff(l,e)>1){const u=t(l).toISOString(),h=i(c).toISOString();r.push({timestamp:u,count:0}),u!==h&&r.push({timestamp:h,count:0})}}if(this.flattenLineGraphEnds){const n=Ve(s[0].timestamp),a=Ve(s[s.length-1].timestamp),o=i(n).toISOString(),l=t(a).toISOString();r=[{timestamp:o,count:0},...r,{timestamp:l,count:0}]}return r},fillEvents(s){return this.placeholderLineChartGroup.map(e=>s.find(i=>i.timestamp===e.timestamp)||e)}}}),jh="";var Oh=function(){var e=this,t=e._self._c;return t("div",{staticClass:"e-relative e-timeline e-border e-rounded",class:e.classes.wrapper},[t("div",{staticClass:"e-timeline__background e-w-full e-h-full e-absolute e-top-0 e-rounded",class:e.classes.background}),e._l(e.sortedMarkers,function(i){return t("div",{key:i.id,staticClass:"e-absolute marker",class:e.getMarkerClass(i),style:e.getMarkerContainerStyle(i),attrs:{"data-id":i.id},on:{click:function(r){return e.handleMarkerClick(i)}}},[e._t(`marker.${i.id}`,function(){return[t("div",{staticClass:"marker-label e-absolute"},[t("div",{staticClass:"marker-label-text",style:e.getMarkerLabelStyle(i)},[e._v(" "+e._s(i.label)+" ")])]),t("div",{staticClass:"marker-line e-absolute e-pointer-events-none",style:e.getMarkerLineStyle(i)})]},{marker:i})],2)}),e.autoResize?t("div",{directives:[{name:"resize-observer",rawName:"v-resize-observer",value:e.onResize,expression:"onResize"}],ref:"timelineContainer",staticClass:"e-timeline__svg-container e-relative e-h-13 e-rounded e-select-none e-overflow-x-hidden"}):t("div",{ref:"timelineContainer",staticClass:"e-timeline__svg-container e-relative e-h-13 e-rounded e-select-none e-overflow-x-hidden"}),t("div",{directives:[{name:"show",rawName:"v-show",value:e.isHoveringTimeline&&!e.isInteractingWithCurtain,expression:"isHoveringTimeline && !isInteractingWithCurtain"}],ref:"cursor",staticClass:"e-timeline__cursor e-absolute e-bg-green-600 e-w-px e-h-full e-top-0 e-pointer-events-none"}),t("div",{staticClass:"external-labels-container e-flex"},e._l(e.hiddenGroupsLabels,function(i){return t("div",{key:i,staticClass:"external-label",class:e.classes.background,style:e.getExternalLabelWrapperStyles(i),on:{click:function(r){return e.toggleGroupVisibility(i)}}},[t("div",{staticClass:"external-label__content",style:e.getExternalLabelStyles(i)},[e._v(" "+e._s(i)+" ")])])}),0),t("div",{ref:"tooltip",staticClass:"e-absolute",style:e.eventTooltipStyle},[e._t("tooltip",function(){return[t("div",{directives:[{name:"show",rawName:"v-show",value:e.isHoveringTimeline&&!e.isHoveringEvent&&!e.isInteractingWithCurtain&&!e.cursorTimestamp,expression:`
|
|
26
|
+
} (data length: ${t&&t.byteLength})`),r.update(t)}selectKeySystemFormat(e){const t=Object.keys(e.levelkeys||{});return this.keyFormatPromise||(this.log(`Selecting key-system from fragment (sn: ${e.sn} ${e.type}: ${e.level}) key formats ${t.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(t)),this.keyFormatPromise}getKeyFormatPromise(e){return new Promise((t,i)=>{const r=xi(this.config),n=e.map(er).filter(a=>!!a&&r.indexOf(a)!==-1);return this.getKeySystemSelectionPromise(n).then(({keySystem:a})=>{const o=ir(a);o?t(o):i(new Error(`Unable to find format for key-system "${a}"`))}).catch(i)})}loadKey(e){const t=e.keyInfo.decryptdata,i=this.getKeyIdString(t),r=`(keyId: ${i} format: "${t.keyFormat}" method: ${t.method} uri: ${t.uri})`;this.log(`Starting session for key ${r}`);let n=this.keyIdToKeySessionPromise[i];return n||(n=this.keyIdToKeySessionPromise[i]=this.getKeySystemForKeyPromise(t).then(({keySystem:a,mediaKeys:o})=>(this.throwIfDestroyed(),this.log(`Handle encrypted media sn: ${e.frag.sn} ${e.frag.type}: ${e.frag.level} using key ${r}`),this.attemptSetMediaKeys(a,o).then(()=>{this.throwIfDestroyed();const l=this.createMediaKeySessionContext({keySystem:a,mediaKeys:o,decryptdata:t}),c="cenc";return this.generateRequestWithPreferredKeySession(l,c,t.pssh,"playlist-key")}))),n.catch(a=>this.handleError(a))),n}throwIfDestroyed(e="Invalid state"){if(!this.hls)throw new Error("invalid state")}handleError(e){this.hls&&(this.error(e.message),e instanceof Ae?this.hls.trigger(p.ERROR,e.data):this.hls.trigger(p.ERROR,{type:q.KEY_SYSTEM_ERROR,details:_.KEY_SYSTEM_NO_KEYS,error:e,fatal:!0}))}getKeySystemForKeyPromise(e){const t=this.getKeyIdString(e),i=this.keyIdToKeySessionPromise[t];if(!i){const r=er(e.keyFormat),n=r?[r]:xi(this.config);return this.attemptKeySystemAccess(n)}return i}getKeySystemSelectionPromise(e){if(e.length||(e=xi(this.config)),e.length===0)throw new Ae({type:q.KEY_SYSTEM_ERROR,details:_.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${JSON.stringify({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(e)}_onMediaEncrypted(e){const{initDataType:t,initData:i}=e;if(this.debug(`"${e.type}" event: init data type: "${t}"`),i===null)return;let r,n;if(t==="sinf"&&this.config.drmSystems[ne.FAIRPLAY]){const u=ce(new Uint8Array(i));try{const h=yi(JSON.parse(u).sinf),d=dr(new Uint8Array(h));if(!d)return;r=d.subarray(8,24),n=ne.FAIRPLAY}catch{this.warn('Failed to parse sinf "encrypted" event message initData');return}}else{const u=tl(i);if(u===null)return;u.version===0&&u.systemId===tr.WIDEVINE&&u.data&&(r=u.data.subarray(8,24)),n=_o(u.systemId)}if(!n||!r)return;const a=we.hexDump(r),{keyIdToKeySessionPromise:o,mediaKeySessions:l}=this;let c=o[a];for(let u=0;u<l.length;u++){const h=l[u],d=h.decryptdata;if(d.pssh||!d.keyId)continue;const f=we.hexDump(d.keyId);if(a===f||d.uri.replace(/-/g,"").indexOf(a)!==-1){c=o[f],delete o[f],d.pssh=new Uint8Array(i),d.keyId=r,c=o[a]=c.then(()=>this.generateRequestWithPreferredKeySession(h,t,i,"encrypted-event-key-match"));break}}c||(c=o[a]=this.getKeySystemSelectionPromise([n]).then(({keySystem:u,mediaKeys:h})=>{var d;this.throwIfDestroyed();const f=new yt("ISO-23001-7",a,(d=ir(u))!=null?d:"");return f.pssh=new Uint8Array(i),f.keyId=r,this.attemptSetMediaKeys(u,h).then(()=>{this.throwIfDestroyed();const g=this.createMediaKeySessionContext({decryptdata:f,keySystem:u,mediaKeys:h});return this.generateRequestWithPreferredKeySession(g,t,i,"encrypted-event-no-match")})})),c.catch(u=>this.handleError(u))}_onWaitingForKey(e){this.log(`"${e.type}" event`)}attemptSetMediaKeys(e,t){const i=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${e}"`);const r=Promise.all(i).then(()=>{if(!this.media)throw new Error("Attempted to set mediaKeys without media element attached");return this.media.setMediaKeys(t)});return this.setMediaKeysQueue.push(r),r.then(()=>{this.log(`Media-keys set for "${e}"`),i.push(r),this.setMediaKeysQueue=this.setMediaKeysQueue.filter(n=>i.indexOf(n)===-1)})}generateRequestWithPreferredKeySession(e,t,i,r){var n,a;const o=(n=this.config.drmSystems)==null||(a=n[e.keySystem])==null?void 0:a.generateRequest;if(o)try{const g=o.call(this.hls,t,i,e);if(!g)throw new Error("Invalid response from configured generateRequest filter");t=g.initDataType,i=e.decryptdata.pssh=g.initData?new Uint8Array(g.initData):null}catch(g){var l;if(this.warn(g.message),(l=this.hls)!=null&&l.config.debug)throw g}if(i===null)return this.log(`Skipping key-session request for "${r}" (no initData)`),Promise.resolve(e);const c=this.getKeyIdString(e.decryptdata);this.log(`Generating key-session request for "${r}": ${c} (init data type: ${t} length: ${i?i.byteLength:null})`);const u=new qi,h=e._onmessage=g=>{const m=e.mediaKeysSession;if(!m){u.emit("error",new Error("invalid state"));return}const{messageType:y,message:v}=g;this.log(`"${y}" message event for session "${m.sessionId}" message size: ${v.byteLength}`),y==="license-request"||y==="license-renewal"?this.renewLicense(e,v).catch(T=>{this.handleError(T),u.emit("error",T)}):y==="license-release"?e.keySystem===ne.FAIRPLAY&&(this.updateKeySession(e,vi("acknowledged")),this.removeSession(e)):this.warn(`unhandled media key message type "${y}"`)},d=e._onkeystatuseschange=g=>{if(!e.mediaKeysSession){u.emit("error",new Error("invalid state"));return}this.onKeyStatusChange(e);const y=e.keyStatus;u.emit("keyStatus",y),y==="expired"&&(this.warn(`${e.keySystem} expired for key ${c}`),this.renewKeySession(e))};e.mediaKeysSession.addEventListener("message",h),e.mediaKeysSession.addEventListener("keystatuseschange",d);const f=new Promise((g,m)=>{u.on("error",m),u.on("keyStatus",y=>{y.startsWith("usable")?g():y==="output-restricted"?m(new Ae({type:q.KEY_SYSTEM_ERROR,details:_.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED,fatal:!1},"HDCP level output restricted")):y==="internal-error"?m(new Ae({type:q.KEY_SYSTEM_ERROR,details:_.KEY_SYSTEM_STATUS_INTERNAL_ERROR,fatal:!0},`key status changed to "${y}"`)):y==="expired"?m(new Error("key expired while generating request")):this.warn(`unhandled key status change "${y}"`)})});return e.mediaKeysSession.generateRequest(t,i).then(()=>{var g;this.log(`Request generated for key-session "${(g=e.mediaKeysSession)==null?void 0:g.sessionId}" keyId: ${c}`)}).catch(g=>{throw new Ae({type:q.KEY_SYSTEM_ERROR,details:_.KEY_SYSTEM_NO_SESSION,error:g,fatal:!1},`Error generating key-session request: ${g}`)}).then(()=>f).catch(g=>{throw u.removeAllListeners(),this.removeSession(e),g}).then(()=>(u.removeAllListeners(),e))}onKeyStatusChange(e){e.mediaKeysSession.keyStatuses.forEach((t,i)=>{this.log(`key status change "${t}" for keyStatuses keyId: ${we.hexDump("buffer"in i?new Uint8Array(i.buffer,i.byteOffset,i.byteLength):new Uint8Array(i))} session keyId: ${we.hexDump(new Uint8Array(e.decryptdata.keyId||[]))} uri: ${e.decryptdata.uri}`),e.keyStatus=t})}fetchServerCertificate(e){const t=this.config,i=t.loader,r=new i(t),n=this.getServerCertificateUrl(e);return n?(this.log(`Fetching server certificate for "${e}"`),new Promise((a,o)=>{const l={responseType:"arraybuffer",url:n},c=t.certLoadPolicy.default,u={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},h={onSuccess:(d,f,g,m)=>{a(d.data)},onError:(d,f,g,m)=>{o(new Ae({type:q.KEY_SYSTEM_ERROR,details:_.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:g,response:he({url:l.url,data:void 0},d)},`"${e}" certificate request failed (${n}). Status: ${d.code} (${d.text})`))},onTimeout:(d,f,g)=>{o(new Ae({type:q.KEY_SYSTEM_ERROR,details:_.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:g,response:{url:l.url,data:void 0}},`"${e}" certificate request timed out (${n})`))},onAbort:(d,f,g)=>{o(new Error("aborted"))}};r.load(l,u,h)})):Promise.resolve()}setMediaKeysServerCertificate(e,t,i){return new Promise((r,n)=>{e.setServerCertificate(i).then(a=>{this.log(`setServerCertificate ${a?"success":"not supported by CDM"} (${i==null?void 0:i.byteLength}) on "${t}"`),r(e)}).catch(a=>{n(new Ae({type:q.KEY_SYSTEM_ERROR,details:_.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:a,fatal:!0},a.message))})})}renewLicense(e,t){return this.requestLicense(e,new Uint8Array(t)).then(i=>this.updateKeySession(e,new Uint8Array(i)).catch(r=>{throw new Ae({type:q.KEY_SYSTEM_ERROR,details:_.KEY_SYSTEM_SESSION_UPDATE_FAILED,error:r,fatal:!0},r.message)}))}unpackPlayReadyKeyMessage(e,t){const i=String.fromCharCode.apply(null,new Uint16Array(t.buffer));if(!i.includes("PlayReadyKeyMessage"))return e.setRequestHeader("Content-Type","text/xml; charset=utf-8"),t;const r=new DOMParser().parseFromString(i,"application/xml"),n=r.querySelectorAll("HttpHeader");if(n.length>0){let u;for(let h=0,d=n.length;h<d;h++){var a,o;u=n[h];const f=(a=u.querySelector("name"))==null?void 0:a.textContent,g=(o=u.querySelector("value"))==null?void 0:o.textContent;f&&g&&e.setRequestHeader(f,g)}}const l=r.querySelector("Challenge"),c=l==null?void 0:l.textContent;if(!c)throw new Error("Cannot find <Challenge> in key message");return vi(atob(c))}setupLicenseXHR(e,t,i,r){const n=this.config.licenseXhrSetup;return n?Promise.resolve().then(()=>{if(!i.decryptdata)throw new Error("Key removed");return n.call(this.hls,e,t,i,r)}).catch(a=>{if(!i.decryptdata)throw a;return e.open("POST",t,!0),n.call(this.hls,e,t,i,r)}).then(a=>(e.readyState||e.open("POST",t,!0),{xhr:e,licenseChallenge:a||r})):(e.open("POST",t,!0),Promise.resolve({xhr:e,licenseChallenge:r}))}requestLicense(e,t){const i=this.config.keyLoadPolicy.default;return new Promise((r,n)=>{const a=this.getLicenseServerUrl(e.keySystem);this.log(`Sending license request to URL: ${a}`);const o=new XMLHttpRequest;o.responseType="arraybuffer",o.onreadystatechange=()=>{if(!this.hls||!e.mediaKeysSession)return n(new Error("invalid state"));if(o.readyState===4)if(o.status===200){this._requestLicenseFailureCount=0;let l=o.response;this.log(`License received ${l instanceof ArrayBuffer?l.byteLength:l}`);const c=this.config.licenseResponseCallback;if(c)try{l=c.call(this.hls,o,a,e)}catch(u){this.error(u)}r(l)}else{const l=i.errorRetry,c=l?l.maxNumRetry:0;if(this._requestLicenseFailureCount++,this._requestLicenseFailureCount>c||o.status>=400&&o.status<500)n(new Ae({type:q.KEY_SYSTEM_ERROR,details:_.KEY_SYSTEM_LICENSE_REQUEST_FAILED,fatal:!0,networkDetails:o,response:{url:a,data:void 0,code:o.status,text:o.statusText}},`License Request XHR failed (${a}). Status: ${o.status} (${o.statusText})`));else{const u=c-this._requestLicenseFailureCount+1;this.warn(`Retrying license request, ${u} attempts left`),this.requestLicense(e,t).then(r,n)}}},e.licenseXhr&&e.licenseXhr.readyState!==XMLHttpRequest.DONE&&e.licenseXhr.abort(),e.licenseXhr=o,this.setupLicenseXHR(o,a,e,t).then(({xhr:l,licenseChallenge:c})=>{e.keySystem==ne.PLAYREADY&&(c=this.unpackPlayReadyKeyMessage(l,c)),l.send(c)})})}onMediaAttached(e,t){if(!this.config.emeEnabled)return;const i=t.media;this.media=i,i.addEventListener("encrypted",this.onMediaEncrypted),i.addEventListener("waitingforkey",this.onWaitingForKey)}onMediaDetached(){const e=this.media,t=this.mediaKeySessions;e&&(e.removeEventListener("encrypted",this.onMediaEncrypted),e.removeEventListener("waitingforkey",this.onWaitingForKey),this.media=null),this._requestLicenseFailureCount=0,this.setMediaKeysQueue=[],this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},yt.clearKeyUriToKeyIdMap();const i=t.length;ht.CDMCleanupPromise=Promise.all(t.map(r=>this.removeSession(r)).concat(e==null?void 0:e.setMediaKeys(null).catch(r=>{this.log(`Could not clear media keys: ${r}`)}))).then(()=>{i&&(this.log("finished closing key sessions and clearing media keys"),t.length=0)}).catch(r=>{this.log(`Could not close sessions and clear media keys: ${r}`)})}onManifestLoading(){this.keyFormatPromise=null}onManifestLoaded(e,{sessionKeys:t}){if(!(!t||!this.config.emeEnabled)&&!this.keyFormatPromise){const i=t.reduce((r,n)=>(r.indexOf(n.keyFormat)===-1&&r.push(n.keyFormat),r),[]);this.log(`Selecting key-system from session-keys ${i.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(i)}}removeSession(e){const{mediaKeysSession:t,licenseXhr:i}=e;if(t){this.log(`Remove licenses and keys and close session ${t.sessionId}`),e._onmessage&&(t.removeEventListener("message",e._onmessage),e._onmessage=void 0),e._onkeystatuseschange&&(t.removeEventListener("keystatuseschange",e._onkeystatuseschange),e._onkeystatuseschange=void 0),i&&i.readyState!==XMLHttpRequest.DONE&&i.abort(),e.mediaKeysSession=e.decryptdata=e.licenseXhr=void 0;const r=this.mediaKeySessions.indexOf(e);return r>-1&&this.mediaKeySessions.splice(r,1),t.remove().catch(n=>{this.log(`Could not remove session: ${n}`)}).then(()=>t.close()).catch(n=>{this.log(`Could not close session: ${n}`)})}}}ht.CDMCleanupPromise=void 0;class Ae extends Error{constructor(e,t){super(t),this.data=void 0,e.error||(e.error=new Error(t)),this.data=e,e.err=e.error}}var ve;(function(s){s.MANIFEST="m",s.AUDIO="a",s.VIDEO="v",s.MUXED="av",s.INIT="i",s.CAPTION="c",s.TIMED_TEXT="tt",s.KEY="k",s.OTHER="o"})(ve||(ve={}));var ls;(function(s){s.DASH="d",s.HLS="h",s.SMOOTH="s",s.OTHER="o"})(ls||(ls={}));var Ze;(function(s){s.OBJECT="CMCD-Object",s.REQUEST="CMCD-Request",s.SESSION="CMCD-Session",s.STATUS="CMCD-Status"})(Ze||(Ze={}));const Tu={[Ze.OBJECT]:["br","d","ot","tb"],[Ze.REQUEST]:["bl","dl","mtp","nor","nrr","su"],[Ze.SESSION]:["cid","pr","sf","sid","st","v"],[Ze.STATUS]:["bs","rtp"]};class dt{constructor(e,t){this.value=void 0,this.params=void 0,Array.isArray(e)&&(e=e.map(i=>i instanceof dt?i:new dt(i))),this.value=e,this.params=t}}class jn{constructor(e){this.description=void 0,this.description=e}}const Eu="Dict";function Su(s){return Array.isArray(s)?JSON.stringify(s):s instanceof Map?"Map{}":s instanceof Set?"Set{}":typeof s=="object"?JSON.stringify(s):String(s)}function bu(s,e,t,i){return new Error(`failed to ${s} "${Su(e)}" as ${t}`,{cause:i})}const Yn="Bare Item",Au="Boolean",Lu="Byte Sequence",Ru="Decimal",Cu="Integer";function Du(s){return s<-999999999999999||999999999999999<s}const _u=/[\x00-\x1f\x7f]+/,Iu="Token",wu="Key";function Me(s,e,t){return bu("serialize",s,e,t)}function ku(s){if(typeof s!="boolean")throw Me(s,Au);return s?"?1":"?0"}function Pu(s){return btoa(String.fromCharCode(...s))}function Ou(s){if(ArrayBuffer.isView(s)===!1)throw Me(s,Lu);return`:${Pu(s)}:`}function qn(s){if(Du(s))throw Me(s,Cu);return s.toString()}function Fu(s){return`@${qn(s.getTime()/1e3)}`}function Xn(s,e){if(s<0)return-Xn(-s,e);const t=Math.pow(10,e);if(Math.abs(s*t%1-.5)<Number.EPSILON){const r=Math.floor(s*t);return(r%2===0?r:r+1)/t}else return Math.round(s*t)/t}function Mu(s){const e=Xn(s,3);if(Math.floor(Math.abs(e)).toString().length>12)throw Me(s,Ru);const t=e.toString();return t.includes(".")?t:`${t}.0`}const Nu="String";function Bu(s){if(_u.test(s))throw Me(s,Nu);return`"${s.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function Uu(s){return s.description||s.toString().slice(7,-1)}function Zn(s){const e=Uu(s);if(/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(e)===!1)throw Me(e,Iu);return e}function cs(s){switch(typeof s){case"number":if(!K(s))throw Me(s,Yn);return Number.isInteger(s)?qn(s):Mu(s);case"string":return Bu(s);case"symbol":return Zn(s);case"boolean":return ku(s);case"object":if(s instanceof Date)return Fu(s);if(s instanceof Uint8Array)return Ou(s);if(s instanceof jn)return Zn(s);default:throw Me(s,Yn)}}function us(s){if(/^[a-z*][a-z0-9\-_.*]*$/.test(s)===!1)throw Me(s,wu);return s}function hs(s){return s==null?"":Object.entries(s).map(([e,t])=>t===!0?`;${us(e)}`:`;${us(e)}=${cs(t)}`).join("")}function Qn(s){return s instanceof dt?`${cs(s.value)}${hs(s.params)}`:cs(s)}function $u(s){return`(${s.value.map(Qn).join(" ")})${hs(s.params)}`}function Gu(s,e={whitespace:!0}){if(typeof s!="object")throw Me(s,Eu);const t=s instanceof Map?s.entries():Object.entries(s),i=e!=null&&e.whitespace?" ":"";return Array.from(t).map(([r,n])=>{n instanceof dt||(n=new dt(n));let a=us(r);return n.value===!0?a+=hs(n.params):(a+="=",Array.isArray(n.value)?a+=$u(n):a+=Qn(n)),a}).join(`,${i}`)}function Hu(s,e){return Gu(s,e)}const Vu=s=>s==="ot"||s==="sf"||s==="st",Ku=s=>typeof s=="number"?K(s):s!=null&&s!==""&&s!==!1;function Wu(s,e){const t=new URL(s),i=new URL(e);if(t.origin!==i.origin)return s;const r=t.pathname.split("/").slice(1),n=i.pathname.split("/").slice(1,-1);for(;r[0]===n[0];)r.shift(),n.shift();for(;n.length;)n.shift(),r.unshift("..");return r.join("/")}function zu(){try{return crypto.randomUUID()}catch{try{const e=URL.createObjectURL(new Blob),t=e.toString();return URL.revokeObjectURL(e),t.slice(t.lastIndexOf("/")+1)}catch{let t=new Date().getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,r=>{const n=(t+Math.random()*16)%16|0;return t=Math.floor(t/16),(r=="x"?n:n&3|8).toString(16)})}}}const Jt=s=>Math.round(s),ju=(s,e)=>(e!=null&&e.baseUrl&&(s=Wu(s,e.baseUrl)),encodeURIComponent(s)),ei=s=>Jt(s/100)*100,Yu={br:Jt,d:Jt,bl:ei,dl:ei,mtp:ei,nor:ju,rtp:ei,tb:Jt};function qu(s,e){const t={};if(s==null||typeof s!="object")return t;const i=Object.keys(s).sort(),r=oe({},Yu,e==null?void 0:e.formatters),n=e==null?void 0:e.filter;return i.forEach(a=>{if(n!=null&&n(a))return;let o=s[a];const l=r[a];l&&(o=l(o,e)),!(a==="v"&&o===1)&&(a=="pr"&&o===1||Ku(o)&&(Vu(a)&&typeof o=="string"&&(o=new jn(o)),t[a]=o))}),t}function Jn(s,e={}){return s?Hu(qu(s,e),oe({whitespace:!1},e)):""}function Xu(s,e={}){if(!s)return{};const t=Object.entries(s),i=Object.entries(Tu).concat(Object.entries((e==null?void 0:e.customHeaderMap)||{})),r=t.reduce((n,a)=>{var o,l;const[c,u]=a,h=((o=i.find(d=>d[1].includes(c)))==null?void 0:o[0])||Ze.REQUEST;return(l=n[h])!=null||(n[h]={}),n[h][c]=u,n},{});return Object.entries(r).reduce((n,[a,o])=>(n[a]=Jn(o,e),n),{})}function Zu(s,e,t){return oe(s,Xu(e,t))}const Qu="CMCD";function Ju(s,e={}){if(!s)return"";const t=Jn(s,e);return`${Qu}=${encodeURIComponent(t)}`}const ea=/CMCD=[^&#]+/;function eh(s,e,t){const i=Ju(e,t);if(!i)return s;if(ea.test(s))return s.replace(ea,i);const r=s.includes("?")?"&":"?";return`${s}${r}${i}`}class th{constructor(e){this.hls=void 0,this.config=void 0,this.media=void 0,this.sid=void 0,this.cid=void 0,this.useHeaders=!1,this.includeKeys=void 0,this.initialized=!1,this.starved=!1,this.buffering=!0,this.audioBuffer=void 0,this.videoBuffer=void 0,this.onWaiting=()=>{this.initialized&&(this.starved=!0),this.buffering=!0},this.onPlaying=()=>{this.initialized||(this.initialized=!0),this.buffering=!1},this.applyPlaylistData=r=>{try{this.apply(r,{ot:ve.MANIFEST,su:!this.initialized})}catch(n){S.warn("Could not generate manifest CMCD data.",n)}},this.applyFragmentData=r=>{try{const n=r.frag,a=this.hls.levels[n.level],o=this.getObjectType(n),l={d:n.duration*1e3,ot:o};(o===ve.VIDEO||o===ve.AUDIO||o==ve.MUXED)&&(l.br=a.bitrate/1e3,l.tb=this.getTopBandwidth(o)/1e3,l.bl=this.getBufferLength(o)),this.apply(r,l)}catch(n){S.warn("Could not generate segment CMCD data.",n)}},this.hls=e;const t=this.config=e.config,{cmcd:i}=t;i!=null&&(t.pLoader=this.createPlaylistLoader(),t.fLoader=this.createFragmentLoader(),this.sid=i.sessionId||zu(),this.cid=i.contentId,this.useHeaders=i.useHeaders===!0,this.includeKeys=i.includeKeys,this.registerListeners())}registerListeners(){const e=this.hls;e.on(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(p.MEDIA_DETACHED,this.onMediaDetached,this),e.on(p.BUFFER_CREATED,this.onBufferCreated,this)}unregisterListeners(){const e=this.hls;e.off(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(p.MEDIA_DETACHED,this.onMediaDetached,this),e.off(p.BUFFER_CREATED,this.onBufferCreated,this)}destroy(){this.unregisterListeners(),this.onMediaDetached(),this.hls=this.config=this.audioBuffer=this.videoBuffer=null,this.onWaiting=this.onPlaying=null}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener("waiting",this.onWaiting),this.media.addEventListener("playing",this.onPlaying)}onMediaDetached(){this.media&&(this.media.removeEventListener("waiting",this.onWaiting),this.media.removeEventListener("playing",this.onPlaying),this.media=null)}onBufferCreated(e,t){var i,r;this.audioBuffer=(i=t.tracks.audio)==null?void 0:i.buffer,this.videoBuffer=(r=t.tracks.video)==null?void 0:r.buffer}createData(){var e;return{v:1,sf:ls.HLS,sid:this.sid,cid:this.cid,pr:(e=this.media)==null?void 0:e.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(e,t={}){oe(t,this.createData());const i=t.ot===ve.INIT||t.ot===ve.VIDEO||t.ot===ve.MUXED;this.starved&&i&&(t.bs=!0,t.su=!0,this.starved=!1),t.su==null&&(t.su=this.buffering);const{includeKeys:r}=this;r&&(t=Object.keys(t).reduce((n,a)=>(r.includes(a)&&(n[a]=t[a]),n),{})),this.useHeaders?(e.headers||(e.headers={}),Zu(e.headers,t)):e.url=eh(e.url,t)}getObjectType(e){const{type:t}=e;if(t==="subtitle")return ve.TIMED_TEXT;if(e.sn==="initSegment")return ve.INIT;if(t==="audio")return ve.AUDIO;if(t==="main")return this.hls.audioTracks.length?ve.VIDEO:ve.MUXED}getTopBandwidth(e){let t=0,i;const r=this.hls;if(e===ve.AUDIO)i=r.audioTracks;else{const n=r.maxAutoLevel,a=n>-1?n+1:r.levels.length;i=r.levels.slice(0,a)}for(const n of i)n.bitrate>t&&(t=n.bitrate);return t>0?t:NaN}getBufferLength(e){const t=this.hls.media,i=e===ve.AUDIO?this.audioBuffer:this.videoBuffer;return!i||!t?NaN:se.bufferInfo(i,t.currentTime,this.config.maxBufferHole).len*1e3}createPlaylistLoader(){const{pLoader:e}=this.config,t=this.applyPlaylistData,i=e||this.config.loader;return class{constructor(n){this.loader=void 0,this.loader=new i(n)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(n,a,o){t(n),this.loader.load(n,a,o)}}}createFragmentLoader(){const{fLoader:e}=this.config,t=this.applyFragmentData,i=e||this.config.loader;return class{constructor(n){this.loader=void 0,this.loader=new i(n)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(n,a,o){t(n),this.loader.load(n,a,o)}}}}const ih=3e5;class sh{constructor(e){this.hls=void 0,this.log=void 0,this.loader=null,this.uri=null,this.pathwayId=".",this.pathwayPriority=null,this.timeToLoad=300,this.reloadTimer=-1,this.updated=0,this.started=!1,this.enabled=!0,this.levels=null,this.audioTracks=null,this.subtitleTracks=null,this.penalizedPathways={},this.hls=e,this.log=S.log.bind(S,"[content-steering]:"),this.registerListeners()}registerListeners(){const e=this.hls;e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(p.MANIFEST_PARSED,this.onManifestParsed,this),e.on(p.ERROR,this.onError,this)}unregisterListeners(){const e=this.hls;e&&(e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(p.MANIFEST_PARSED,this.onManifestParsed,this),e.off(p.ERROR,this.onError,this))}startLoad(){if(this.started=!0,this.clearTimeout(),this.enabled&&this.uri){if(this.updated){const e=this.timeToLoad*1e3-(performance.now()-this.updated);if(e>0){this.scheduleRefresh(this.uri,e);return}}this.loadSteeringManifest(this.uri)}}stopLoad(){this.started=!1,this.loader&&(this.loader.destroy(),this.loader=null),this.clearTimeout()}clearTimeout(){this.reloadTimer!==-1&&(self.clearTimeout(this.reloadTimer),this.reloadTimer=-1)}destroy(){this.unregisterListeners(),this.stopLoad(),this.hls=null,this.levels=this.audioTracks=this.subtitleTracks=null}removeLevel(e){const t=this.levels;t&&(this.levels=t.filter(i=>i!==e))}onManifestLoading(){this.stopLoad(),this.enabled=!0,this.timeToLoad=300,this.updated=0,this.uri=null,this.pathwayId=".",this.levels=this.audioTracks=this.subtitleTracks=null}onManifestLoaded(e,t){const{contentSteering:i}=t;i!==null&&(this.pathwayId=i.pathwayId,this.uri=i.uri,this.started&&this.startLoad())}onManifestParsed(e,t){this.audioTracks=t.audioTracks,this.subtitleTracks=t.subtitleTracks}onError(e,t){const{errorAction:i}=t;if((i==null?void 0:i.action)===me.SendAlternateToPenaltyBox&&i.flags===Ce.MoveAllAlternatesMatchingHost){const r=this.levels;let n=this.pathwayPriority,a=this.pathwayId;if(t.context){const{groupId:o,pathwayId:l,type:c}=t.context;o&&r?a=this.getPathwayForGroupId(o,c,a):l&&(a=l)}a in this.penalizedPathways||(this.penalizedPathways[a]=performance.now()),!n&&r&&(n=r.reduce((o,l)=>(o.indexOf(l.pathwayId)===-1&&o.push(l.pathwayId),o),[])),n&&n.length>1&&(this.updatePathwayPriority(n),i.resolved=this.pathwayId!==a),i.resolved||S.warn(`Could not resolve ${t.details} ("${t.error.message}") with content-steering for Pathway: ${a} levels: ${r&&r.length} priorities: ${JSON.stringify(n)} penalized: ${JSON.stringify(this.penalizedPathways)}`)}}filterParsedLevels(e){this.levels=e;let t=this.getLevelsForPathway(this.pathwayId);if(t.length===0){const i=e[0].pathwayId;this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${i}"`),t=this.getLevelsForPathway(i),this.pathwayId=i}return t.length!==e.length?(this.log(`Found ${t.length}/${e.length} levels in Pathway "${this.pathwayId}"`),t):e}getLevelsForPathway(e){return this.levels===null?[]:this.levels.filter(t=>e===t.pathwayId)}updatePathwayPriority(e){this.pathwayPriority=e;let t;const i=this.penalizedPathways,r=performance.now();Object.keys(i).forEach(n=>{r-i[n]>ih&&delete i[n]});for(let n=0;n<e.length;n++){const a=e[n];if(a in i)continue;if(a===this.pathwayId)return;const o=this.hls.nextLoadLevel,l=this.hls.levels[o];if(t=this.getLevelsForPathway(a),t.length>0){this.log(`Setting Pathway to "${a}"`),this.pathwayId=a,Gr(t),this.hls.trigger(p.LEVELS_UPDATED,{levels:t});const c=this.hls.levels[o];l&&c&&this.levels&&(c.attrs["STABLE-VARIANT-ID"]!==l.attrs["STABLE-VARIANT-ID"]&&c.bitrate!==l.bitrate&&this.log(`Unstable Pathways change from bitrate ${l.bitrate} to ${c.bitrate}`),this.hls.nextLoadLevel=o);break}}}getPathwayForGroupId(e,t,i){const r=this.getLevelsForPathway(i).concat(this.levels||[]);for(let n=0;n<r.length;n++)if(t===ee.AUDIO_TRACK&&r[n].hasAudioGroup(e)||t===ee.SUBTITLE_TRACK&&r[n].hasSubtitleGroup(e))return r[n].pathwayId;return i}clonePathways(e){const t=this.levels;if(!t)return;const i={},r={};e.forEach(n=>{const{ID:a,"BASE-ID":o,"URI-REPLACEMENT":l}=n;if(t.some(u=>u.pathwayId===a))return;const c=this.getLevelsForPathway(o).map(u=>{const h=new ae(u.attrs);h["PATHWAY-ID"]=a;const d=h.AUDIO&&`${h.AUDIO}_clone_${a}`,f=h.SUBTITLES&&`${h.SUBTITLES}_clone_${a}`;d&&(i[h.AUDIO]=d,h.AUDIO=d),f&&(r[h.SUBTITLES]=f,h.SUBTITLES=f);const g=ia(u.uri,h["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",l),m=new it({attrs:h,audioCodec:u.audioCodec,bitrate:u.bitrate,height:u.height,name:u.name,url:g,videoCodec:u.videoCodec,width:u.width});if(u.audioGroups)for(let y=1;y<u.audioGroups.length;y++)m.addGroupId("audio",`${u.audioGroups[y]}_clone_${a}`);if(u.subtitleGroups)for(let y=1;y<u.subtitleGroups.length;y++)m.addGroupId("text",`${u.subtitleGroups[y]}_clone_${a}`);return m});t.push(...c),ta(this.audioTracks,i,l,a),ta(this.subtitleTracks,r,l,a)})}loadSteeringManifest(e){const t=this.hls.config,i=t.loader;this.loader&&this.loader.destroy(),this.loader=new i(t);let r;try{r=new self.URL(e)}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest URI: ${e}`);return}if(r.protocol!=="data:"){const u=(this.hls.bandwidthEstimate||t.abrEwmaDefaultEstimate)|0;r.searchParams.set("_HLS_pathway",this.pathwayId),r.searchParams.set("_HLS_throughput",""+u)}const n={responseType:"json",url:r.href},a=t.steeringManifestLoadPolicy.default,o=a.errorRetry||a.timeoutRetry||{},l={loadPolicy:a,timeout:a.maxLoadTimeMs,maxRetry:o.maxNumRetry||0,retryDelay:o.retryDelayMs||0,maxRetryDelay:o.maxRetryDelayMs||0},c={onSuccess:(u,h,d,f)=>{this.log(`Loaded steering manifest: "${r}"`);const g=u.data;if(g.VERSION!==1){this.log(`Steering VERSION ${g.VERSION} not supported!`);return}this.updated=performance.now(),this.timeToLoad=g.TTL;const{"RELOAD-URI":m,"PATHWAY-CLONES":y,"PATHWAY-PRIORITY":v}=g;if(m)try{this.uri=new self.URL(m,r).href}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest RELOAD-URI: ${m}`);return}this.scheduleRefresh(this.uri||d.url),y&&this.clonePathways(y);const T={steeringManifest:g,url:r.toString()};this.hls.trigger(p.STEERING_MANIFEST_LOADED,T),v&&this.updatePathwayPriority(v)},onError:(u,h,d,f)=>{if(this.log(`Error loading steering manifest: ${u.code} ${u.text} (${h.url})`),this.stopLoad(),u.code===410){this.enabled=!1,this.log(`Steering manifest ${h.url} no longer available`);return}let g=this.timeToLoad*1e3;if(u.code===429){const m=this.loader;if(typeof(m==null?void 0:m.getResponseHeader)=="function"){const y=m.getResponseHeader("Retry-After");y&&(g=parseFloat(y)*1e3)}this.log(`Steering manifest ${h.url} rate limited`);return}this.scheduleRefresh(this.uri||h.url,g)},onTimeout:(u,h,d)=>{this.log(`Timeout loading steering manifest (${h.url})`),this.scheduleRefresh(this.uri||h.url)}};this.log(`Requesting steering manifest: ${r}`),this.loader.load(n,l,c)}scheduleRefresh(e,t=this.timeToLoad*1e3){this.clearTimeout(),this.reloadTimer=self.setTimeout(()=>{var i;const r=(i=this.hls)==null?void 0:i.media;if(r&&!r.ended){this.loadSteeringManifest(e);return}this.scheduleRefresh(e,this.timeToLoad*1e3)},t)}}function ta(s,e,t,i){s&&Object.keys(e).forEach(r=>{const n=s.filter(a=>a.groupId===r).map(a=>{const o=oe({},a);return o.details=void 0,o.attrs=new ae(o.attrs),o.url=o.attrs.URI=ia(a.url,a.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",t),o.groupId=o.attrs["GROUP-ID"]=e[r],o.attrs["PATHWAY-ID"]=i,o});s.push(...n)})}function ia(s,e,t,i){const{HOST:r,PARAMS:n,[t]:a}=i;let o;e&&(o=a==null?void 0:a[e],o&&(s=o));const l=new self.URL(s);return r&&!o&&(l.host=r),n&&Object.keys(n).sort().forEach(c=>{c&&l.searchParams.set(c,n[c])}),l.href}const rh=/^age:\s*[\d.]+\s*$/im;class sa{constructor(e){this.xhrSetup=void 0,this.requestTimeout=void 0,this.retryTimeout=void 0,this.retryDelay=void 0,this.config=null,this.callbacks=null,this.context=null,this.loader=null,this.stats=void 0,this.xhrSetup=e&&e.xhrSetup||null,this.stats=new Ct,this.retryDelay=0}destroy(){this.callbacks=null,this.abortInternal(),this.loader=null,this.config=null,this.context=null,this.xhrSetup=null,this.stats=null}abortInternal(){const e=this.loader;self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),e&&(e.onreadystatechange=null,e.onprogress=null,e.readyState!==4&&(this.stats.aborted=!0,e.abort()))}abort(){var e;this.abortInternal(),(e=this.callbacks)!=null&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.loader)}load(e,t,i){if(this.stats.loading.start)throw new Error("Loader can only be used once.");this.stats.loading.start=self.performance.now(),this.context=e,this.config=t,this.callbacks=i,this.loadInternal()}loadInternal(){const{config:e,context:t}=this;if(!e||!t)return;const i=this.loader=new self.XMLHttpRequest,r=this.stats;r.loading.first=0,r.loaded=0,r.aborted=!1;const n=this.xhrSetup;n?Promise.resolve().then(()=>{if(!this.stats.aborted)return n(i,t.url)}).catch(a=>(i.open("GET",t.url,!0),n(i,t.url))).then(()=>{this.stats.aborted||this.openAndSendXhr(i,t,e)}).catch(a=>{this.callbacks.onError({code:i.status,text:a.message},t,i,r)}):this.openAndSendXhr(i,t,e)}openAndSendXhr(e,t,i){e.readyState||e.open("GET",t.url,!0);const r=t.headers,{maxTimeToFirstByteMs:n,maxLoadTimeMs:a}=i.loadPolicy;if(r)for(const 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),i.timeout=n&&K(n)?n:a,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),i.timeout),e.send()}readystatechange(){const{context:e,loader:t,stats:i}=this;if(!e||!t)return;const r=t.readyState,n=this.config;if(!i.aborted&&r>=2&&(i.loading.first===0&&(i.loading.first=Math.max(self.performance.now(),i.loading.start),n.timeout!==n.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),n.timeout=n.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),n.loadPolicy.maxLoadTimeMs-(i.loading.first-i.loading.start)))),r===4)){self.clearTimeout(this.requestTimeout),t.onreadystatechange=null,t.onprogress=null;const a=t.status,o=t.responseType!=="text";if(a>=200&&a<300&&(o&&t.response||t.responseText!==null)){i.loading.end=Math.max(self.performance.now(),i.loading.first);const l=o?t.response:t.responseText,c=t.responseType==="arraybuffer"?l.byteLength:l.length;if(i.loaded=i.total=c,i.bwEstimate=i.total*8e3/(i.loading.end-i.loading.first),!this.callbacks)return;const u=this.callbacks.onProgress;if(u&&u(i,e,l,t),!this.callbacks)return;const h={url:t.responseURL,data:l,code:a};this.callbacks.onSuccess(h,i,e,t)}else{const l=n.loadPolicy.errorRetry,c=i.retry,u={url:e.url,data:void 0,code:a};Ut(l,c,!1,u)?this.retry(l):(S.error(`${a} while loading ${e.url}`),this.callbacks.onError({code:a,text:t.statusText},e,t,i))}}}loadtimeout(){var e;const t=(e=this.config)==null?void 0:e.loadPolicy.timeoutRetry,i=this.stats.retry;if(Ut(t,i,!0))this.retry(t);else{var r;S.warn(`timeout while loading ${(r=this.context)==null?void 0:r.url}`);const n=this.callbacks;n&&(this.abortInternal(),n.onTimeout(this.stats,this.context,this.loader))}}retry(e){const{context:t,stats:i}=this;this.retryDelay=Fi(e,i.retry),i.retry++,S.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${t==null?void 0:t.url}, retrying ${i.retry}/${e.maxNumRetry} in ${this.retryDelay}ms`),this.abortInternal(),this.loader=null,self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(this.loadInternal.bind(this),this.retryDelay)}loadprogress(e){const t=this.stats;t.loaded=e.loaded,e.lengthComputable&&(t.total=e.total)}getCacheAge(){let e=null;if(this.loader&&rh.test(this.loader.getAllResponseHeaders())){const t=this.loader.getResponseHeader("age");e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.loader&&new RegExp(`^${e}:\\s*[\\d.]+\\s*$`,"im").test(this.loader.getAllResponseHeaders())?this.loader.getResponseHeader(e):null}}function nh(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch{}return!1}const ah=/(\d+)-(\d+)\/(\d+)/;class ra{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||uh,this.controller=new self.AbortController,this.stats=new Ct}destroy(){this.loader=this.callbacks=this.context=this.config=this.request=null,this.abortInternal(),this.response=null,this.fetchSetup=this.controller=this.stats=null}abortInternal(){this.controller&&!this.stats.loading.end&&(this.stats.aborted=!0,this.controller.abort())}abort(){var e;this.abortInternal(),(e=this.callbacks)!=null&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.response)}load(e,t,i){const r=this.stats;if(r.loading.start)throw new Error("Loader can only be used once.");r.loading.start=self.performance.now();const n=oh(e,this.controller.signal),a=i.onProgress,o=e.responseType==="arraybuffer",l=o?"byteLength":"length",{maxTimeToFirstByteMs:c,maxLoadTimeMs:u}=t.loadPolicy;this.context=e,this.config=t,this.callbacks=i,this.request=this.fetchSetup(e,n),self.clearTimeout(this.requestTimeout),t.timeout=c&&K(c)?c:u,this.requestTimeout=self.setTimeout(()=>{this.abortInternal(),i.onTimeout(r,e,this.response)},t.timeout),self.fetch(this.request).then(h=>{this.response=this.loader=h;const d=Math.max(self.performance.now(),r.loading.start);if(self.clearTimeout(this.requestTimeout),t.timeout=u,this.requestTimeout=self.setTimeout(()=>{this.abortInternal(),i.onTimeout(r,e,this.response)},u-(d-r.loading.start)),!h.ok){const{status:f,statusText:g}=h;throw new hh(g||"fetch, bad network response",f,h)}return r.loading.first=d,r.total=ch(h.headers)||r.total,a&&K(t.highWaterMark)?this.loadProgressively(h,r,e,t.highWaterMark,a):o?h.arrayBuffer():e.responseType==="json"?h.json():h.text()}).then(h=>{const d=this.response;if(!d)throw new Error("loader destroyed");self.clearTimeout(this.requestTimeout),r.loading.end=Math.max(self.performance.now(),r.loading.first);const f=h[l];f&&(r.loaded=r.total=f);const g={url:d.url,data:h,code:d.status};a&&!K(t.highWaterMark)&&a(r,e,h,d),i.onSuccess(g,r,e,d)}).catch(h=>{if(self.clearTimeout(this.requestTimeout),r.aborted)return;const d=h&&h.code||0,f=h?h.message:null;i.onError({code:d,text:f},e,h?h.details:null,r)})}getCacheAge(){let e=null;if(this.response){const t=this.response.headers.get("age");e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.response?this.response.headers.get(e):null}loadProgressively(e,t,i,r=0,n){const a=new Jr,o=e.body.getReader(),l=()=>o.read().then(c=>{if(c.done)return a.dataLength&&n(t,i,a.flush(),e),Promise.resolve(new ArrayBuffer(0));const u=c.value,h=u.length;return t.loaded+=h,h<r||a.dataLength?(a.push(u),a.dataLength>=r&&n(t,i,a.flush(),e)):n(t,i,u,e),l()}).catch(()=>Promise.reject());return l()}}function oh(s,e){const t={method:"GET",mode:"cors",credentials:"same-origin",signal:e,headers:new self.Headers(oe({},s.headers))};return s.rangeEnd&&t.headers.set("Range","bytes="+s.rangeStart+"-"+String(s.rangeEnd-1)),t}function lh(s){const e=ah.exec(s);if(e)return parseInt(e[2])-parseInt(e[1])+1}function ch(s){const e=s.get("Content-Range");if(e){const i=lh(e);if(K(i))return i}const t=s.get("Content-Length");if(t)return parseInt(t)}function uh(s,e){return new self.Request(s.url,e)}class hh extends Error{constructor(e,t,i){super(e),this.code=void 0,this.details=void 0,this.code=t,this.details=i}}const dh=/\s/,fh={newCue(s,e,t,i){const r=[];let n,a,o,l,c;const u=self.VTTCue||self.TextTrackCue;for(let d=0;d<i.rows.length;d++)if(n=i.rows[d],o=!0,l=0,c="",!n.isEmpty()){var h;for(let m=0;m<n.chars.length;m++)dh.test(n.chars[m].uchar)&&o?l++:(c+=n.chars[m].uchar,o=!1);n.cueStartTime=e,e===t&&(t+=1e-4),l>=16?l--:l++;const f=Nn(c.trim()),g=is(e,t,f);s!=null&&(h=s.cues)!=null&&h.getCueById(g)||(a=new u(e,t,f),a.id=g,a.line=d+1,a.align="left",a.position=10+Math.min(80,Math.floor(l*8/32)*10),r.push(a))}return s&&r.length&&(r.sort((d,f)=>d.line==="auto"||f.line==="auto"?0:d.line>8&&f.line>8?f.line-d.line:d.line-f.line),r.forEach(d=>Pr(s,d))),r}},gh={maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null},na=he(he({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,preferManagedMediaSource:!0,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,frontBufferFlushThreshold:1/0,maxBufferSize:60*1e3*1e3,maxBufferHole:.1,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,maxFragLookUpTolerance:.25,liveSyncDurationCount:3,liveMaxLatencyDurationCount:1/0,liveSyncDuration:void 0,liveMaxLatencyDuration:void 0,maxLiveSyncPlaybackRate:1,liveDurationInfinity:!1,liveBackBufferLength:null,maxMaxBufferLength:600,enableWorker:!0,workerPath:null,enableSoftwareAES:!0,startLevel:void 0,startFragPrefetch:!1,fpsDroppedMonitoringPeriod:5e3,fpsDroppedMonitoringThreshold:.2,appendErrorMaxRetry:3,loader:sa,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:Kl,bufferController:Yc,capLevelController:os,errorController:kl,fpsController:xu,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:sr,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableID3MetadataCues:!0,useMediaCapabilities:!0,certLoadPolicy:{default:gh},keyLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"},errorRetry:{maxNumRetry:8,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"}}},manifestLoadPolicy:{default:{maxTimeToFirstByteMs:1/0,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},playlistLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:2,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},fragLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:12e4,timeoutRetry:{maxNumRetry:4,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:6,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},steeringManifestLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},manifestLoadingTimeOut:1e4,manifestLoadingMaxRetry:1,manifestLoadingRetryDelay:1e3,manifestLoadingMaxRetryTimeout:64e3,levelLoadingTimeOut:1e4,levelLoadingMaxRetry:4,levelLoadingRetryDelay:1e3,levelLoadingMaxRetryTimeout:64e3,fragLoadingTimeOut:2e4,fragLoadingMaxRetry:6,fragLoadingRetryDelay:1e3,fragLoadingMaxRetryTimeout:64e3},mh()),{},{subtitleStreamController:Kc,subtitleTrackController:zc,timelineController:yu,audioStreamController:Hc,audioTrackController:Vc,emeController:ht,cmcdController:th,contentSteeringController:sh});function mh(){return{cueHandler:fh,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 ph(s,e){if((e.liveSyncDurationCount||e.liveMaxLatencyDurationCount)&&(e.liveSyncDuration||e.liveMaxLatencyDuration))throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");if(e.liveMaxLatencyDurationCount!==void 0&&(e.liveSyncDurationCount===void 0||e.liveMaxLatencyDurationCount<=e.liveSyncDurationCount))throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(e.liveMaxLatencyDuration!==void 0&&(e.liveSyncDuration===void 0||e.liveMaxLatencyDuration<=e.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');const t=ds(s),i=["manifest","level","frag"],r=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return i.forEach(n=>{const a=`${n==="level"?"playlist":n}LoadPolicy`,o=e[a]===void 0,l=[];r.forEach(c=>{const u=`${n}Loading${c}`,h=e[u];if(h!==void 0&&o){l.push(u);const d=t[a].default;switch(e[a]={default:d},c){case"TimeOut":d.maxLoadTimeMs=h,d.maxTimeToFirstByteMs=h;break;case"MaxRetry":d.errorRetry.maxNumRetry=h,d.timeoutRetry.maxNumRetry=h;break;case"RetryDelay":d.errorRetry.retryDelayMs=h,d.timeoutRetry.retryDelayMs=h;break;case"MaxRetryTimeout":d.errorRetry.maxRetryDelayMs=h,d.timeoutRetry.maxRetryDelayMs=h;break}}}),l.length&&S.warn(`hls.js config: "${l.join('", "')}" setting(s) are deprecated, use "${a}": ${JSON.stringify(e[a])}`)}),he(he({},t),e)}function ds(s){return s&&typeof s=="object"?Array.isArray(s)?s.map(ds):Object.keys(s).reduce((e,t)=>(e[t]=ds(s[t]),e),{}):s}function yh(s){const e=s.loader;e!==ra&&e!==sa?(S.log("[config]: Custom loader detected, cannot enable progressive streaming"),s.progressive=!1):nh()&&(s.loader=ra,s.progressive=!0,s.enableSoftwareAES=!0,S.log("[config]: Progressive streaming enabled, using FetchLoader"))}let fs;class vh extends Ni{constructor(e,t){super(e,"[level-controller]"),this._levels=[],this._firstLevel=-1,this._maxAutoLevel=-1,this._startLevel=void 0,this.currentLevel=null,this.currentLevelIndex=-1,this.manualLevelIndex=-1,this.steering=void 0,this.onParsedComplete=void 0,this.steering=t,this._registerListeners()}_registerListeners(){const{hls:e}=this;e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(p.LEVEL_LOADED,this.onLevelLoaded,this),e.on(p.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(p.FRAG_BUFFERED,this.onFragBuffered,this),e.on(p.ERROR,this.onError,this)}_unregisterListeners(){const{hls:e}=this;e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(p.LEVEL_LOADED,this.onLevelLoaded,this),e.off(p.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(p.FRAG_BUFFERED,this.onFragBuffered,this),e.off(p.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){const i=this.hls.config.preferManagedMediaSource,r=[],n={},a={};let o=!1,l=!1,c=!1;t.levels.forEach(u=>{var h,d;const f=u.attrs;let{audioCodec:g,videoCodec:m}=u;((h=g)==null?void 0:h.indexOf("mp4a.40.34"))!==-1&&(fs||(fs=/chrome|firefox/i.test(navigator.userAgent)),fs&&(u.audioCodec=g=void 0)),g&&(u.audioCodec=g=Ot(g,i)),((d=m)==null?void 0:d.indexOf("avc1"))===0&&(m=u.videoCodec=ol(m));const{width:y,height:v,unknownCodecs:T}=u;if(o||(o=!!(y&&v)),l||(l=!!m),c||(c=!!g),T!=null&&T.length||g&&!Ri(g,"audio",i)||m&&!Ri(m,"video",i))return;const{CODECS:x,"FRAME-RATE":L,"HDCP-LEVEL":E,"PATHWAY-ID":w,RESOLUTION:R,"VIDEO-RANGE":B}=f,b=`${`${w||"."}-`}${u.bitrate}-${R}-${L}-${x}-${B}-${E}`;if(n[b])if(n[b].uri!==u.url&&!u.attrs["PATHWAY-ID"]){const D=a[b]+=1;u.attrs["PATHWAY-ID"]=new Array(D+1).join(".");const k=new it(u);n[b]=k,r.push(k)}else n[b].addGroupId("audio",f.AUDIO),n[b].addGroupId("text",f.SUBTITLES);else{const D=new it(u);n[b]=D,a[b]=1,r.push(D)}}),this.filterAndSortMediaOptions(r,t,o,l,c)}filterAndSortMediaOptions(e,t,i,r,n){let a=[],o=[],l=e;if((i||r)&&n&&(l=l.filter(({videoCodec:g,videoRange:m,width:y,height:v})=>(!!g||!!(y&&v))&&Tl(m))),l.length===0){Promise.resolve().then(()=>{if(this.hls){t.levels.length&&this.warn(`One or more CODECS in variant not supported: ${JSON.stringify(t.levels[0].attrs)}`);const g=new Error("no level with compatible codecs found in manifest");this.hls.trigger(p.ERROR,{type:q.MEDIA_ERROR,details:_.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:t.url,error:g,reason:g.message})}});return}if(t.audioTracks){const{preferManagedMediaSource:g}=this.hls.config;a=t.audioTracks.filter(m=>!m.audioCodec||Ri(m.audioCodec,"audio",g)),aa(a)}t.subtitles&&(o=t.subtitles,aa(o));const c=l.slice(0);l.sort((g,m)=>{if(g.attrs["HDCP-LEVEL"]!==m.attrs["HDCP-LEVEL"])return(g.attrs["HDCP-LEVEL"]||"")>(m.attrs["HDCP-LEVEL"]||"")?1:-1;if(i&&g.height!==m.height)return g.height-m.height;if(g.frameRate!==m.frameRate)return g.frameRate-m.frameRate;if(g.videoRange!==m.videoRange)return Nt.indexOf(g.videoRange)-Nt.indexOf(m.videoRange);if(g.videoCodec!==m.videoCodec){const y=Tr(g.videoCodec),v=Tr(m.videoCodec);if(y!==v)return v-y}if(g.uri===m.uri&&g.codecSet!==m.codecSet){const y=Pt(g.codecSet),v=Pt(m.codecSet);if(y!==v)return v-y}return g.averageBitrate!==m.averageBitrate?g.averageBitrate-m.averageBitrate:0});let u=c[0];if(this.steering&&(l=this.steering.filterParsedLevels(l),l.length!==c.length)){for(let g=0;g<c.length;g++)if(c[g].pathwayId===l[0].pathwayId){u=c[g];break}}this._levels=l;for(let g=0;g<l.length;g++)if(l[g]===u){var h;this._firstLevel=g;const m=u.bitrate,y=this.hls.bandwidthEstimate;if(this.log(`manifest loaded, ${l.length} level(s) found, first bitrate: ${m}`),((h=this.hls.userConfig)==null?void 0:h.abrEwmaDefaultEstimate)===void 0){const v=Math.min(m,this.hls.config.abrEwmaDefaultEstimateMax);v>y&&y===na.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=v)}break}const d=n&&!r,f={levels:l,audioTracks:a,subtitleTracks:o,sessionData:t.sessionData,sessionKeys:t.sessionKeys,firstLevel:this._firstLevel,stats:t.stats,audio:n,video:r,altAudio:!d&&a.some(g=>!!g.url)};this.hls.trigger(p.MANIFEST_PARSED,f),(this.hls.config.autoStartLoad||this.hls.forceStartLoad)&&this.hls.startLoad(this.hls.config.startPosition)}get levels(){return this._levels.length===0?null:this._levels}get level(){return this.currentLevelIndex}set level(e){const t=this._levels;if(t.length===0)return;if(e<0||e>=t.length){const u=new Error("invalid level idx"),h=e<0;if(this.hls.trigger(p.ERROR,{type:q.OTHER_ERROR,details:_.LEVEL_SWITCH_ERROR,level:e,fatal:h,error:u,reason:u.message}),h)return;e=Math.min(e,t.length-1)}const i=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,i===e&&a.details&&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 ${i}${n?" with Pathway "+n:""}`);const 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(p.LEVEL_SWITCHING,l);const c=a.details;if(!c||c.live){const u=this.switchParams(a.uri,r==null?void 0:r.details);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){const e=this.hls.config.startLevel;return e!==void 0?e:this.hls.firstAutoLevel}return this._startLevel}set startLevel(e){this._startLevel=e}onError(e,t){t.fatal||!t.context||t.context.type===ee.LEVEL&&t.context.level===this.level&&this.checkRetry(t)}onFragBuffered(e,{frag:t}){if(t!==void 0&&t.type===j.MAIN){const i=t.elementaryStreams;if(!Object.keys(i).some(n=>!!i[n]))return;const 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 i;const{level:r,details:n}=t,a=this._levels[r];if(!a){var o;this.warn(`Invalid level index ${r}`),(o=t.deliveryDirectives)!=null&&o.skip&&(n.deltaUpdateFailed=!0);return}r===this.currentLevelIndex?(a.fragmentError===0&&(a.loadError=0),this.playlistLoaded(r,t,a.details)):(i=t.deliveryDirectives)!=null&&i.skip&&(n.deltaUpdateFailed=!0)}loadPlaylist(e){super.loadPlaylist();const t=this.currentLevelIndex,i=this.currentLevel;if(i&&this.shouldLoadPlaylist(i)){let r=i.uri;if(e)try{r=e.addDirectives(r)}catch(a){this.warn(`Could not construct new URL with HLS Delivery Directives: ${a}`)}const n=i.attrs["PATHWAY-ID"];this.log(`Loading level index ${t}${(e==null?void 0:e.msn)!==void 0?" at sn "+e.msn+" part "+e.part:""} with${n?" Pathway "+n:""} ${r}`),this.clearTimer(),this.hls.trigger(p.LEVEL_LOADING,{url:r,level:t,pathwayId:i.attrs["PATHWAY-ID"],id:0,deliveryDirectives:e||null})}}get nextLoadLevel(){return this.manualLevelIndex!==-1?this.manualLevelIndex:this.hls.nextAutoLevel}set nextLoadLevel(e){this.level=e,this.manualLevelIndex===-1&&(this.hls.nextAutoLevel=e)}removeLevel(e){var t;const i=this._levels.filter((r,n)=>n!==e?!0:(this.steering&&this.steering.removeLevel(r),r===this.currentLevel&&(this.currentLevel=null,this.currentLevelIndex=-1,r.details&&r.details.fragments.forEach(a=>a.level=-1)),!1));Gr(i),this._levels=i,this.currentLevelIndex>-1&&(t=this.currentLevel)!=null&&t.details&&(this.currentLevelIndex=this.currentLevel.details.fragments[0].level),this.hls.trigger(p.LEVELS_UPDATED,{levels:i})}onLevelsUpdated(e,{levels:t}){this._levels=t}checkMaxAutoUpdated(){const{autoLevelCapping:e,maxAutoLevel:t,maxHdcpLevel:i}=this.hls;this._maxAutoLevel!==t&&(this._maxAutoLevel=t,this.hls.trigger(p.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:e,levels:this.levels,maxAutoLevel:t,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:i}))}}function aa(s){const e={};s.forEach(t=>{const i=t.groupId||"";t.id=e[i]=e[i]||0,e[i]++})}class xh{constructor(e){this.config=void 0,this.keyUriToKeyInfo={},this.emeController=null,this.config=e}abort(e){for(const i in this.keyUriToKeyInfo){const r=this.keyUriToKeyInfo[i].loader;if(r){var t;if(e&&e!==((t=r.context)==null?void 0:t.frag.type))return;r.abort()}}}detach(){for(const e in this.keyUriToKeyInfo){const t=this.keyUriToKeyInfo[e];(t.mediaKeySessionContext||t.decryptdata.isCommonEncryption)&&delete this.keyUriToKeyInfo[e]}}destroy(){this.detach();for(const e in this.keyUriToKeyInfo){const t=this.keyUriToKeyInfo[e].loader;t&&t.destroy()}this.keyUriToKeyInfo={}}createKeyLoadError(e,t=_.KEY_LOAD_ERROR,i,r,n){return new $e({type:q.NETWORK_ERROR,details:t,fatal:!1,frag:e,response:n,error:i,networkDetails:r})}loadClear(e,t){if(this.emeController&&this.config.emeEnabled){const{sn:i,cc:r}=e;for(let n=0;n<t.length;n++){const a=t[n];if(r<=a.cc&&(i==="initSegment"||a.sn==="initSegment"||i<a.sn)){this.emeController.selectKeySystemFormat(a).then(o=>{a.setKeyFormat(o)});break}}}}load(e){return!e.decryptdata&&e.encrypted&&this.emeController?this.emeController.selectKeySystemFormat(e).then(t=>this.loadInternal(e,t)):this.loadInternal(e)}loadInternal(e,t){var i,r;t&&e.setKeyFormat(t);const n=e.decryptdata;if(!n){const c=new Error(t?`Expected frag.decryptdata to be defined after setting format ${t}`:"Missing decryption data on fragment in onKeyLoading");return Promise.reject(this.createKeyLoadError(e,_.KEY_LOAD_ERROR,c))}const a=n.uri;if(!a)return Promise.reject(this.createKeyLoadError(e,_.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${a}"`)));let o=this.keyUriToKeyInfo[a];if((i=o)!=null&&i.decryptdata.key)return n.key=o.decryptdata.key,Promise.resolve({frag:e,keyInfo:o});if((r=o)!=null&&r.keyLoadPromise){var l;switch((l=o.mediaKeySessionContext)==null?void 0:l.keyStatus){case void 0:case"status-pending":case"usable":case"usable-in-future":return o.keyLoadPromise.then(c=>(n.key=c.keyInfo.decryptdata.key,{frag:e,keyInfo:o}))}}switch(o=this.keyUriToKeyInfo[a]={decryptdata:n,keyLoadPromise:null,loader:null,mediaKeySessionContext:null},n.method){case"ISO-23001-7":case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return n.keyFormat==="identity"?this.loadKeyHTTP(o,e):this.loadKeyEME(o,e);case"AES-128":return this.loadKeyHTTP(o,e);default:return Promise.reject(this.createKeyLoadError(e,_.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${n.method}"`)))}}loadKeyEME(e,t){const i={frag:t,keyInfo:e};if(this.emeController&&this.config.emeEnabled){const r=this.emeController.loadKey(i);if(r)return(e.keyLoadPromise=r.then(n=>(e.mediaKeySessionContext=n,i))).catch(n=>{throw e.keyLoadPromise=null,n})}return Promise.resolve(i)}loadKeyHTTP(e,t){const i=this.config,r=i.loader,n=new r(i);return t.keyLoader=e.loader=n,e.keyLoadPromise=new Promise((a,o)=>{const l={keyInfo:e,frag:t,responseType:"arraybuffer",url:e.decryptdata.uri},c=i.keyLoadPolicy.default,u={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},h={onSuccess:(d,f,g,m)=>{const{frag:y,keyInfo:v,url:T}=g;if(!y.decryptdata||v!==this.keyUriToKeyInfo[T])return o(this.createKeyLoadError(y,_.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),m));v.decryptdata.key=y.decryptdata.key=new Uint8Array(d.data),y.keyLoader=null,v.loader=null,a({frag:y,keyInfo:v})},onError:(d,f,g,m)=>{this.resetLoader(f),o(this.createKeyLoadError(t,_.KEY_LOAD_ERROR,new Error(`HTTP Error ${d.code} loading key ${d.text}`),g,he({url:l.url,data:void 0},d)))},onTimeout:(d,f,g)=>{this.resetLoader(f),o(this.createKeyLoadError(t,_.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),g))},onAbort:(d,f,g)=>{this.resetLoader(f),o(this.createKeyLoadError(t,_.INTERNAL_ABORTED,new Error("key loading aborted"),g))}};n.load(l,u,h)})}resetLoader(e){const{frag:t,keyInfo:i,url:r}=e,n=i.loader;t.keyLoader===n&&(t.keyLoader=null,i.loader=null),delete this.keyUriToKeyInfo[r],n&&n.destroy()}}function oa(){return self.SourceBuffer||self.WebKitSourceBuffer}function la(){if(!et())return!1;const e=oa();return!e||e.prototype&&typeof e.prototype.appendBuffer=="function"&&typeof e.prototype.remove=="function"}function Th(){if(!la())return!1;const s=et();return typeof(s==null?void 0:s.isTypeSupported)=="function"&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some(e=>s.isTypeSupported(vt(e,"video")))||["mp4a.40.2","fLaC"].some(e=>s.isTypeSupported(vt(e,"audio"))))}function Eh(){var s;const e=oa();return typeof(e==null||(s=e.prototype)==null?void 0:s.changeType)=="function"}const Sh=250,ti=2,bh=.1,Ah=.05;class Lh{constructor(e,t,i,r){this.config=void 0,this.media=null,this.fragmentTracker=void 0,this.hls=void 0,this.nudgeRetry=0,this.stallReported=!1,this.stalled=null,this.moved=!1,this.seeking=!1,this.config=e,this.media=t,this.fragmentTracker=i,this.hls=r}destroy(){this.media=null,this.hls=this.fragmentTracker=null}poll(e,t){const{config:i,media:r,stalled:n}=this;if(r===null)return;const{currentTime:a,seeking:o}=r,l=this.seeking&&!o,c=!this.seeking&&o;if(this.seeking=o,a!==e){if(this.moved=!0,o||(this.nudgeRetry=0),n!==null){if(this.stallReported){const y=self.performance.now()-n;S.warn(`playback not stuck anymore @${a}, after ${Math.round(y)}ms`),this.stallReported=!1}this.stalled=null}return}if(c||l){this.stalled=null;return}if(r.paused&&!o||r.ended||r.playbackRate===0||!se.getBuffered(r).length){this.nudgeRetry=0;return}const u=se.bufferInfo(r,a,0),h=u.nextStart||0;if(o){const y=u.len>ti,v=!h||t&&t.start<=a||h-a>ti&&!this.fragmentTracker.getPartialFragment(a);if(y||v)return;this.moved=!1}if(!this.moved&&this.stalled!==null){var d;if(!(u.len>0)&&!h)return;const v=Math.max(h,u.start||0)-a,T=this.hls.levels?this.hls.levels[this.hls.currentLevel]:null,L=(T==null||(d=T.details)==null?void 0:d.live)?T.details.targetduration*2:ti,E=this.fragmentTracker.getPartialFragment(a);if(v>0&&(v<=L||E)){r.paused||this._trySkipBufferHole(E);return}}const f=self.performance.now();if(n===null){this.stalled=f;return}const g=f-n;if(!o&&g>=Sh&&(this._reportStall(u),!this.media))return;const m=se.bufferInfo(r,a,i.maxBufferHole);this._tryFixBufferStall(m,g)}_tryFixBufferStall(e,t){const{config:i,fragmentTracker:r,media:n}=this;if(n===null)return;const a=n.currentTime,o=r.getPartialFragment(a);o&&(this._trySkipBufferHole(o)||!this.media)||(e.len>i.maxBufferHole||e.nextStart&&e.nextStart-a<i.maxBufferHole)&&t>i.highBufferWatchdogPeriod*1e3&&(S.warn("Trying to nudge playhead over buffer-hole"),this.stalled=null,this._tryNudgeBuffer())}_reportStall(e){const{hls:t,media:i,stallReported:r}=this;if(!r&&i){this.stallReported=!0;const n=new Error(`Playback stalling at @${i.currentTime} due to low buffer (${JSON.stringify(e)})`);S.warn(n.message),t.trigger(p.ERROR,{type:q.MEDIA_ERROR,details:_.BUFFER_STALLED_ERROR,fatal:!1,error:n,buffer:e.len})}}_trySkipBufferHole(e){const{config:t,hls:i,media:r}=this;if(r===null)return 0;const n=r.currentTime,a=se.bufferInfo(r,n,0),o=n<a.start?a.start:a.nextStart;if(o){const l=a.len<=t.maxBufferHole,c=a.len>0&&a.len<1&&r.readyState<3,u=o-n;if(u>0&&(l||c)){if(u>t.maxBufferHole){const{fragmentTracker:d}=this;let f=!1;if(n===0){const g=d.getAppendedFrag(0,j.MAIN);g&&o<g.end&&(f=!0)}if(!f){const g=e||d.getAppendedFrag(n,j.MAIN);if(g){let m=!1,y=g.end;for(;y<o;){const v=d.getPartialFragment(y);if(v)y+=v.duration;else{m=!0;break}}if(m)return 0}}}const h=Math.max(o+Ah,n+bh);if(S.warn(`skipping hole, adjusting currentTime from ${n} to ${h}`),this.moved=!0,this.stalled=null,r.currentTime=h,e&&!e.gap){const d=new Error(`fragment loaded with buffer holes, seeking from ${n} to ${h}`);i.trigger(p.ERROR,{type:q.MEDIA_ERROR,details:_.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:d,reason:d.message,frag:e})}return h}}return 0}_tryNudgeBuffer(){const{config:e,hls:t,media:i,nudgeRetry:r}=this;if(i===null)return;const n=i.currentTime;if(this.nudgeRetry++,r<e.nudgeMaxRetry){const a=n+(r+1)*e.nudgeOffset,o=new Error(`Nudging 'currentTime' from ${n} to ${a}`);S.warn(o.message),i.currentTime=a,t.trigger(p.ERROR,{type:q.MEDIA_ERROR,details:_.BUFFER_NUDGE_ON_STALL,error:o,fatal:!1})}else{const a=new Error(`Playhead still not moving while enough data buffered @${n} after ${e.nudgeMaxRetry} nudges`);S.error(a.message),t.trigger(p.ERROR,{type:q.MEDIA_ERROR,details:_.BUFFER_STALLED_ERROR,error:a,fatal:!0})}}}const Rh=100;class Ch extends $i{constructor(e,t,i){super(e,t,i,"[stream-controller]",j.MAIN),this.audioCodecSwap=!1,this.gapController=null,this.level=-1,this._forceStartLoad=!1,this.altAudio=!1,this.audioOnly=!1,this.fragPlaying=null,this.onvplaying=null,this.onvseeked=null,this.fragLastKbps=0,this.couldBacktrack=!1,this.backtrackFragment=null,this.audioCodecSwitch=!1,this.videoBuffer=null,this._registerListeners()}_registerListeners(){const{hls:e}=this;e.on(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.MANIFEST_PARSED,this.onManifestParsed,this),e.on(p.LEVEL_LOADING,this.onLevelLoading,this),e.on(p.LEVEL_LOADED,this.onLevelLoaded,this),e.on(p.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.on(p.ERROR,this.onError,this),e.on(p.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(p.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.on(p.BUFFER_CREATED,this.onBufferCreated,this),e.on(p.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(p.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(p.FRAG_BUFFERED,this.onFragBuffered,this)}_unregisterListeners(){const{hls:e}=this;e.off(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.MANIFEST_PARSED,this.onManifestParsed,this),e.off(p.LEVEL_LOADED,this.onLevelLoaded,this),e.off(p.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.off(p.ERROR,this.onError,this),e.off(p.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(p.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.off(p.BUFFER_CREATED,this.onBufferCreated,this),e.off(p.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(p.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(p.FRAG_BUFFERED,this.onFragBuffered,this)}onHandlerDestroying(){this._unregisterListeners(),super.onHandlerDestroying()}startLoad(e){if(this.levels){const{lastCurrentTime:t,hls:i}=this;if(this.stopLoad(),this.setInterval(Rh),this.level=-1,!this.startFragRequested){let r=i.startLevel;r===-1&&(i.config.testBandwidth&&this.levels.length>1?(r=0,this.bitrateTest=!0):r=i.firstAutoLevel),i.nextLoadLevel=r,this.level=i.loadLevel,this.loadedmetadata=!1}t>0&&e===-1&&(this.log(`Override startPosition with lastCurrentTime @${t.toFixed(3)}`),e=t),this.state=F.IDLE,this.nextLoadPosition=this.startPosition=this.lastCurrentTime=e,this.tick()}else this._forceStartLoad=!0,this.state=F.STOPPED}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case F.WAITING_LEVEL:{const{levels:t,level:i}=this,r=t==null?void 0:t[i],n=r==null?void 0:r.details;if(n&&(!n.live||this.levelLastLoaded===r)){if(this.waitForCdnTuneIn(n))break;this.state=F.IDLE;break}else if(this.hls.nextLoadLevel!==this.level){this.state=F.IDLE;break}break}case F.FRAG_LOADING_WAITING_RETRY:{var e;const t=self.performance.now(),i=this.retryDate;if(!i||t>=i||(e=this.media)!=null&&e.seeking){const{levels:r,level:n}=this,a=r==null?void 0:r[n];this.resetStartWhenNotLoaded(a||null),this.state=F.IDLE}}break}this.state===F.IDLE&&this.doTickIdle(),this.onTickEnd()}onTickEnd(){super.onTickEnd(),this.checkBuffer(),this.checkFragmentChanged()}doTickIdle(){const{hls:e,levelLastLoaded:t,levels:i,media:r}=this;if(t===null||!r&&(this.startFragRequested||!e.config.startFragPrefetch)||this.altAudio&&this.audioOnly)return;const n=e.nextLoadLevel;if(!(i!=null&&i[n]))return;const a=i[n],o=this.getMainFwdBufferInfo();if(o===null)return;const l=this.getLevelDetails();if(l&&this._streamEnded(o,l)){const m={};this.altAudio&&(m.type="video"),this.hls.trigger(p.BUFFER_EOS,m),this.state=F.ENDED;return}e.loadLevel!==n&&e.manualLevel===-1&&this.log(`Adapting to level ${n} from level ${this.level}`),this.level=e.nextLoadLevel=n;const c=a.details;if(!c||this.state===F.WAITING_LEVEL||c.live&&this.levelLastLoaded!==a){this.level=n,this.state=F.WAITING_LEVEL;return}const u=o.len,h=this.getMaxBufferLength(a.maxBitrate);if(u>=h)return;this.backtrackFragment&&this.backtrackFragment.start>o.end&&(this.backtrackFragment=null);const d=this.backtrackFragment?this.backtrackFragment.start:o.end;let f=this.getNextFragment(d,c);if(this.couldBacktrack&&!this.fragPrevious&&f&&f.sn!=="initSegment"&&this.fragmentTracker.getState(f)!==de.OK){var g;const y=((g=this.backtrackFragment)!=null?g:f).sn-c.startSN,v=c.fragments[y-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,d)){if(!f.gap){const y=this.audioOnly&&!this.altAudio?te.AUDIO:te.VIDEO,v=(y===te.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;v&&this.afterBufferFlushed(v,y,j.MAIN)}f=this.getNextFragmentLoopLoading(f,c,o,j.MAIN,h)}f&&(f.initSegment&&!f.initSegment.data&&!this.bitrateTest&&(f=f.initSegment),this.loadFragment(f,a,d))}loadFragment(e,t,i){const r=this.fragmentTracker.getState(e);this.fragCurrent=e,r===de.NOT_LOADED||r===de.PARTIAL?e.sn==="initSegment"?this._loadInitSegment(e,t):this.bitrateTest?(this.log(`Fragment ${e.sn} of level ${e.level} is being downloaded to test bitrate and will not be buffered`),this._loadBitrateTestFrag(e,t)):(this.startFragRequested=!0,super.loadFragment(e,t,i)):this.clearTrackerIfNeeded(e)}getBufferedFrag(e){return this.fragmentTracker.getBufferedFrag(e,j.MAIN)}followingBufferedFrag(e){return e?this.getBufferedFrag(e.end+.5):null}immediateLevelSwitch(){this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY)}nextLevelSwitch(){const{levels:e,media:t}=this;if(t!=null&&t.readyState){let i;const r=this.getAppendedFrag(t.currentTime);r&&r.start>1&&this.flushMainBuffer(0,r.start-1);const n=this.getLevelDetails();if(n!=null&&n.live){const o=this.getMainFwdBufferInfo();if(!o||o.len<n.targetduration*2)return}if(!t.paused&&e){const o=this.hls.nextLoadLevel,l=e[o],c=this.fragLastKbps;c&&this.fragCurrent?i=this.fragCurrent.duration*l.maxBitrate/(1e3*c)+1:i=0}else i=0;const a=this.getBufferedFrag(t.currentTime+i);if(a){const o=this.followingBufferedFrag(a);if(o){this.abortCurrentFrag();const l=o.maxStartPTS?o.maxStartPTS:o.start,c=o.duration,u=Math.max(a.end,l+Math.min(Math.max(c-this.config.maxFragLookUpTolerance,c*(this.couldBacktrack?.5:.125)),c*(this.couldBacktrack?.75:.25)));this.flushMainBuffer(u,Number.POSITIVE_INFINITY)}}}}abortCurrentFrag(){const e=this.fragCurrent;switch(this.fragCurrent=null,this.backtrackFragment=null,e&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.state){case F.KEY_LOADING:case F.FRAG_LOADING:case F.FRAG_LOADING_WAITING_RETRY:case F.PARSING:case F.PARSED:this.state=F.IDLE;break}this.nextLoadPosition=this.getLoadPosition()}flushMainBuffer(e,t){super.flushMainBuffer(e,t,this.altAudio?"video":null)}onMediaAttached(e,t){super.onMediaAttached(e,t);const i=t.media;this.onvplaying=this.onMediaPlaying.bind(this),this.onvseeked=this.onMediaSeeked.bind(this),i.addEventListener("playing",this.onvplaying),i.addEventListener("seeked",this.onvseeked),this.gapController=new Lh(this.config,i,this.fragmentTracker,this.hls)}onMediaDetaching(){const{media:e}=this;e&&this.onvplaying&&this.onvseeked&&(e.removeEventListener("playing",this.onvplaying),e.removeEventListener("seeked",this.onvseeked),this.onvplaying=this.onvseeked=null,this.videoBuffer=null),this.fragPlaying=null,this.gapController&&(this.gapController.destroy(),this.gapController=null),super.onMediaDetaching()}onMediaPlaying(){this.tick()}onMediaSeeked(){const e=this.media,t=e?e.currentTime:null;K(t)&&this.log(`Media seeked to ${t.toFixed(3)}`);const i=this.getMainFwdBufferInfo();if(i===null||i.len===0){this.warn(`Main forward buffer length on "seeked" event ${i?i.len:"empty"})`);return}this.tick()}onManifestLoading(){this.log("Trigger BUFFER_RESET"),this.hls.trigger(p.BUFFER_RESET,void 0),this.fragmentTracker.removeAllFragments(),this.couldBacktrack=!1,this.startPosition=this.lastCurrentTime=this.fragLastKbps=0,this.levels=this.fragPlaying=this.backtrackFragment=this.levelLastLoaded=null,this.altAudio=this.audioOnly=this.startFragRequested=!1}onManifestParsed(e,t){let i=!1,r=!1;t.levels.forEach(n=>{const a=n.audioCodec;a&&(i=i||a.indexOf("mp4a.40.2")!==-1,r=r||a.indexOf("mp4a.40.5")!==-1)}),this.audioCodecSwitch=i&&r&&!Eh(),this.audioCodecSwitch&&this.log("Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC"),this.levels=t.levels,this.startFragRequested=!1}onLevelLoading(e,t){const{levels:i}=this;if(!i||this.state!==F.IDLE)return;const r=i[t.level];(!r.details||r.details.live&&this.levelLastLoaded!==r||this.waitForCdnTuneIn(r.details))&&(this.state=F.WAITING_LEVEL)}onLevelLoaded(e,t){var i;const{levels:r}=this,n=t.level,a=t.details,o=a.totalduration;if(!r){this.warn(`Levels were reset while loading level ${n}`);return}this.log(`Level ${n} loaded [${a.startSN},${a.endSN}]${a.lastPartSn?`[part-${a.lastPartSn}-${a.lastPartIndex}]`:""}, cc [${a.startCC}, ${a.endCC}] duration:${o}`);const l=r[n],c=this.fragCurrent;c&&(this.state===F.FRAG_LOADING||this.state===F.FRAG_LOADING_WAITING_RETRY)&&c.level!==t.level&&c.loader&&this.abortCurrentFrag();let u=0;if(a.live||(i=l.details)!=null&&i.live){var h;if(this.checkLiveUpdate(a),a.deltaUpdateFailed)return;u=this.alignPlaylists(a,l.details,(h=this.levelLastLoaded)==null?void 0:h.details)}if(l.details=a,this.levelLastLoaded=l,this.hls.trigger(p.LEVEL_UPDATED,{details:a,level:n}),this.state===F.WAITING_LEVEL){if(this.waitForCdnTuneIn(a))return;this.state=F.IDLE}this.startFragRequested?a.live&&this.synchronizeToLiveEdge(a):this.setStartPosition(a,u),this.tick()}_handleFragmentLoadProgress(e){var t;const{frag:i,part:r,payload:n}=e,{levels:a}=this;if(!a){this.warn(`Levels were reset while fragment load was in progress. Fragment ${i.sn} of level ${i.level} will not be buffered`);return}const o=a[i.level],l=o.details;if(!l){this.warn(`Dropping fragment ${i.sn} of level ${i.level} after level details were reset`),this.fragmentTracker.removeFragment(i);return}const c=o.videoCodec,u=l.PTSKnown||!l.live,h=(t=i.initSegment)==null?void 0:t.data,d=this._getAudioCodec(o),f=this.transmuxer=this.transmuxer||new Sn(this.hls,j.MAIN,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),g=r?r.index:-1,m=g!==-1,y=new Bi(i.level,i.sn,i.stats.chunkCount,n.byteLength,g,m),v=this.initPTS[i.cc];f.push(n,h,d,c,i,r,l.totalduration,u,y,v)}onAudioTrackSwitching(e,t){const i=this.altAudio;if(!!!t.url){if(this.mediaBuffer!==this.media){this.log("Switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;const 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();const n=this.hls;i&&(n.trigger(p.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null}),this.fragmentTracker.removeAllFragments()),n.trigger(p.AUDIO_TRACK_SWITCHED,t)}}onAudioTrackSwitched(e,t){const i=t.id,r=!!this.hls.audioTracks[i].url;if(r){const n=this.videoBuffer;n&&this.mediaBuffer!==n&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=n)}this.altAudio=r,this.tick()}onBufferCreated(e,t){const i=t.tracks;let r,n,a=!1;for(const o in i){const l=i[o];if(l.id==="main"){if(n=o,r=l,o==="video"){const c=i[o];c&&(this.videoBuffer=c.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){const{frag:i,part:r}=t;if(i&&i.type!==j.MAIN)return;if(this.fragContextChanged(i)){this.warn(`Fragment ${i.sn}${r?" p: "+r.index:""} of level ${i.level} finished buffering, but was aborted. state: ${this.state}`),this.state===F.PARSED&&(this.state=F.IDLE);return}const n=r?r.stats:i.stats;this.fragLastKbps=Math.round(8*n.total/(n.buffering.end-n.loading.first)),i.sn!=="initSegment"&&(this.fragPrevious=i),this.fragBufferedComplete(i,r)}onError(e,t){var i;if(t.fatal){this.state=F.ERROR;return}switch(t.details){case _.FRAG_GAP:case _.FRAG_PARSING_ERROR:case _.FRAG_DECRYPT_ERROR:case _.FRAG_LOAD_ERROR:case _.FRAG_LOAD_TIMEOUT:case _.KEY_LOAD_ERROR:case _.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(j.MAIN,t);break;case _.LEVEL_LOAD_ERROR:case _.LEVEL_LOAD_TIMEOUT:case _.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===F.WAITING_LEVEL&&((i=t.context)==null?void 0:i.type)===ee.LEVEL&&(this.state=F.IDLE);break;case _.BUFFER_APPEND_ERROR:case _.BUFFER_FULL_ERROR:if(!t.parent||t.parent!=="main")return;if(t.details===_.BUFFER_APPEND_ERROR){this.resetLoadingState();return}this.reduceLengthAndFlushBuffer(t)&&this.flushMainBuffer(0,Number.POSITIVE_INFINITY);break;case _.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}checkBuffer(){const{media:e,gapController:t}=this;if(!(!e||!t||!e.readyState)){if(this.loadedmetadata||!se.getBuffered(e).length){const i=this.state!==F.IDLE?this.fragCurrent:null;t.poll(this.lastCurrentTime,i)}this.lastCurrentTime=e.currentTime}}onFragLoadEmergencyAborted(){this.state=F.IDLE,this.loadedmetadata||(this.startFragRequested=!1,this.nextLoadPosition=this.startPosition),this.tickImmediate()}onBufferFlushed(e,{type:t}){if(t!==te.AUDIO||this.audioOnly&&!this.altAudio){const i=(t===te.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;this.afterBufferFlushed(i,t,j.MAIN),this.tick()}}onLevelsUpdated(e,t){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level),this.levels=t.levels}swapAudioCodec(){this.audioCodecSwap=!this.audioCodecSwap}seekToStartPos(){const{media:e}=this;if(!e)return;const t=e.currentTime;let i=this.startPosition;if(i>=0&&t<i){if(e.seeking){this.log(`could not seek to ${i}, already seeking at ${t}`);return}const r=se.getBuffered(e),a=(r.length?r.start(0):0)-i;a>0&&(a<this.config.maxBufferHole||a<this.config.maxFragLookUpTolerance)&&(this.log(`adjusting start position by ${a} to match buffer start`),i+=a,this.startPosition=i),this.log(`seek to target start position ${i} from current time ${t}`),e.currentTime=i}}_getAudioCodec(e){let t=this.config.defaultAudioCodec||e.audioCodec;return this.audioCodecSwap&&t&&(this.log("Swapping audio codec"),t.indexOf("mp4a.40.5")!==-1?t="mp4a.40.2":t="mp4a.40.5"),t}_loadBitrateTestFrag(e,t){e.bitrateTest=!0,this._doFragLoad(e,t).then(i=>{const{hls:r}=this;if(!i||this.fragContextChanged(e))return;t.fragmentError=0,this.state=F.IDLE,this.startFragRequested=!1,this.bitrateTest=!1;const n=e.stats;n.parsing.start=n.parsing.end=n.buffering.start=n.buffering.end=self.performance.now(),r.trigger(p.FRAG_LOADED,i),e.bitrateTest=!1})}_handleTransmuxComplete(e){var t;const i="main",{hls:r}=this,{remuxResult:n,chunkMeta:a}=e,o=this.getCurrentContext(a);if(!o){this.resetWhenMissingContext(a);return}const{frag:l,part:c,level:u}=o,{video:h,text:d,id3:f,initSegment:g}=n,{details:m}=u,y=this.altAudio?void 0:n.audio;if(this.fragContextChanged(l)){this.fragmentTracker.removeFragment(l);return}if(this.state=F.PARSING,g){if(g!=null&&g.tracks){const x=l.initSegment||l;this._bufferInitSegment(u,g.tracks,x,a),r.trigger(p.FRAG_PARSING_INIT_SEGMENT,{frag:x,id:i,tracks:g.tracks})}const v=g.initPTS,T=g.timescale;K(v)&&(this.initPTS[l.cc]={baseTime:v,timescale:T},r.trigger(p.INIT_PTS_FOUND,{frag:l,id:i,initPTS:v,timescale:T}))}if(h&&m&&l.sn!=="initSegment"){const v=m.fragments[l.sn-1-m.startSN],T=l.sn===m.startSN,x=!v||l.cc>v.cc;if(n.independent!==!1){const{startPTS:L,endPTS:E,startDTS:w,endDTS:R}=h;if(c)c.elementaryStreams[h.type]={startPTS:L,endPTS:E,startDTS:w,endDTS:R};else if(h.firstKeyFrame&&h.independent&&a.id===1&&!x&&(this.couldBacktrack=!0),h.dropped&&h.independent){const B=this.getMainFwdBufferInfo(),C=(B?B.end:this.getLoadPosition())+this.config.maxBufferHole,b=h.firstKeyFramePTS?h.firstKeyFramePTS:L;if(!T&&C<b-this.config.maxBufferHole&&!x){this.backtrack(l);return}else x&&(l.gap=!0);l.setElementaryStreamInfo(h.type,l.start,E,l.start,R,!0)}else T&&L>ti&&(l.gap=!0);l.setElementaryStreamInfo(h.type,L,E,w,R),this.backtrackFragment&&(this.backtrackFragment=l),this.bufferFragmentData(h,l,c,a,T||x)}else if(T||x)l.gap=!0;else{this.backtrack(l);return}}if(y){const{startPTS:v,endPTS:T,startDTS:x,endDTS:L}=y;c&&(c.elementaryStreams[te.AUDIO]={startPTS:v,endPTS:T,startDTS:x,endDTS:L}),l.setElementaryStreamInfo(te.AUDIO,v,T,x,L),this.bufferFragmentData(y,l,c,a)}if(m&&f!=null&&(t=f.samples)!=null&&t.length){const v={id:i,frag:l,details:m,samples:f.samples};r.trigger(p.FRAG_PARSING_METADATA,v)}if(m&&d){const v={id:i,frag:l,details:m,samples:d.samples};r.trigger(p.FRAG_PARSING_USERDATA,v)}}_bufferInitSegment(e,t,i,r){if(this.state!==F.PARSING)return;this.audioOnly=!!t.audio&&!t.video,this.altAudio&&!this.audioOnly&&delete t.audio;const{audio:n,video:a,audiovideo:o}=t;if(n){let l=e.audioCodec;const c=navigator.userAgent.toLowerCase();this.audioCodecSwitch&&(l&&(l.indexOf("mp4a.40.5")!==-1?l="mp4a.40.2":l="mp4a.40.5"),n.metadata.channelCount!==1&&c.indexOf("firefox")===-1&&(l="mp4a.40.5")),l&&l.indexOf("mp4a.40.5")!==-1&&c.indexOf("android")!==-1&&n.container!=="audio/mpeg"&&(l="mp4a.40.2",this.log(`Android: force audio codec to ${l}`)),e.audioCodec&&e.audioCodec!==l&&this.log(`Swapping manifest audio codec "${e.audioCodec}" for "${l}"`),n.levelCodec=l,n.id="main",this.log(`Init audio buffer, container:${n.container}, codecs[selected/level/parsed]=[${l||""}/${e.audioCodec||""}/${n.codec}]`)}a&&(a.levelCodec=e.videoCodec,a.id="main",this.log(`Init video buffer, container:${a.container}, codecs[level/parsed]=[${e.videoCodec||""}/${a.codec}]`)),o&&this.log(`Init audiovideo buffer, container:${o.container}, codecs[level/parsed]=[${e.codecs}/${o.codec}]`),this.hls.trigger(p.BUFFER_CODECS,t),Object.keys(t).forEach(l=>{const u=t[l].initSegment;u!=null&&u.byteLength&&this.hls.trigger(p.BUFFER_APPENDING,{type:l,data:u,frag:i,part:null,chunkMeta:r,parent:i.type})}),this.tickImmediate()}getMainFwdBufferInfo(){return this.getFwdBufferInfo(this.mediaBuffer?this.mediaBuffer:this.media,j.MAIN)}backtrack(e){this.couldBacktrack=!0,this.backtrackFragment=e,this.resetTransmuxer(),this.flushBufferGap(e),this.fragmentTracker.removeFragment(e),this.fragPrevious=null,this.nextLoadPosition=e.start,this.state=F.IDLE}checkFragmentChanged(){const e=this.media;let t=null;if(e&&e.readyState>1&&e.seeking===!1){const i=e.currentTime;if(se.isBuffered(e,i)?t=this.getAppendedFrag(i):se.isBuffered(e,i+.1)&&(t=this.getAppendedFrag(i+.1)),t){this.backtrackFragment=null;const r=this.fragPlaying,n=t.level;(!r||t.sn!==r.sn||r.level!==n)&&(this.fragPlaying=t,this.hls.trigger(p.FRAG_CHANGED,{frag:t}),(!r||r.level!==n)&&this.hls.trigger(p.LEVEL_SWITCHED,{level:n}))}}}get nextLevel(){const e=this.nextBufferedFrag;return e?e.level:-1}get currentFrag(){const e=this.media;return e?this.fragPlaying||this.getAppendedFrag(e.currentTime):null}get currentProgramDateTime(){const e=this.media;if(e){const t=e.currentTime,i=this.currentFrag;if(i&&K(t)&&K(i.programDateTime)){const r=i.programDateTime+(t-i.start)*1e3;return new Date(r)}}return null}get currentLevel(){const e=this.currentFrag;return e?e.level:-1}get nextBufferedFrag(){const e=this.currentFrag;return e?this.followingBufferedFrag(e):null}get forceStartLoad(){return this._forceStartLoad}}class Ne{static get version(){return"1.5.6"}static isMSESupported(){return la()}static isSupported(){return Th()}static getMediaSource(){return et()}static get Events(){return p}static get ErrorTypes(){return q}static get ErrorDetails(){return _}static get DefaultConfig(){return Ne.defaultConfig?Ne.defaultConfig:na}static set DefaultConfig(e){Ne.defaultConfig=e}constructor(e={}){this.config=void 0,this.userConfig=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this.started=!1,this._emitter=new qi,this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.abrController=void 0,this.bufferController=void 0,this.capLevelController=void 0,this.latencyController=void 0,this.levelController=void 0,this.streamController=void 0,this.audioTrackController=void 0,this.subtitleTrackController=void 0,this.emeController=void 0,this.cmcdController=void 0,this._media=null,this.url=null,this.triggeringException=void 0,xo(e.debug||!1,"Hls instance");const t=this.config=ph(Ne.DefaultConfig,e);this.userConfig=e,t.progressive&&yh(t);const{abrController:i,bufferController:r,capLevelController:n,errorController:a,fpsController:o}=t,l=new a(this),c=this.abrController=new i(this),u=this.bufferController=new r(this),h=this.capLevelController=new n(this),d=new o(this),f=new dl(this),g=new yl(this),m=t.contentSteeringController,y=m?new m(this):null,v=this.levelController=new vh(this,y),T=new zl(this),x=new xh(this.config),L=this.streamController=new Ch(this,T,x);h.setStreamController(L),d.setStreamController(L);const E=[f,v,L];y&&E.splice(1,0,y),this.networkControllers=E;const w=[c,u,h,d,g,T];this.audioTrackController=this.createController(t.audioTrackController,E);const R=t.audioStreamController;R&&E.push(new R(this,T,x)),this.subtitleTrackController=this.createController(t.subtitleTrackController,E);const B=t.subtitleStreamController;B&&E.push(new B(this,T,x)),this.createController(t.timelineController,w),x.emeController=this.emeController=this.createController(t.emeController,w),this.cmcdController=this.createController(t.cmcdController,w),this.latencyController=this.createController(vl,w),this.coreComponents=w,E.push(l);const C=l.onErrorOut;typeof C=="function"&&this.on(p.ERROR,C,l)}createController(e,t){if(e){const i=new e(this);return t&&t.push(i),i}return null}on(e,t,i=this){this._emitter.on(e,t,i)}once(e,t,i=this){this._emitter.once(e,t,i)}removeAllListeners(e){this._emitter.removeAllListeners(e)}off(e,t,i=this,r){this._emitter.off(e,t,i,r)}listeners(e){return this._emitter.listeners(e)}emit(e,t,i){return this._emitter.emit(e,t,i)}trigger(e,t){if(this.config.debug)return this.emit(e,e,t);try{return this.emit(e,e,t)}catch(i){if(S.error("An internal error happened while handling event "+e+'. Error message: "'+i.message+'". Here is a stacktrace:',i),!this.triggeringException){this.triggeringException=!0;const r=e===p.ERROR;this.trigger(p.ERROR,{type:q.OTHER_ERROR,details:_.INTERNAL_EXCEPTION,fatal:r,event:e,error:i}),this.triggeringException=!1}}return!1}listenerCount(e){return this._emitter.listenerCount(e)}destroy(){S.log("destroy"),this.trigger(p.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;const e=this.config;e.xhrSetup=e.fetchSetup=void 0,this.userConfig=null}attachMedia(e){S.log("attachMedia"),this._media=e,this.trigger(p.MEDIA_ATTACHING,{media:e})}detachMedia(){S.log("detachMedia"),this.trigger(p.MEDIA_DETACHING,void 0),this._media=null}loadSource(e){this.stopLoad();const t=this.media,i=this.url,r=this.url=gi.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,S.log(`loadSource:${r}`),t&&i&&(i!==r||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(t)),this.trigger(p.MANIFEST_LOADING,{url:e})}startLoad(e=-1){S.log(`startLoad(${e})`),this.started=!0,this.networkControllers.forEach(t=>{t.startLoad(e)})}stopLoad(){S.log("stopLoad"),this.started=!1,this.networkControllers.forEach(e=>{e.stopLoad()})}resumeBuffering(){this.started&&this.networkControllers.forEach(e=>{"fragmentLoader"in e&&e.startLoad(-1)})}pauseBuffering(){this.networkControllers.forEach(e=>{"fragmentLoader"in e&&e.stopLoad()})}swapAudioCodec(){S.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){S.log("recoverMediaError");const e=this._media;this.detachMedia(),e&&this.attachMedia(e)}removeLevel(e){this.levelController.removeLevel(e)}get levels(){const e=this.levelController.levels;return e||[]}get currentLevel(){return this.streamController.currentLevel}set currentLevel(e){S.log(`set currentLevel:${e}`),this.levelController.manualLevel=e,this.streamController.immediateLevelSwitch()}get nextLevel(){return this.streamController.nextLevel}set nextLevel(e){S.log(`set nextLevel:${e}`),this.levelController.manualLevel=e,this.streamController.nextLevelSwitch()}get loadLevel(){return this.levelController.level}set loadLevel(e){S.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){S.log(`set firstLevel:${e}`),this.levelController.firstLevel=e}get startLevel(){const e=this.levelController.startLevel;return e===-1&&this.abrController.forcedAutoLevel>-1?this.abrController.forcedAutoLevel:e}set startLevel(e){S.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){const t=!!e;t!==this.config.capLevelToPlayerSize&&(t?this.capLevelController.startCapping():(this.capLevelController.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=t)}get autoLevelCapping(){return this._autoLevelCapping}get bandwidthEstimate(){const{bwEstimator:e}=this.abrController;return e?e.getEstimate():NaN}set bandwidthEstimate(e){this.abrController.resetEstimator(e)}get ttfbEstimate(){const{bwEstimator:e}=this.abrController;return e?e.getEstimateTTFB():NaN}set autoLevelCapping(e){this._autoLevelCapping!==e&&(S.log(`set autoLevelCapping:${e}`),this._autoLevelCapping=e,this.levelController.checkMaxAutoUpdated())}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(e){xl(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(){const{levels:e,config:{minAutoBitrate:t}}=this;if(!e)return 0;const i=e.length;for(let r=0;r<i;r++)if(e[r].maxBitrate>=t)return r;return 0}get maxAutoLevel(){const{levels:e,autoLevelCapping:t,maxHdcpLevel:i}=this;let r;if(t===-1&&e!=null&&e.length?r=e.length-1:r=t,i)for(let n=r;n--;){const a=e[n].attrs["HDCP-LEVEL"];if(a&&a<=i)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()}setAudioOption(e){var t;return(t=this.audioTrackController)==null?void 0:t.setAudioOption(e)}setSubtitleOption(e){var t;return(t=this.subtitleTrackController)==null||t.setSubtitleOption(e),null}get allAudioTracks(){const e=this.audioTrackController;return e?e.allAudioTracks:[]}get audioTracks(){const e=this.audioTrackController;return e?e.audioTracks:[]}get audioTrack(){const e=this.audioTrackController;return e?e.audioTrack:-1}set audioTrack(e){const t=this.audioTrackController;t&&(t.audioTrack=e)}get allSubtitleTracks(){const e=this.subtitleTrackController;return e?e.allSubtitleTracks:[]}get subtitleTracks(){const e=this.subtitleTrackController;return e?e.subtitleTracks:[]}get subtitleTrack(){const e=this.subtitleTrackController;return e?e.subtitleTrack:-1}get media(){return this._media}set subtitleTrack(e){const t=this.subtitleTrackController;t&&(t.subtitleTrack=e)}get subtitleDisplay(){const e=this.subtitleTrackController;return e?e.subtitleDisplay:!1}set subtitleDisplay(e){const t=this.subtitleTrackController;t&&(t.subtitleDisplay=e)}get lowLatencyMode(){return this.config.lowLatencyMode}set lowLatencyMode(e){this.config.lowLatencyMode=e}get liveSyncPosition(){return this.latencyController.liveSyncPosition}get latency(){return this.latencyController.latency}get maxLatency(){return this.latencyController.maxLatency}get targetLatency(){return this.latencyController.targetLatency}get drift(){return this.latencyController.drift}get forceStartLoad(){return this.streamController.forceStartLoad}}Ne.defaultConfig=void 0;function gs(){const s=document;return!!(s.fullscreenElement||s.mozFullScreenElement||s.webkitFullscreenElement||s.msFullscreenElement)}function ca(s){if(gs())return new Promise(t=>t(null));const e=s;if(e.requestFullscreen)return e==null?void 0:e.requestFullscreen();if(e.mozRequestFullScreen)return e==null?void 0:e.mozRequestFullScreen();if(e.webkitRequestFullScreen)return e==null?void 0:e.webkitRequestFullScreen();if(e.msRequestFullscreen)return e==null?void 0:e.msRequestFullscreen()}function ua(){if(!gs())return new Promise(e=>e(null));const s=document;if(s.exitFullscreen)return s.exitFullscreen();if(s.mozCancelFullScreen)return s.mozCancelFullScreen();if(s.webkitCancelFullScreen)return s.webkitCancelFullScreen();if(s.msExitFullscreen)return s.msExitFullscreen()}function ha(s,e){let t=null;return function(...i){const r=this;t!==null&&clearTimeout(t),t=setTimeout(()=>{t=null,s.apply(r,i)},e||1e3)}}const ms=new Intl.NumberFormat(void 0,{minimumIntegerDigits:2}),da=["play","pause","ended","loadeddata","waiting","playing","timeupdate","canplay","canplaythrough","statechanged","error"],ps=s=>{const e=Math.floor(s%60),t=Math.floor(s/60)%60,i=Math.floor(s/3600);return i===0?`${t}:${ms.format(e)}`:`${i}:${ms.format(t)}:${ms.format(e)}`},Dh=Ee.extend({name:"VideoPlayer",components:{ESpinner:fi},props:{sources:{type:[Array,String],required:!0},videoListeners:{type:Object,default:()=>({})},videoOptions:{type:Object,default:()=>({})},isHls:{type:Boolean,default:!1},streamingToken:{type:String,default:""},isLiveView:{type:Boolean,default:!1}},data(){return{playing:!1,percentagePlayed:0,videoLength:"0:00",duration:0,videoDuration:0,currentTime:"0:00",realtime:0,isScrubbing:!1,wasPaused:!1,isFullscreen:!1,isFinished:!1,isLoading:!0,isError:!1,player:new Ne}},computed:{sourceItems(){return Array.isArray(this.sources)?this.sources:[{src:this.sources}]},hasStartedOrFinished(){return(this.isFinished||this.realtime<=.1)&&!this.isLoading&&!this.isLooped()},withControls(){const s=this.videoOptions;return(s==null?void 0:s.controls)===!1?"hide":""}},mounted(){this.isHls&&this.initHls(),this.bindEvents(),this.initializePlayer(),this.initializeFullscreenListeners()},beforeDestroy(){this.unbindEvents(),this.destroyPlayer(),this.removeFullscreenListeners()},methods:{initHls(){var e,t,i,r;const s=this.$refs.player;(e=this.player)!=null&&e.stopLoad&&this.player.stopLoad(),Ne.isSupported()&&(this.isLoading=!0,this.player=new Ne({startPosition:0,xhrSetup:n=>{this.streamingToken&&n.setRequestHeader("Authorization",`Bearer ${this.streamingToken}`)}}),(t=this.player)==null||t.loadSource(this.sources[0].src),(i=this.player)==null||i.attachMedia(s),(r=this.player)==null||r.on(Ne.Events.MANIFEST_PARSED,()=>{this.playing&&s.play()}))},handle404Error(){this.isError=!0,this.isLoading=!1,this.playing=!1},bindEvents(){const s=this.$refs.player;da.forEach(e=>{s.addEventListener(e,()=>this.bindVideoEvent(e),!0)})},unbindEvents(){const s=this.$refs.player;da.forEach(e=>{s.removeEventListener(e,()=>this.bindVideoEvent(e),!0)})},bindVideoEvent(s){const e=this.$refs.player,t=this.$refs.timelineContainer;s==="loadeddata"&&(this.videoLength=ps(e.duration)),s==="timeupdate"&&(this.percentagePlayed=(e==null?void 0:e.currentTime)/e.duration*100,t.style.setProperty("--progress-position",this.percentagePlayed.toString())),this.$emit(s,{event,player:e})},initializePlayer(){const s=this.$refs.player;s&&(s.autoplay&&this.setPlaying(!0),document.addEventListener("mouseup",this.handleScrubbingOnMouseEnd),document.addEventListener("keydown",this.handleKeyDown))},destroyPlayer(){window.removeEventListener("keydown",this.handleKeyDown),document.removeEventListener("mouseup",this.handleScrubbingOnMouseEnd)},removeFullscreenListeners(){document.fullscreenEnabled||document.webkitFullscreenEnabled||document.mozFullScreenEnabled||document.msFullscreenEnabled?(document.removeEventListener("fullscreenchange",this.handleFullscreenChange),document.removeEventListener("webkitfullscreenchange",this.handleFullscreenChange),document.removeEventListener("mozfullscreenchange",this.handleFullscreenChange),document.removeEventListener("MSFullscreenChange",this.handleFullscreenChange)):console.log("Fullscreen API is not supported in this browser.")},initializeFullscreenListeners(){document.fullscreenEnabled||document.webkitFullscreenEnabled||document.mozFullScreenEnabled||document.msFullscreenEnabled?(document.addEventListener("fullscreenchange",this.handleFullscreenChange),document.addEventListener("webkitfullscreenchange",this.handleFullscreenChange),document.addEventListener("mozfullscreenchange",this.handleFullscreenChange),document.addEventListener("MSFullscreenChange",this.handleFullscreenChange)):console.log("Fullscreen API is not supported in this browser.")},handleFullscreenChange(){this.isFullscreen=document.fullscreenElement||document.mozFullScreenElement||document.webkitFullscreenElement||document.msFullscreenElement||window.innerWidth==screen.width&&window.innerHeight==screen.height},isLooped(){return this.$refs.player.loop},handleScrubbingOnMouseEnd(s){this.isScrubbing&&this.toggleScrubbing(s)},handleEnded(){this.isFinished=!0,this.playing=!1},handleLoading(){this.isLoading=!1},play(){const s=this.$refs.player;if(!s)return;s.play()!==void 0&&s.play().then(()=>this.setPlaying(!0)).catch(console.error)},pause(){const s=this.$refs.player;s&&(s.pause(),this.setPlaying(!1))},togglePlay(){this.playing?this.pause():this.play()},setPlaying(s){this.playing=s},seekToPercentage(s){const e=this.$refs.player;if(!e)return;const t=s/100*e.duration;e.currentTime=t},convertTimeToDuration(s){return[parseInt(s/60%60,10),parseInt(s%60,10)].join(":").replace(/\b(\d)\b/g,"0$1")},closeFullscreenMode(){document.fullscreenElement&&(ua().then(()=>{this.isFullscreen=!1,console.log("Exited fullscreen")}),this.isFullscreen=!1)},openFullscreenMode(){const s=this.$refs.videoContainer;s&&(ca(s).then(()=>{this.isFullscreen=!0}),this.isFullscreen=!0)},toggleFullscreenMode(){this.isFullscreen?this.closeFullscreenMode():this.openFullscreenMode()},getDuration(){const s=this.$refs.player;this.videoLength=ps(s.duration),this.videoDuration=s.duration},handleTimeUpdate(){const s=this.$refs.player,e=this.$refs.timelineContainer;if(!s||!e)return;this.currentTime=ps(s.currentTime),this.realtime=s.currentTime;const t=Number(this.realtime)/Number(this.videoDuration);e.style.setProperty("--progress-position",t.toString())},handleTimelineUpdate(s){const e=this.$refs.player;if(!document.body.contains(e))return;const t=this.$refs.timelineContainer,i=t.getBoundingClientRect(),r=Math.min(Math.max(0,s.x-i.x),i.width)/i.width;t.style.setProperty("--preview-position",r.toString()),this.isScrubbing&&(s.preventDefault(),t.style.setProperty("--progress-position",r.toString()))},skip(s=5){const e=this.$refs.player;e.currentTime+=s},async toggleScrubbing(s){const e=this.$refs.timelineContainer,t=this.$refs.videoContainer,i=this.$refs.player;if(!i)return;const r=e.getBoundingClientRect(),n=Math.min(Math.max(0,s.x-r.x),r.width)/r.width;if(this.isScrubbing=(s.buttons&1)===1,t.classList.toggle("scrubbing",this.isScrubbing),this.isScrubbing){this.wasPaused=i.paused,await i.pause(),this.handleTimelineUpdate(s);return}if(this.realtime=n*this.videoDuration,i.currentTime=n*this.videoDuration,this.wasPaused)return;const a=i.play();a!==void 0&&a.then(()=>this.handleTimelineUpdate(s)).catch(console.error)},handleKeyDown(s){var t;const e=(t=document.activeElement)==null?void 0:t.tagName.toLowerCase();if(e!=="input")switch(s.key.toLowerCase()){case" ":if(e==="button")return;this.togglePlay();break;case"k":this.togglePlay();break;case"escape":s.preventDefault(),this.closeFullscreenMode(),this.isFullscreen=!1;break;case"f":this.openFullscreenMode(),this.isFullscreen=!0;break}}}}),zh="";var _h=function(){var e=this,t=e._self._c;return t("div",{ref:"videoContainer",staticClass:"video-container paused",attrs:{"data-volume-level":"high"}},[t("video",e._g(e._b({ref:"player",attrs:{controls:!1,preload:"auto"},on:{ended:e.handleEnded,click:e.togglePlay,loadedmetadata:e.getDuration,timeupdate:e.handleTimeUpdate,loadeddata:e.handleLoading}},"video",e.videoOptions,!1),e.videoListeners),e._l(e.sourceItems,function(i){return t("source",e._g({key:i.src,attrs:{src:i.src,type:i.type},on:{error:e.handle404Error}},e.videoListeners))}),0),e.isLoading?t("div",{staticClass:"spinner-container"},[t("ESpinner",{attrs:{color:!e.isHls,size:e.isHls?"7xl":"9xl",opacity:"0.6",dark:!0}})],1):e._e(),e.isError?t("div",{staticClass:"spinner-container e-gap-3"},[t("i",{staticClass:"fa-solid fa-video-slash fa-2xl e-align-middle"}),t("span",[e._v("This video file cannot be played.")])]):e._e(),t("div",{class:["video-controls-container",e.withControls]},[t("div",{staticClass:"controls"},[t("button",{ref:"playPauseBtn",staticClass:"play-pause-btn fa-lg fa-solid",class:{"fa-play":!e.playing,"fa-pause":e.playing},attrs:{title:e.playing?"pause":"play"},on:{click:e.togglePlay}}),t("div",{staticClass:"duration-container"},[t("div",{ref:"currentTimeElem",staticClass:"current-time"},[e._v(" "+e._s(e.currentTime)+" ")]),e._v(" / "),t("div",{ref:"totalTimeElem",staticClass:"total-time"},[e._v(e._s(e.videoLength))])]),t("div",{ref:"timelineContainer",staticClass:"timeline-container",on:{mousemove:e.handleTimelineUpdate,mousedown:e.toggleScrubbing}},[e._m(0)]),t("button",{ref:"fullScreenBtn",staticClass:"full-screen-btn fa-solid",class:{"fa-expand":!e.isFullscreen,"fa-compress":e.isFullscreen},on:{click:e.toggleFullscreenMode}})])])])},Ih=[function(){var s=this,e=s._self._c;return e("div",{staticClass:"timeline"},[e("div",{staticClass:"thumb-indicator"})])}],wh=Be(Dh,_h,Ih,!1,null,"160e835f",null,null);const fa=wh.exports,ii=s=>{const e=N.utcFormat("%_d")(s),i={1:"st",2:"nd",3:"rd"}[e.charAt(1)]||"th";return`${e}${i}`},ga=s=>new Date(Date.UTC(s.getUTCFullYear(),s.getUTCMonth(),s.getUTCDate()+1)).getUTCDate()===1?"":N.utcFormat("%-d")(s),Et=s=>["0"," 0","00"].includes(N.utcFormat("%H")(s))?"":`${N.utcFormat("%H")(s)}h`,ze=s=>{const e=N.utcFormat("%H:%M")(s);return e==="00:00"?"":e},ys=s=>N.utcFormat("%M:%S")(s),ma=s=>`${N.utcFormat("%Hh%Mm")(s)}`,vs=s=>{const e=ze(s),t=ii(s),i=N.utcFormat("%B")(s);return e||`${i} ${t}`},xs=s=>{const e=ze(s),t=Number.parseInt(N.utcFormat("%H")(s)),i=ii(s),r=N.utcFormat("%B")(s);return e&&t%6===0?`${r} ${i} ${e}`:vs(s)},St=s=>e=>{const t=N.utcFormat("%H")(e);return!(N.utcFormat("%M")(e)==="00"&&Number.parseInt(t)%s===0)},Ts=s=>e=>{const t=N.utcFormat("%M")(e);return Number.parseInt(t)%s!==0},pa=s=>e=>{const t=N.utcFormat("%M")(e),i=N.utcFormat("%S")(e);return Number.parseInt(t)%s!==0&&Number.parseInt(i)===0},Y={_10_seconds:25e-6,_20_seconds:1e-4,_30_seconds:15e-5,_1_minute:3e-4,_2_minutes:75e-5,_5_minutes:.002,_15_minutes:.005,_30_minutes:.01,_1_hour:.025,_2_hours:.05,_3_hours:.1,_4_hours:.15,_6_hours:.25,_1_day:1,_2_days:2,_1_month:8,_1_month_abbr:13,_1_month_letter:22,_3_months:33,infinity:1/0},kh={[ft.overview]:[{precision:Y._30_seconds,interval:N.utcMinute.every(2),format:ma},{precision:Y._1_minute,interval:N.utcMinute.every(5),format:ma},{precision:Y._2_minutes,interval:N.utcMinute.every(10),format:vs},{precision:Y._5_minutes,interval:N.utcMinute.every(20),format:xs},{precision:Y._15_minutes,interval:N.utcHour,format:xs},{precision:Y._30_minutes,interval:N.utcHour.every(2),format:xs},{precision:Y._2_hours,interval:N.utcHour.every(6),format:s=>{const e=ze(s),t=ii(s),i=N.utcFormat("%B")(s);return e||`${i} ${t}`}},{precision:Y._3_hours,interval:N.utcHour.every(12),format:vs},{precision:Y._6_hours,interval:N.utcHour.every(24),format:s=>{const e=ii(s);return`${N.utcFormat("%b")(s)} ${e}`}},{precision:Y._2_days,interval:N.utcMonth,format:s=>{const t=s.getUTCMonth()===0&&s.getUTCDate()===1?"%Y – %B":"%B";return N.utcFormat(t)(s)}},{precision:Y.infinity,interval:N.utcYear,format:"%Y"}],[ft.detailed]:[{precision:Y._10_seconds,interval:N.utcSecond.every(10),format:ys},{precision:Y._20_seconds,interval:(Ta=N.utcSecond.every(20))==null?void 0:Ta.filter(pa(2)),format:ys},{precision:Y._30_seconds,interval:(Ea=N.utcSecond.every(30))==null?void 0:Ea.filter(pa(2)),format:ys},{precision:Y._1_minute,interval:N.utcMinute.filter(Ts(5)),format:ze},{precision:Y._2_minutes,interval:(Sa=N.utcMinute.every(2))==null?void 0:Sa.filter(Ts(10)),format:ze},{precision:Y._5_minutes,interval:(ba=N.utcMinute.every(5))==null?void 0:ba.filter(Ts(20)),format:ze},{precision:Y._15_minutes,interval:(Aa=N.utcMinute.every(15))==null?void 0:Aa.filter(St(1)),format:ze},{precision:Y._30_minutes,interval:(La=N.utcMinute.every(30))==null?void 0:La.filter(St(2)),format:ze},{precision:Y._1_hour,interval:N.utcHour.filter(St(6)),format:Et},{precision:Y._2_hours,interval:(Ra=N.utcHour.every(2))==null?void 0:Ra.filter(St(6)),format:Et},{precision:Y._3_hours,interval:(Ca=N.utcHour.every(3))==null?void 0:Ca.filter(St(12)),format:Et},{precision:Y._4_hours,interval:N.utcHour.every(4),format:Et},{precision:Y._6_hours,interval:N.utcHour.every(6),format:Et},{precision:Y._1_day,interval:N.utcDay,format:ga},{precision:Y._2_days,interval:N.utcDay.every(2),format:ga},{precision:Y._1_month,interval:N.utcMonth,format:"%B"},{precision:Y._1_month_abbr,interval:N.utcMonth,format:"%b"},{precision:Y._1_month_letter,interval:N.utcMonth,format:s=>N.utcFormat("%B")(s).charAt(0)},{precision:Y._3_months,interval:N.utcMonth.every(3),format:"Q%q"},{precision:Y.infinity,interval:N.utcMonth.every(3),format:""}],[ft.detailedBackground]:[{precision:Y._10_seconds,interval:N.utcSecond,format:""},{precision:Y._20_seconds,interval:N.utcSecond.every(5),format:""},{precision:Y._30_seconds,interval:N.utcSecond.every(10),format:""},{precision:Y._1_minute,interval:N.utcSecond.every(20),format:""},{precision:Y._2_minutes,interval:N.utcSecond.every(30),format:""},{precision:Y._5_minutes,interval:N.utcMinute,format:""},{precision:Y._15_minutes,interval:N.utcMinute.every(3),format:""},{precision:Y._30_minutes,interval:N.utcMinute.every(6),format:""},{precision:Y._1_hour,interval:N.utcMinute.every(15),format:""},{precision:Y._2_hours,interval:N.utcMinute.every(30),format:""},{precision:Y._3_hours,interval:N.utcHour,format:""},{precision:Y._4_hours,interval:N.utcHour,format:""},{precision:Y._6_hours,interval:N.utcMinute.every(120),format:""},{precision:Y._1_day,interval:N.utcHour.every(8),format:""},{precision:Y._2_days,interval:N.utcHour.every(12),format:""},{precision:Y._1_month,interval:N.utcDay.filter(s=>{const e=s.getUTCDate(),t=new Date(s.getUTCFullYear(),s.getUTCMonth()+1,0).getUTCDate(),i=Math.ceil(t/5);return e===i||e===2*i||e===3*i||e===4*i}),format:""},{precision:Y._1_month_abbr,interval:N.utcDay.filter(s=>{const e=s.getUTCDate(),t=new Date(s.getUTCFullYear(),s.getUTCMonth()+1,0).getUTCDate(),i=Math.ceil(t/4);return e===i||e===2*i||e===3*i}),format:""},{precision:Y._1_month_letter,interval:N.utcDay.filter(s=>{const e=s.getUTCDate(),t=new Date(s.getUTCFullYear(),s.getUTCMonth()+1,0).getUTCDate(),i=Math.ceil(t/2);return e===i}),format:""},{precision:Y._3_months,interval:N.utcMonth,format:""},{precision:Y.infinity,interval:N.utcMonth,format:""}]},Es={bind(s,e){const{value:t}=e;if(typeof t!="function"){console.error("Invalid callback function provided to v-resize-observer");return}const i=new ResizeObserver(r=>{r[0]&&t(r[0])});i.observe(s),s.__resizeObserver__=i},unbind(s){s.__resizeObserver__&&(s.__resizeObserver__.disconnect(),delete s.__resizeObserver__)}},ya=[{name:"resize-observer",definition:Es}],V={eventGroup:"event-group",eventGroupBg:"event-group-bg",eventRect:"event-rect",eventBarContainer:"event-bar-container",eventBarContainerHovered:"event-bar-container--hovered",eventBarContainerSelected:"event-bar-container--selected",eventBar:"event-bar",eventBarHoverZone:"event-bar-hover-zone",eventBarCap:"event-bar-cap",eventRectText:"event-rect-text",eventRectHovered:"event-rect--hovered",eventRectSelected:"event-rect--selected",labelGroup:"label-g",labelBg:"label-bg",labelBgFill:"label-bg-fill",labelText:"label-text",loadingIndicator:"loading-indicator",xAxis:"x-axis",selectedTimestampCursor:"selected-timestamp-cursor",marker:"marker",markerLabel:"marker-label",markerLine:"marker-line",barChartGroup:"bar-chart-group",lineGraphGroup:"line-graph-group",lineGraphPath:"line-graph-path",lineGraphHoverZone:"line-graph-hover-zone",lineGraphDot:"line-graph-dot",curtain:"curtain"},Qe={transparencyGradient:"transparency-gradient",transparencyGradientLight:"transparency-gradient-light",loadingGradient:"loading-gradient"},Ph=Ee.extend({name:"ETimeline",directives:{resizeObserver:Es},props:{eventsGroups:{type:Object,default:()=>({})},xAxesConfig:{type:Object,default:()=>kh},dark:{type:Boolean,default:!1},startDate:{type:String,default:void 0},endDate:{type:String,default:void 0},selectedTimestamp:{type:String,default:void 0},showEventTooltip:{type:Boolean,default:!0},disableZoom:{type:Boolean,default:!1},insertZerosAtInterval:{type:String,default:void 0},flattenLineGraphEnds:{type:Boolean,default:!0},curtains:{type:Boolean,default:!1},showLabels:{type:Boolean,default:!0},rectMinWidth:{type:Number,default:1},barHeight:{type:Number,default:18},barYPadding:{type:Number,default:0},barXPadding:{type:Number,default:0},chartMinHeight:{type:Number,default:60},minZoom:{type:Number,default:1e-4},maxZoom:{type:Number,default:85e4},cursorTimestamp:{type:[String,void 0],default:void 0},selectedClass:{type:[String,void 0],default:void 0},panOnDateClick:{type:Boolean,default:!1},panTransitionDuration:{type:Number,default:500},selectedDate:{type:String,default:""},autoResize:{type:Boolean,default:!0},markers:{type:Array,default:()=>[]},stickyMarkers:{type:Boolean,default:!0}},data(){return{tooltip:null,cursor:null,timeline:null,selectedTimestampCursor:null,svg:null,axesContainer:null,xAxes:{},timeScale:null,initialTimeScale:null,currentTimeScaleDensity:null,zoomBehavior:null,isMouseDown:!1,axisHeight:22,isHoveringEvent:!1,hoveredEvent:null,isHoveringTimeline:!1,hoveredTimestamp:null,eventTooltipStyle:{},hoveredEventType:null,utcOffset:0,lastTransform:{x:0,k:1},transformDiff:{translation:0,scale:1},yScale:null,hoveredCounts:[],countsByTimestamp:{},dotsByTimestamp:{},visibleFrom:null,visibleTo:null,curtainHandleWidth:5,leftCurtainWidth:50,rightCurtainWidth:50,isHoveringCurtain:!1,isDraggingCurtain:!1,characterWidth:7.5,textPadding:5,debouncedOnResize:()=>{},isFirstPaint:!0,timeouts:[],groupsVisibility:{},markersPositions:{}}},computed:{barChartHeight(){return this.barHeight+this.barYPadding},classes(){return{wrapper:{"e-border-gray-700 e-timeline--dark":this.dark,"e-border-gray-300":!this.dark,"e-timeline--dragging":this.isInteractingWithCurtain},background:this.dark?"e-bg-gray-900":"e-bg-gray-50",tooltipSlot:this.dark?"e-bg-gray-900 e-text-white e-border-gray-700":"e-bg-gray-100 e-text-gray-700 e-border-gray-300",eventTooltipSlot:this.dark?"e-bg-gray-900 e-text-white e-border-gray-700":"e-bg-gray-100 e-text-gray-700 e-border-gray-300"}},lineGraphGroups(){return Object.entries(this.filteredEventsGroups).reduce((s,[e,t])=>t.chartType===je.lineGraph?{...s,[e]:t}:s,{})},chartHeight(){if(!this.showLabels)return this.chartMinHeight;const e=(Object.keys(this.lineGraphGroups).length+Object.keys(this.barChartGroups).length)*this.barChartHeight;return Math.max(this.chartMinHeight,e)},barGroups(){return Object.entries(this.filteredEventsGroups).reduce((s,[e,t])=>!t.chartType||t.chartType===je.bars?{...s,[e]:t}:s,{})},barChartGroups(){return Object.entries(this.filteredEventsGroups).reduce((s,[e,t])=>t.chartType===je.barChart?{...s,[e]:t}:s,{})},hasChart(){return Object.keys(this.lineGraphGroups).length+Object.keys(this.barChartGroups).length>0},labelRectWidth(){return Object.values(this.eventsGroups).reduce((t,i)=>{var r;return Math.max(t,(r=i.label)==null?void 0:r.length)},0)*this.characterWidth+2*this.textPadding},combinedXAxesHeight(){const s=Object.keys(this.xAxesConfig).length-1;return this.axisHeight*s},timelineHeight(){const s=Object.keys(this.barGroups).length,e=this.barChartHeight*s,t=this.hasChart?this.chartHeight:0;return this.combinedXAxesHeight+t+e},filteredEventsGroups(){const s=Object.entries(this.eventsGroups).filter(([e,t])=>this.getCurrentGroupVisibility(e));return Object.fromEntries(s)},allEventsSorted(){return Object.values(this.filteredEventsGroups).map(e=>e.events).flat().sort((e,t)=>new Date(e.timestamp||e.startDate)>new Date(t.timestamp||t.startDate)?1:-1)},oldestEvent(){let s;return this.allEventsSorted.length>1?s=this.allEventsSorted[0]:s={timestamp:new Date(new Date().getTime()-864e5)},s},latestEvent(){let s;return this.allEventsSorted.length>1?s=this.allEventsSorted[this.allEventsSorted.length-1]:s={timestamp:new Date},s},allLineChartTimestamps(){const s=new Set;return Object.values(this.lineGraphGroups).forEach(e=>{e.events.forEach(t=>{s.add(t.timestamp)})}),Array.from(s).sort()},placeholderLineChartGroup(){return this.fillTimeGaps(this.allLineChartTimestamps.map(s=>({timestamp:s,count:0})))},filledGapsLineGraphGroups(){return Object.entries(this.lineGraphGroups).reduce((s,[e,t])=>({...s,[e]:{...t,events:this.fillEvents(t.events)}}),{})},isInteractingWithCurtain(){return this.isHoveringCurtain||this.isDraggingCurtain},flattenedCounts(){return[...Object.values(this.lineGraphGroups),...Object.values(this.barChartGroups)].map(s=>s.events).flat()},hiddenGroupsLabels(){return Object.entries(this.groupsVisibility).reduce((s,[e,t])=>t?s:[...s,e],[])},minHoverZone(){return this.showLabels?this.labelRectWidth:0},sortedMarkers(){return[...this.markers].sort((s,e)=>new Date(s.timestamp).getTime()>new Date(e.timestamp).getTime()?1:-1)}},watch:{dark(){this.handleDarkModeChange()},selectedTimestamp(){this.repositionSelectedTimestampCursor()},markers(){this.updateMarkersPositions()},startDate(){this.zoomToStartAndEndDates()},endDate(){this.zoomToStartAndEndDates()},eventsGroups(){this.updateAndRedrawTimeline()},cursorTimestamp(){if(this.cursorTimestamp){this.hoveredTimestamp=this.cursorTimestamp;const s=this.tzStringToDate(this.hoveredTimestamp),e=this.timeScale(s);this.cursor.style.left=e+"px",this.isHoveringTimeline=!0}else this.isHoveringTimeline=!1},selectedDate(s){s&&this.panToTimestamp(s)},groupsVisibility(){this.updateAndRedrawTimeline()}},created(){this.debouncedOnResize=ha(this.handleResize,100)},mounted(){this.initTimeline()},beforeDestroy(){this.clearTimeline(),document.removeEventListener("mouseup",this.handleDocumentMouseUp)},methods:{initTimeline(s,e){if(this.initRefs(),!this.timeline||this.timeline.offsetWidth===0){this.timeouts.push(setTimeout(this.initTimeline,500));return}this.initSvg(),this.initDefs(),this.initUtcOffset(),this.initTimeScale(s,e),this.initXAxes(),this.initYScale(),this.initZoomBehavior(),this.drawEventsGroups(),this.curtains&&(this.initCurtains(),this.emitCurtainChange()),this.initSelectedTimestampCursor(),this.updateMarkersPositions(),this.registerEventsListeners(),this.emitVisibleInterval(gt.initial),this.selectedDate&&this.panOnDateClick&&this.panToTimestamp(this.selectedDate)},initRefs(){this.tooltip=this.$refs.tooltip,this.cursor=this.$refs.cursor,this.timeline=this.$refs.timelineContainer,this.selectedTimestampCursor=this.$refs.selectedTimestamp},initSvg(){this.svg=N.select(this.timeline).append("svg").attr("width",this.timeline.offsetWidth).attr("height",this.timelineHeight)},initDefs(){const s=this.svg.append("defs");Object.entries(this.filteredEventsGroups).forEach(([e,t])=>{const{color:i,chartType:r}=t,n=s.append("linearGradient").attr("id",`${Qe.loadingGradient}-${e}`).attr("x1","0%").attr("y1","0%").attr("x2","100%").attr("y2","0%");n.append("stop").attr("offset","0%").attr("stop-color",i).attr("stop-opacity","0"),n.append("stop").attr("offset","50%").attr("stop-color",i).attr("stop-opacity","0.6"),n.append("stop").attr("offset","100%").attr("stop-color",i).attr("stop-opacity","0"),[je.lineGraph,je.barChart].includes(r)&&[{id:Qe.transparencyGradientLight,stop:38,opacity:.3},{id:Qe.transparencyGradient,stop:130,opacity:.4}].forEach(({id:o,stop:l,opacity:c})=>{const u=s.append("linearGradient").attr("id",`${o}-${e}`).attr("x1","0%").attr("x2","0%").attr("y1","0%").attr("y2","100%");u.append("stop").attr("offset","0%").style("stop-color",i).style("stop-opacity",c),u.append("stop").attr("offset",`${l}%`).style("stop-color",i).style("stop-opacity",0)})})},initUtcOffset(){const s=this.startDate||this.oldestEvent.timestamp||this.oldestEvent.startDate;this.utcOffset=Ve.parseZone(s).utcOffset()},initTimeScale(s,e){const t=s||this.startDate||this.oldestEvent.timestamp||this.oldestEvent.startDate,i=e||this.endDate||this.latestEvent.timestamp||this.latestEvent.endDate;this.timeScale=N.scaleTime().domain([this.tzStringToDate(t),this.tzStringToDate(i)]).range([0,this.timeline.offsetWidth]),this.initialTimeScale=this.timeScale.copy(),this.updateCurrentTimeScaleDensity()},initXAxes(){let s=0;const e=5;for(const t in this.xAxesConfig){const i=this.createAxis(t);this.xAxes[t]=i,this.svg.append("g").classed(V.xAxis,!0).classed(`${V.xAxis}-${t}`,!0).attr("transform",`translate(0, ${s||e})`).call(i),this.translateTicksText(t),s+=this.axisHeight}},initYScale(){this.yScale=N.scaleLinear().range([this.chartHeight,0]),this.updateYScaleDomain()},updateYScaleDomain(){const[s,e]=this.timeScale.domain(),t=this.flattenedCounts.filter(r=>{const n=new Date(r.startDate||r.timestamp),a=new Date(r.endDate||r.timestamp);return a>=s&&a<=e||n>=s&&n<=e}),i=N.max(t,r=>r.count);this.yScale.domain([0,i])},initZoomBehavior(){this.disableZoom||(this.zoomBehavior=N.zoom().on("zoom",this.handleZoom).scaleExtent([this.minZoom,this.maxZoom]),this.svg.call(this.zoomBehavior))},initSelectedTimestampCursor(){this.svg.append("line").attr("class",V.selectedTimestampCursor).style("stroke","red").style("stroke-width","1px").style("opacity",0).attr("x1",0).attr("x2",0).attr("y1",0).attr("y2",this.timelineHeight),this.repositionSelectedTimestampCursor()},updateMarkersPositions(){this.sortedMarkers.forEach((t,i,r)=>{const n=typeof t.timestamp=="string"?this.tzStringToDate(t.timestamp):t.timestamp,a=this.timeScale(n);let o=!1;const l=this.stickyMarkers?Math.max(a,i*12):a;if(i<r.length-1){const c=r[i+1],u=typeof c.timestamp=="string"?this.tzStringToDate(c.timestamp):c.timestamp,h=this.timeScale(u);o=(this.stickyMarkers?Math.max(h,(i+1)*12):a)-l<200+12}this.markersPositions={...this.markersPositions,[t.id]:{isHidden:o,position:l}}})},updateAndRedrawTimeline(){const{startDate:s,endDate:e}=this.getCurrentTimeBounds();this.clearTimeline(),this.initTimeline(s,e)},clearTimeline(){this.svg&&this.svg.remove(),this.countsByTimestamp={}},repositionSelectedTimestampCursor(){const s=this.svg.select(`.${V.selectedTimestampCursor}`);if(!this.selectedTimestamp){s.style("opacity",0);return}const e=this.tzStringToDate(this.selectedTimestamp),t=this.timeScale(e);isNaN(t)?s.style("opacity",0):s.attr("x1",t).attr("x2",t).style("opacity",.5)},updateCurrentTimeScaleDensity(){const s=this.timeScale.invert(0).getTime(),e=this.timeScale.invert(1).getTime(),t=36e5;this.currentTimeScaleDensity=(e-s)/t},registerEventsListeners(){document.addEventListener("mouseup",this.handleDocumentMouseUp),this.svg.on("mousedown",this.handleMouseDown),this.svg.on("mousemove",this.handleMouseMove),this.svg.on("click",this.handleClick),this.svg.on("mouseleave",this.handleMouseLeave)},emitVisibleInterval(s){const e=this.timeScale.invert(0),t=this.timeScale.invert(this.timeline.offsetWidth);if(this.visibleFrom&&this.visibleFrom.getTime()===e.getTime()&&this.visibleTo&&this.visibleTo.getTime()===t.getTime())return;this.visibleFrom=e,this.visibleTo=t;const i=this.dateToTzString(this.visibleFrom),r=this.dateToTzString(this.visibleTo);this.$emit("visible-interval-change",{fromDate:i,toDate:r,trigger:s,transform:this.transformDiff})},createAxis(s){const e=this.xAxesConfig[s],t=this.getAxisTicksConfig(e);return N.axisBottom(this.timeScale).ticks(t.interval).tickFormat(t.formatFn).tickSizeOuter(0).tickSizeInner(this.timelineHeight)},getAxisTicksConfig(s){const{interval:e,format:t}=s.find(r=>r.precision>=this.currentTimeScaleDensity&&r.interval);return{formatFn:r=>typeof t=="function"?t(r):N.timeFormat(t)(r),interval:e}},onResize(s){this.isFirstPaint?(this.handleResize(s),this.isFirstPaint=!1):this.debouncedOnResize(s)},handleResize({contentRect:s}){this.svg&&(this.svg.attr("width",s.width),this.updateAndRedrawTimeline())},handleDarkModeChange(){if(!this.showLabels)return;const s=this;this.svg.selectAll(`.${V.labelBg}`).each(function(){N.select(this).style("fill",s.dark?"black":"white")}),this.svg.selectAll(`.${V.labelBgFill}`).each(function(){const e=N.select(this),t=e.node().dataset.color;e.style("fill",s.getLabelBackgroundColor(t)).style("stroke",s.getTextFillColor(t)).style("stroke-width",.25)}),this.svg.selectAll(`.${V.labelText}`).each(function(){const e=N.select(this),t=e.node().dataset.color;e.style("fill",s.getTextFillColor(t))})},handleMouseDown(){this.isMouseDown=!0},handleDocumentMouseUp(){this.isMouseDown=!1},handleMouseLeave(){this.isHoveringTimeline=!1,this.$emit("hovered-timestamp",void 0)},handleMouseMove(s){if(this.isMouseDown)return;const e=s.offsetX;if(e<=this.minHoverZone){this.isHoveringTimeline=!1;return}const t=this.timeScale.invert(e);this.hoveredTimestamp=this.dateToTzString(t),this.isHoveringTimeline=!0,this.$emit("hovered-timestamp",this.hoveredTimestamp),this.cursor.style.left=e+"px",this.tooltip&&(this.eventTooltipStyle={left:`${e}px`,bottom:`${this.timeline.getBoundingClientRect().height}px`,zIndex:100})},handleClick(s){const e=s.offsetX;if(e<=this.minHoverZone)return;const t=this.timeScale.invert(e),i=this.dateToTzString(t);this.$emit("date-clicked",i),this.isHoveringEvent&&this.$emit("event-clicked",{event:this.hoveredEvent,type:this.hoveredEventType}),this.panOnDateClick&&this.panToTimestamp(i)},handleMarkerClick(s){this.$emit("marker-clicked",s),this.panToTimestamp(s.timestamp)},handleLineMouseOver(s,e,t){this.hoveredCounts=Object.entries(this.countsByTimestamp[`${e.timestamp}`]).reduce((i,r)=>{const[n,a]=r;return[...i,{type:n,count:a}]},[]),this.hoveredEvent=e,this.isHoveringEvent=!0,this.$emit("event-mouseover",{eventData:e,eventType:t,hoveredCounts:this.hoveredCounts})},handleLineMouseOut(){this.isHoveringEvent=!1,this.hoveredCounts=[],this.$emit("event-mouseout")},handleBarMouseOver(s,e,t){s.offsetX<=this.minHoverZone||(this.hoveredEvent=e,this.hoveredEventType=t,this.isHoveringEvent=!0,this.$emit("event-mouseover",{eventData:e,eventType:t}))},handleBarMouseOut(){this.isHoveringEvent=!1,this.hoveredEvent=null,this.$emit("event-mouseout")},handleLabelMouseOver(s){N.selectAll(`.${V.lineGraphGroup}-${s}`).classed(`${V.lineGraphGroup}--highlighted`,!0),N.selectAll(`.${V.lineGraphGroup}-label`).classed(`${V.lineGraphGroup}-label--highlighted`,!0)},handleLabelMouseLeave(s){N.selectAll(`.${V.lineGraphGroup}-${s}`).classed(`${V.lineGraphGroup}--highlighted`,!1),N.selectAll(`.${V.lineGraphGroup}-label`).classed(`${V.lineGraphGroup}-label--highlighted`,!1)},handleZoom(s){const e=s.transform.rescaleX(this.initialTimeScale);this.timeScale.domain(e.domain()),this.updateCurrentTimeScaleDensity(),this.updateYScaleDomain();const t=s.transform.k/this.lastTransform.k;this.transformDiff={scale:t,translation:s.transform.x-this.lastTransform.x},this.lastTransform={...s.transform};for(const i in this.xAxes)this.rescaleAxis(i,e),this.translateTicksText(i);this.updateEventsBars(),this.updateLineGraphs(),this.updateBarChart(),this.updateLineGraphHoverZones(),this.repositionSelectedTimestampCursor(),this.updateMarkersPositions(),this.emitVisibleInterval(gt.zoom),this.curtains&&this.emitCurtainChange()},panToTimestamp(s){const e=this.tzStringToDate(s),t=this.timeScale(e),i=N.zoomTransform(this.svg.node()),r=i.x-t+this.timeline.offsetWidth/2;this.svg.transition().duration(this.panTransitionDuration).call(this.zoomBehavior.transform,N.zoomIdentity.translate(r,0).scale(i.k)),this.emitVisibleInterval(gt.autoPan)},emitCurtainChange(){const{startDate:s,endDate:e}=this.calculateDateRangeFromCurtains();this.$emit("curtain-range-change",{startDate:new Date(s).toISOString(),endDate:new Date(e).toISOString()})},calculateDateRangeFromCurtains(){const s=this.timeline.offsetWidth,e=this.timeScale.domain(),t=e[1].getTime()-e[0].getTime(),i=(this.leftCurtainWidth-this.curtainHandleWidth*2)/s*t,r=(this.rightCurtainWidth+this.curtainHandleWidth*2)/s*t,n=new Date(e[0].getTime()+i),a=new Date(e[1].getTime()-r);return{startDate:n,endDate:a}},handleDragStart(){this.isDraggingCurtain=!0},handleDragEnd(){this.isDraggingCurtain=!1},handleLeftDrag(s){s.sourceEvent.stopPropagation();const e=Math.min(s.x,this.timeline.offsetWidth-this.rightCurtainWidth);this.leftCurtainWidth=Math.max(0,e),this.svg.select(`.${V.curtain}--left`).attr("width",this.leftCurtainWidth),this.emitCurtainChange()},handleRightDrag(s){s.sourceEvent.stopPropagation();const e=this.timeline.offsetWidth,t=Math.min(this.timeline.offsetWidth-s.x,this.timeline.offsetWidth-this.leftCurtainWidth),i=e-t;this.rightCurtainWidth=Math.max(0,t),this.svg.select(`.${V.curtain}--right`).attr("width",this.rightCurtainWidth).attr("x",i),this.emitCurtainChange()},zoomToStartAndEndDates(){const s=this.startDate||this.oldestEvent.timestamp||this.oldestEvent.startDate,e=this.endDate||this.latestEvent.timestamp||this.latestEvent.endDate,t=this.tzStringToDate(s),i=this.tzStringToDate(e),r=this.timeline.offsetWidth,n=[t,i],a=[0,r];this.timeScale=N.scaleTime().domain(n).range(a),this.initialTimeScale=this.timeScale.copy(),this.updateCurrentTimeScaleDensity();for(const o in this.xAxes)this.rescaleAxis(o,this.timeScale),this.translateTicksText(o);this.updateEventsBars(),this.updateLineGraphs(),this.updateLineGraphHoverZones(),this.repositionSelectedTimestampCursor(),this.updateMarkersPositions()},rescaleAxis(s,e){const t=this.xAxes[s],i=this.getAxisTicksConfig(this.xAxesConfig[s]);t.scale(e).ticks(i.interval).tickFormat(i.formatFn).tickSizeOuter(0),this.svg.select(`.${V.xAxis}-${s}`).call(t)},translateTicksText(s){this.svg.select(`.${V.xAxis}-${s}`).selectAll(".tick text").each(function(){let e=N.select(this),t=e.node().getBBox();e.attr("x",t.height/2).attr("y",0).style("text-anchor","start")})},updateEventsBars(){const s=`.${V.eventGroup} > rect.${V.eventRect}`;this.svg.selectAll(s).attr("x",this.getEventRectX).attr("width",this.getEventRectWidth);const e=`.${V.eventGroup} > text.${V.eventRectText}`;this.svg.selectAll(e).attr("x",t=>this.getEventRectX(t)+this.textPadding).text(this.getEventText)},updateBarChart(){const s=Object.keys(this.barChartGroups).length;Object.keys(this.barChartGroups).forEach((e,t)=>{const i=d=>(this.getEventRectWidth(d)-this.barXPadding*2)/s,r=d=>this.yScale.range()[0]-this.yScale(d.count),n=d=>this.getEventRectX(d)+this.barXPadding+t*i(d),a=d=>this.yScale(d.count),o=`.${V.eventBarContainer}-${e}`,l=this.svg.selectAll(o),c=`.${V.barChartGroup} rect.${V.eventBarHoverZone}`;l.selectAll(c).attr("x",n).attr("width",i);const u=`.${V.barChartGroup} rect.${V.eventBar}`;l.selectAll(u).attr("x",n).attr("width",i).attr("y",a).attr("height",r);const h=`.${V.barChartGroup} rect.${V.eventBarCap}`;l.selectAll(h).attr("x",n).attr("width",i).attr("y",a)})},updateLineGraphs(){Object.entries(this.lineGraphGroups).forEach(([s])=>{const e=N.area().x(t=>this.timeScale(this.tzStringToDate(t.timestamp))).y0(this.timelineHeight).y1(t=>this.yScale(t.count)).curve(N.curveMonotoneX);this.svg.selectAll(`.${V.lineGraphPath}-${s}`).attr("d",t=>e(t))})},updateLineGraphHoverZones(){Object.keys(this.lineGraphGroups).forEach(s=>{const e=this;this.svg.selectAll(`.${V.lineGraphDot}-${s}`).each(function(t){N.select(this).attr("cx",e.timeScale(e.tzStringToDate(t.timestamp))).attr("cy",e.yScale(t.count))}),this.svg.selectAll(`.${V.lineGraphHoverZone}-${s}`).each(function(t){const i=e.timeScale(e.tzStringToDate(t.timestamp).getTime())-15;N.select(this).attr("x",i).attr("y",0).attr("width",30).attr("height",e.chartHeight)})})},getEventRectX(s){return this.timeScale(this.tzStringToDate(s.startDate||s.timestamp))},getEventRectWidth(s){if(!s)return 0;if(s.startDate&&s.endDate){const e=new Date(s.startDate),t=new Date(s.endDate),i=this.timeScale(t)-this.timeScale(e);return Math.max(i,this.rectMinWidth)}else{const e=1/(this.currentTimeScaleDensity*3600);return Math.max(e,this.rectMinWidth)}},getEventText(s){var i;const t=(this.getEventRectWidth(s)-this.textPadding)/this.characterWidth;return t<4?"":((i=s.text)==null?void 0:i.length)<=t?s.text:`${s.text.slice(0,t-3)}...`},initCurtains(){if(!this.curtains)return;const s=this.timeline.offsetWidth,e=this.timelineHeight;this.svg.append("rect").classed(`${V.curtain} ${V.curtain}--left`,!0).attr("width",this.leftCurtainWidth).attr("height",e+this.curtainHandleWidth*2).attr("y",-this.curtainHandleWidth).attr("x",-this.curtainHandleWidth).attr("fill","rgba(0, 0, 0, 0.5)").on("mouseenter",()=>this.isHoveringCurtain=!0).on("mouseleave",()=>this.isHoveringCurtain=!1).call(N.drag().on("start",this.handleDragStart).on("drag",this.handleLeftDrag).on("end",this.handleDragEnd)),this.svg.append("rect").classed(`${V.curtain} ${V.curtain}--right`,!0).attr("x",s-this.rightCurtainWidth+this.curtainHandleWidth*2).attr("y",-this.curtainHandleWidth).attr("width",this.rightCurtainWidth+this.curtainHandleWidth*2).attr("height",e+this.curtainHandleWidth*2).attr("fill","rgba(0, 0, 0, 0.5)").on("mouseenter",()=>this.isHoveringCurtain=!0).on("mouseleave",()=>this.isHoveringCurtain=!1).call(N.drag().on("start",this.handleDragStart).on("drag",this.handleRightDrag).on("end",this.handleDragEnd))},drawEventsGroups(){this.svg.selectAll(`g.${V.eventGroup}`).remove(),this.drawLineGraphEventsGroups(),this.drawBarEventsGroups(),this.drawBarChartEventsGroups()},drawLineGraphEventsGroups(){const s=this.combinedXAxesHeight,e=this.insertZerosAtInterval?this.filledGapsLineGraphGroups:this.lineGraphGroups;Object.entries(e).forEach(([t,i])=>{const r=this.svg.append("g").classed(`${V.lineGraphGroup} ${V.lineGraphGroup}-${t}`,!0).attr("transform",`translate(0,${s})`),{color:n,events:a}=i;this.drawLineGraph({events:a,gElement:r,color:n,type:t}),this.drawLineGraphHoverZones({events:a,gElement:r,color:n,type:t})}),Object.entries(this.lineGraphGroups).forEach(([t,i],r)=>{const{color:n,isLoading:a,label:o}=i,l=this.chartHeight-this.barChartHeight*(r+1),c=s+this.chartHeight-this.barChartHeight,u=this.svg.append("g").classed(`${V.lineGraphGroup}-label`,!0).attr("transform",`translate(0,${s})`).on("mouseover",()=>this.handleLabelMouseOver(t)).on("mouseleave",()=>this.handleLabelMouseLeave(t));this.drawProgressIndicator({type:t,color:n,isLoading:a,yPosition:c}),this.drawTextLabel({color:n,label:o,type:t,yPosition:l,gElement:u})})},drawLineGraph({events:s,gElement:e,color:t,type:i}){const r=N.area().x(a=>this.timeScale(this.tzStringToDate(a.timestamp))).y0(this.timelineHeight).y1(a=>this.yScale(a.count)).curve(N.curveMonotoneX),n=`clip-${i}`;e.append("defs").append("clipPath").attr("id",n).append("rect").attr("width",this.timeline.offsetWidth).attr("height",this.chartHeight),e.append("path").datum(s).classed(`${V.lineGraphPath}-${i}`,!0).attr("fill",`url(#${Qe.transparencyGradientLight}-${i})`).attr("stroke",t).attr("stroke-linejoin","round").attr("stroke-linecap","round").attr("stroke-width",1).attr("d",a=>r(a)).attr("clip-path",`url(#${n})`)},drawLineGraphHoverZones({events:s,gElement:e,color:t,type:i}){s.forEach(r=>{const n=`${r.timestamp}`;this.countsByTimestamp[n]={...this.countsByTimestamp[n]||{},[i]:r.count};const a=e.append("circle").classed(`${V.lineGraphDot} ${V.lineGraphDot}-${i}`,!0).attr("cx",this.timeScale(this.tzStringToDate(r.timestamp))).attr("cy",this.yScale(r.count)).attr("r",1.5).attr("fill",t).attr("stroke-width",0).datum(r);this.dotsByTimestamp[n]=[...this.dotsByTimestamp[n]||[],a],e.append("rect").classed(`${V.lineGraphHoverZone}-${i}`,!0).attr("x",this.timeScale(this.tzStringToDate(r.timestamp))-15).attr("y",0).attr("width",30).attr("height",this.chartHeight).attr("fill","transparent").datum(r).on("mouseover",o=>{this.handleLineMouseOver(o,r,i),this.dotsByTimestamp[n].forEach(l=>l.classed(`${V.lineGraphDot}--active`,!0))}).on("mouseout",()=>{this.handleLineMouseOut(),this.dotsByTimestamp[n].forEach(o=>o.classed(`${V.lineGraphDot}--active`,!1))})})},drawBarEventsGroups(){Object.entries(this.barGroups).forEach(([s,e],t)=>{const{color:i,bgColor:r,label:n,events:a,isLoading:o}=e,l=this.hasChart?this.chartHeight:0,c=t*this.barChartHeight+this.combinedXAxesHeight+l;this.drawProgressIndicator({yPosition:c,type:s,color:i,isLoading:o});const u=this.svg.append("g").attr("data-color",i).classed(V.eventGroup,!0).classed(`${V.eventGroup}-${s}`,!0);this.drawBackground({color:r||i,gElement:u,yPosition:c}),this.drawBars({events:a,color:i,gElement:u,yPosition:c,type:s}),this.drawTextLabel({color:i,label:n,type:s,gElement:u,yPosition:c})})},drawBarChartEventsGroups(){const s=this.combinedXAxesHeight,e=this.barChartGroups;Object.entries(e).forEach(([t,i],r)=>{const n=this.svg.append("g").classed(`${V.barChartGroup} ${V.barChartGroup}-${t}`,!0).attr("transform",`translate(0,${s})`),{color:a,events:o}=i;this.drawBarsChart({events:o,color:a,gElement:n,yOffset:s,type:t,index:r})})},drawProgressIndicator({yPosition:s,type:e,isLoading:t}){this.svg.append("rect").classed(`${V.loadingIndicator} ${V.loadingIndicator}-${e}`,!0).attr("x",0).attr("y",s).attr("width",this.timeline.offsetWidth/3).attr("height",this.barChartHeight).attr("fill",`url(#${Qe.loadingGradient}-${e})`).style("visibility",t?"visible":"hidden")},drawBackground({color:s,yPosition:e,gElement:t}){t.append("rect").attr("class",V.eventGroupBg).attr("x",0).attr("y",e).attr("width",this.timeline.offsetWidth).attr("height",this.barChartHeight).attr("fill",N.color(s).toString()).style("opacity",.1)},drawBars({events:s,gElement:e,yPosition:t,color:i,type:r}){const n=this;e.selectAll(V.eventRect).data(s).enter().append("rect").attr("class",a=>V.eventRect+(a.className?` ${a.className}`:"")).attr("x",this.getEventRectX).attr("y",t+this.barYPadding/2).attr("ry",1.5).attr("rx",1.5).attr("width",this.getEventRectWidth).attr("height",this.barChartHeight-this.barYPadding).attr("stroke-width",5).attr("cursor","pointer").attr("stroke","#0000").style("fill",a=>a.color||i).on("mouseover",function(a,o){N.select(this).classed(V.eventRectHovered,!0),n.handleBarMouseOver(a,o,r)}).on("mouseout",function(){N.select(this).classed(V.eventRectHovered,!1),n.handleBarMouseOut()}),e.selectAll(V.eventRectText).data(s.filter(a=>!!a.text)).enter().append("text").attr("class",V.eventRectText).attr("x",a=>this.getEventRectX(a)+this.textPadding).attr("y",t+this.barChartHeight/2).attr("dy","0.35em").style("text-anchor","start").style("font-size","12px").style("font-weight",600).style("stroke-linejoin","round").style("paint-order","stroke").style("pointer-events","none").style("fill",a=>this.getTextFillColor(a.color||i,.75)).text(this.getEventText)},drawBarsChart({events:s,gElement:e,color:t,yOffset:i,type:r,index:n}){const a=this,o=Object.keys(this.barChartGroups).length,l=f=>(this.getEventRectWidth(f)-this.barXPadding*2)/o,c=f=>this.yScale.range()[0]-this.yScale(f.count),u=f=>this.getEventRectX(f)+this.barXPadding+n*l(f),h=f=>this.yScale(f.count),d=e.selectAll(V.eventBarContainer).data(s).enter().append("g").attr("class",`${V.eventBarContainer} ${V.eventBarContainer}-${r}`);d.append("rect").attr("class",f=>V.eventBarHoverZone+(f.className?` ${f.className}`:"")).attr("x",u).attr("y",-i).attr("width",l).attr("height",this.yScale.range()[0]+i).attr("fill",f=>f.color||t).attr("fill-opacity",0),d.append("rect").attr("class",f=>V.eventBar+(f.className?` ${f.className}`:"")).attr("x",u).attr("y",h).attr("width",l).attr("height",c).attr("stroke-width",5).attr("cursor","pointer").attr("stroke","#0000").attr("fill",`url(#${Qe.transparencyGradient}-${r})`),d.append("rect").attr("class",f=>V.eventBarCap+(f.className?` ${f.className}`:"")).attr("x",u).attr("y",h).attr("width",l).attr("height",2).attr("stroke-width",0).style("fill",f=>f.color||t),d.on("mouseover",function(f,g){const m=N.select(this);a.onBarChartBarMouseOver(m,t),a.handleBarMouseOver(f,g,r)}).on("mouseout",function(){const f=N.select(this);a.onBarChartBarMouseOut(f,r),a.handleBarMouseOut()}).on("click",function(){e.selectAll(`.${V.eventBarContainerSelected}`).classed(V.eventBarContainerSelected,!1),N.select(this).classed(V.eventBarContainerSelected,!0)})},onBarChartBarMouseOver(s,e){s.classed(V.eventBarContainerHovered,!0),s.selectAll(`.${V.eventBarHoverZone}`).attr("fill-opacity",.2);const i=s.selectAll(`.${V.eventBar}`);i.attr("fill",e),i.attr("fill-opacity",.5)},onBarChartBarMouseOut(s,e){s.classed(V.eventBarContainerHovered,!1),s.selectAll(`.${V.eventBarHoverZone}`).attr("fill-opacity",0);const i=s.selectAll(`.${V.eventBar}`);i.attr("fill",`url(#${Qe.transparencyGradient}-${e})`),i.attr("fill-opacity",1)},drawTextLabel({gElement:s,yPosition:e,color:t,label:i,type:r}){if(!this.showLabels)return;const n={x:-5,y:e,w:this.labelRectWidth,h:this.barChartHeight,radius:3},a=s.append("g").attr("class",`${V.labelGroup} ${V.labelGroup}-${r}`).style("cursor","pointer").on("click",()=>this.toggleGroupVisibility(r));a.append("rect").attr("class",V.labelBg).attr("data-color",t).attr("x",n.x).attr("y",n.y).attr("width",n.w).attr("height",n.h).attr("rx",n.radius).attr("ry",n.radius).style("fill",this.dark?"#131a29":"white"),a.append("rect").attr("class",V.labelBgFill).attr("data-color",t).attr("x",n.x).attr("y",n.y).attr("width",n.w).attr("height",n.h).attr("rx",n.radius).attr("ry",n.radius).style("fill",this.getLabelBackgroundColor(t)).style("stroke",this.getTextFillColor(t)).style("stroke-width",.25),a.append("text").attr("class",V.labelText).attr("data-color",t).attr("x",5).attr("y",e+this.barChartHeight/2).attr("dy","0.35em").style("text-anchor","start").style("font-size","12px").style("font-weight",500).style("stroke-linejoin","round").style("paint-order","stroke").style("fill",this.getTextFillColor(t)).text(i)},getTextFillColor(s,e=0){var t,i;return(this.dark?(t=N.color(s))==null?void 0:t.brighter(1.5+e):(i=N.color(s))==null?void 0:i.darker(2+e)).toString()},getLabelBackgroundColor(s){let e=N.color(s);return e.opacity=this.dark?.2:.5,e.toString()},getCurrentGroupVisibility(s){var i;const e=this.groupsVisibility[s];if(e!==void 0)return e;const t=(i=this.eventsGroups[s])==null?void 0:i.isHidden;return t!==void 0?!t:!0},toggleGroupVisibility(s){this.groupsVisibility={...this.groupsVisibility,[s]:!this.getCurrentGroupVisibility(s)}},getExternalLabelStyles(s){const e=this.eventsGroups[s].color;return{background:this.getLabelBackgroundColor(e),color:this.getTextFillColor(e)}},getExternalLabelWrapperStyles(s){const e=this.eventsGroups[s].color;return{borderColor:this.getTextFillColor(e)}},getMarkerClass(s){var e;return{"marker--hidden":(e=this.markersPositions[s==null?void 0:s.id])==null?void 0:e.isHidden}},getMarkerContainerStyle(s){var e;return{top:"0",left:`${(e=this.markersPositions[s.id])==null?void 0:e.position}px`}},getMarkerLabelStyle(s){return{background:s.color,color:s.textColor||""}},getMarkerLineStyle(s){return{background:s.color,height:`${this.timelineHeight+24}px`}},tzStringToDate(s){return Ve(s).add(this.utcOffset,"minutes").toDate()},dateToTzString(s){const e=new Date(s).getTimezoneOffset();return Ve(s).add(e,"minutes").utcOffset(this.utcOffset,!0).format()},getCurrentTimeBounds(){const s=this.timeScale.domain();return{startDate:s[0],endDate:s[1]}},getFormattedTimestamp(s){return Ve.parseZone(s).format("YYYY-MM-DDTHH:mm:ss")},fillTimeGaps(s){if(s.length<=1)return s;const e=this.insertZerosAtInterval,t=n=>n.clone().add(1,e),i=n=>n.clone().subtract(1,e);let r=[];for(let n=0;n<s.length;n++){const a=s[n];if(r.push(a),n===s.length-1)break;const o=s[n+1],l=Ve(a.timestamp),c=Ve(o.timestamp);if(c.diff(l,e)>1){const u=t(l).toISOString(),h=i(c).toISOString();r.push({timestamp:u,count:0}),u!==h&&r.push({timestamp:h,count:0})}}if(this.flattenLineGraphEnds){const n=Ve(s[0].timestamp),a=Ve(s[s.length-1].timestamp),o=i(n).toISOString(),l=t(a).toISOString();r=[{timestamp:o,count:0},...r,{timestamp:l,count:0}]}return r},fillEvents(s){return this.placeholderLineChartGroup.map(e=>s.find(i=>i.timestamp===e.timestamp)||e)}}}),jh="";var Oh=function(){var e=this,t=e._self._c;return t("div",{staticClass:"e-relative e-timeline e-border e-rounded",class:e.classes.wrapper},[t("div",{staticClass:"e-timeline__background e-w-full e-h-full e-absolute e-top-0 e-rounded",class:e.classes.background}),e._l(e.sortedMarkers,function(i){return t("div",{key:i.id,staticClass:"e-absolute marker",class:e.getMarkerClass(i),style:e.getMarkerContainerStyle(i),attrs:{"data-id":i.id},on:{click:function(r){return e.handleMarkerClick(i)}}},[e._t(`marker.${i.id}`,function(){return[t("div",{staticClass:"marker-label e-absolute"},[t("div",{staticClass:"marker-label-text",style:e.getMarkerLabelStyle(i)},[e._v(" "+e._s(i.label)+" ")])]),t("div",{staticClass:"marker-line e-absolute e-pointer-events-none",style:e.getMarkerLineStyle(i)})]},{marker:i})],2)}),e.autoResize?t("div",{directives:[{name:"resize-observer",rawName:"v-resize-observer",value:e.onResize,expression:"onResize"}],ref:"timelineContainer",staticClass:"e-timeline__svg-container e-relative e-h-13 e-rounded e-select-none e-overflow-x-hidden"}):t("div",{ref:"timelineContainer",staticClass:"e-timeline__svg-container e-relative e-h-13 e-rounded e-select-none e-overflow-x-hidden"}),t("div",{directives:[{name:"show",rawName:"v-show",value:e.isHoveringTimeline&&!e.isInteractingWithCurtain,expression:"isHoveringTimeline && !isInteractingWithCurtain"}],ref:"cursor",staticClass:"e-timeline__cursor e-absolute e-bg-green-600 e-w-px e-h-full e-top-0 e-pointer-events-none"}),t("div",{staticClass:"external-labels-container e-flex"},e._l(e.hiddenGroupsLabels,function(i){return t("div",{key:i,staticClass:"external-label",class:e.classes.background,style:e.getExternalLabelWrapperStyles(i),on:{click:function(r){return e.toggleGroupVisibility(i)}}},[t("div",{staticClass:"external-label__content",style:e.getExternalLabelStyles(i)},[e._v(" "+e._s(i)+" ")])])}),0),t("div",{ref:"tooltip",staticClass:"e-absolute",style:e.eventTooltipStyle},[e._t("tooltip",function(){return[t("div",{directives:[{name:"show",rawName:"v-show",value:e.isHoveringTimeline&&!e.isHoveringEvent&&!e.isInteractingWithCurtain&&!e.cursorTimestamp,expression:`
|
|
27
27
|
isHoveringTimeline &&
|
|
28
28
|
!isHoveringEvent &&
|
|
29
29
|
!isInteractingWithCurtain &&
|