@maveio/components 0.0.159 → 0.0.161

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.
@@ -1,11 +1,11 @@
1
- 'use strict';var chunkBVMU4ZXD_cjs=require('./chunk-BVMU4ZXD.cjs'),chunkQ22T22LT_cjs=require('./chunk-Q22T22LT.cjs'),chunkDITZCOYN_cjs=require('./chunk-DITZCOYN.cjs'),chunkKVMGCTLR_cjs=require('./chunk-KVMGCTLR.cjs'),chunkSDKTBB4N_cjs=require('./chunk-SDKTBB4N.cjs'),chunkYT56YDUY_cjs=require('./chunk-YT56YDUY.cjs'),chunkEOHKHSQ3_cjs=require('./chunk-EOHKHSQ3.cjs'),chunkFUBUUA7Y_cjs=require('./chunk-FUBUUA7Y.cjs'),chunk5NSCV6C2_cjs=require('./chunk-5NSCV6C2.cjs'),chunk5STN56TL_cjs=require('./chunk-5STN56TL.cjs'),chunkJHSFSCC2_cjs=require('./chunk-JHSFSCC2.cjs');function Ah(s){return s?.map(o0).join(" ")}function bh(s){return s?.split(/\s+/).map(l0)}function o0(s){if(s){let{id:e,width:t,height:i}=s;return [e,t,i].filter(r=>r!=null).join(":")}}function l0(s){if(s){let[e,t,i]=s.split(":");return {id:e,width:+t,height:+i}}}function _h(s){return s?.map(d0).join(" ")}function Ih(s){return s?.split(/\s+/).map(c0)}function d0(s){if(s){let{id:e,kind:t,language:i,label:r}=s;return [e,t,i,r].filter(n=>n!=null).join(":")}}function c0(s){if(s){let[e,t,i,r]=s.split(":");return {id:e,kind:t,language:i,label:r}}}function gs(s){return typeof s=="number"&&!Number.isNaN(s)&&Number.isFinite(s)}var $n=s=>new Promise(e=>setTimeout(e,s));var Lh=[{singular:"hour",plural:"hours"},{singular:"minute",plural:"minutes"},{singular:"second",plural:"seconds"}],u0=(s,e)=>{let t=s===1?Lh[e].singular:Lh[e].plural;return `${s} ${t}`},Bi=s=>{if(!gs(s))return "";let e=Math.abs(s),t=e!==s,i=new Date(0,0,0,0,0,e,0);return `${[i.getHours(),i.getMinutes(),i.getSeconds()].map((o,l)=>o&&u0(o,l)).filter(o=>o).join(", ")}${t?" remaining":""}`};function Ft(s,e){let t=false;s<0&&(t=true,s=0-s),s=s<0?0:s;let i=Math.floor(s%60),r=Math.floor(s/60%60),n=Math.floor(s/3600),a=Math.floor(e/60%60),o=Math.floor(e/3600);return (isNaN(s)||s===1/0)&&(n=r=i="0"),n=n>0||o>0?n+":":"",r=((n||a>=10)&&r<10?"0"+r:r)+":",i=i<10?"0"+i:i,(t?"-":"")+n+r+i}var xh=(s,e,t)=>{if(!e.has(s))throw TypeError("Cannot "+t)},bi=(s,e,t)=>(xh(s,e,"read from private field"),t?t.call(s):e.get(s)),f0=(s,e,t)=>{if(e.has(s))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(s):e.set(s,t);},Gn=(s,e,t,i)=>(xh(s,e,"write to private field"),e.set(s,t),t),lt;function m0(s){return `
1
+ 'use strict';var chunkBVMU4ZXD_cjs=require('./chunk-BVMU4ZXD.cjs'),chunkQ22T22LT_cjs=require('./chunk-Q22T22LT.cjs'),chunkDITZCOYN_cjs=require('./chunk-DITZCOYN.cjs'),chunkKVMGCTLR_cjs=require('./chunk-KVMGCTLR.cjs'),chunkSDKTBB4N_cjs=require('./chunk-SDKTBB4N.cjs'),chunkYT56YDUY_cjs=require('./chunk-YT56YDUY.cjs'),chunkEOHKHSQ3_cjs=require('./chunk-EOHKHSQ3.cjs'),chunkFUBUUA7Y_cjs=require('./chunk-FUBUUA7Y.cjs'),chunk5NSCV6C2_cjs=require('./chunk-5NSCV6C2.cjs'),chunk5STN56TL_cjs=require('./chunk-5STN56TL.cjs'),chunkJHSFSCC2_cjs=require('./chunk-JHSFSCC2.cjs');function bh(s){return s?.map(l0).join(" ")}function _h(s){return s?.split(/\s+/).map(d0)}function l0(s){if(s){let{id:e,width:t,height:i}=s;return [e,t,i].filter(r=>r!=null).join(":")}}function d0(s){if(s){let[e,t,i]=s.split(":");return {id:e,width:+t,height:+i}}}function Ih(s){return s?.map(c0).join(" ")}function Lh(s){return s?.split(/\s+/).map(u0)}function c0(s){if(s){let{id:e,kind:t,language:i,label:r}=s;return [e,t,i,r].filter(n=>n!=null).join(":")}}function u0(s){if(s){let[e,t,i,r]=s.split(":");return {id:e,kind:t,language:i,label:r}}}function gs(s){return typeof s=="number"&&!Number.isNaN(s)&&Number.isFinite(s)}var $n=s=>new Promise(e=>setTimeout(e,s));var xh=[{singular:"hour",plural:"hours"},{singular:"minute",plural:"minutes"},{singular:"second",plural:"seconds"}],h0=(s,e)=>{let t=s===1?xh[e].singular:xh[e].plural;return `${s} ${t}`},Bi=s=>{if(!gs(s))return "";let e=Math.abs(s),t=e!==s,i=new Date(0,0,0,0,0,e,0);return `${[i.getHours(),i.getMinutes(),i.getSeconds()].map((o,l)=>o&&h0(o,l)).filter(o=>o).join(", ")}${t?" remaining":""}`};function Ft(s,e){let t=false;s<0&&(t=true,s=0-s),s=s<0?0:s;let i=Math.floor(s%60),r=Math.floor(s/60%60),n=Math.floor(s/3600),a=Math.floor(e/60%60),o=Math.floor(e/3600);return (isNaN(s)||s===1/0)&&(n=r=i="0"),n=n>0||o>0?n+":":"",r=((n||a>=10)&&r<10?"0"+r:r)+":",i=i<10?"0"+i:i,(t?"-":"")+n+r+i}var Rh=(s,e,t)=>{if(!e.has(s))throw TypeError("Cannot "+t)},bi=(s,e,t)=>(Rh(s,e,"read from private field"),t?t.call(s):e.get(s)),m0=(s,e,t)=>{if(e.has(s))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(s):e.set(s,t);},Gn=(s,e,t,i)=>(Rh(s,e,"write to private field"),e.set(s,t),t),lt;function g0(s){return `
2
2
  <style>
3
3
  :host {
4
4
  display: var(--media-control-display, var(--media-gesture-receiver-display, inline-block));
5
5
  box-sizing: border-box;
6
6
  }
7
7
  </style>
8
- `}var ps=class extends chunkDITZCOYN_cjs.o.HTMLElement{constructor(){if(super(),f0(this,lt,void 0),!this.shadowRoot){this.attachShadow(this.constructor.shadowRootOptions);let e=chunkDITZCOYN_cjs.s(this.attributes);this.shadowRoot.innerHTML=this.constructor.getTemplateHTML(e);}}static get observedAttributes(){return [chunkDITZCOYN_cjs.b.MEDIA_CONTROLLER,chunkDITZCOYN_cjs.d.MEDIA_PAUSED]}attributeChangedCallback(e,t,i){var r,n,a,o,l;e===chunkDITZCOYN_cjs.b.MEDIA_CONTROLLER&&(t&&((n=(r=bi(this,lt))==null?void 0:r.unassociateElement)==null||n.call(r,this),Gn(this,lt,null)),i&&this.isConnected&&(Gn(this,lt,(a=this.getRootNode())==null?void 0:a.getElementById(i)),(l=(o=bi(this,lt))==null?void 0:o.associateElement)==null||l.call(o,this)));}connectedCallback(){var e,t,i,r;this.tabIndex=-1,this.setAttribute("aria-hidden","true"),Gn(this,lt,g0(this)),this.getAttribute(chunkDITZCOYN_cjs.b.MEDIA_CONTROLLER)&&((t=(e=bi(this,lt))==null?void 0:e.associateElement)==null||t.call(e,this)),(i=bi(this,lt))==null||i.addEventListener("pointerdown",this),(r=bi(this,lt))==null||r.addEventListener("click",this);}disconnectedCallback(){var e,t,i,r;this.getAttribute(chunkDITZCOYN_cjs.b.MEDIA_CONTROLLER)&&((t=(e=bi(this,lt))==null?void 0:e.unassociateElement)==null||t.call(e,this)),(i=bi(this,lt))==null||i.removeEventListener("pointerdown",this),(r=bi(this,lt))==null||r.removeEventListener("click",this),Gn(this,lt,null);}handleEvent(e){var t;let i=(t=e.composedPath())==null?void 0:t[0];if(["video","media-controller"].includes(i?.localName)){if(e.type==="pointerdown")this._pointerType=e.pointerType;else if(e.type==="click"){let{clientX:n,clientY:a}=e,{left:o,top:l,width:d,height:c}=this.getBoundingClientRect(),u=n-o,h=a-l;if(u<0||h<0||u>d||h>c||d===0&&c===0)return;let f=this._pointerType||"mouse";if(this._pointerType=void 0,f===chunkDITZCOYN_cjs.i.TOUCH){this.handleTap(e);return}else if(f===chunkDITZCOYN_cjs.i.MOUSE||f===chunkDITZCOYN_cjs.i.PEN){this.handleMouseClick(e);return}}}}get mediaPaused(){return chunkDITZCOYN_cjs.F(this,chunkDITZCOYN_cjs.d.MEDIA_PAUSED)}set mediaPaused(e){chunkDITZCOYN_cjs.G(this,chunkDITZCOYN_cjs.d.MEDIA_PAUSED,e);}handleTap(e){}handleMouseClick(e){let t=this.mediaPaused?chunkDITZCOYN_cjs.a.MEDIA_PLAY_REQUEST:chunkDITZCOYN_cjs.a.MEDIA_PAUSE_REQUEST;this.dispatchEvent(new chunkDITZCOYN_cjs.o.CustomEvent(t,{composed:true,bubbles:true}));}};lt=new WeakMap;ps.shadowRootOptions={mode:"open"};ps.getTemplateHTML=m0;function g0(s){var e;let t=s.getAttribute(chunkDITZCOYN_cjs.b.MEDIA_CONTROLLER);return t?(e=s.getRootNode())==null?void 0:e.getElementById(t):chunkDITZCOYN_cjs.x(s,"media-controller")}chunkDITZCOYN_cjs.o.customElements.get("media-gesture-receiver")||chunkDITZCOYN_cjs.o.customElements.define("media-gesture-receiver",ps);var Hn=ps;var Ll=(s,e,t)=>{if(!e.has(s))throw TypeError("Cannot "+t)},Et=(s,e,t)=>(Ll(s,e,"read from private field"),t?t.call(s):e.get(s)),pt=(s,e,t)=>{if(e.has(s))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(s):e.set(s,t);},$i=(s,e,t,i)=>(Ll(s,e,"write to private field"),e.set(s,t),t),Lt=(s,e,t)=>(Ll(s,e,"access private method"),t),Wn,Es,hr,vs,Kn,bl,Rh,ur,Vn,_l,kh,Il,Dh,fr,Yn,qn,xl,Ts,mr,X={AUDIO:"audio",AUTOHIDE:"autohide",BREAKPOINTS:"breakpoints",GESTURES_DISABLED:"gesturesdisabled",KEYBOARD_CONTROL:"keyboardcontrol",NO_AUTOHIDE:"noautohide",USER_INACTIVE:"userinactive",AUTOHIDE_OVER_CONTROLS:"autohideovercontrols"};function p0(s){return `
8
+ `}var ps=class extends chunkDITZCOYN_cjs.o.HTMLElement{constructor(){if(super(),m0(this,lt,void 0),!this.shadowRoot){this.attachShadow(this.constructor.shadowRootOptions);let e=chunkDITZCOYN_cjs.s(this.attributes);this.shadowRoot.innerHTML=this.constructor.getTemplateHTML(e);}}static get observedAttributes(){return [chunkDITZCOYN_cjs.b.MEDIA_CONTROLLER,chunkDITZCOYN_cjs.d.MEDIA_PAUSED]}attributeChangedCallback(e,t,i){var r,n,a,o,l;e===chunkDITZCOYN_cjs.b.MEDIA_CONTROLLER&&(t&&((n=(r=bi(this,lt))==null?void 0:r.unassociateElement)==null||n.call(r,this),Gn(this,lt,null)),i&&this.isConnected&&(Gn(this,lt,(a=this.getRootNode())==null?void 0:a.getElementById(i)),(l=(o=bi(this,lt))==null?void 0:o.associateElement)==null||l.call(o,this)));}connectedCallback(){var e,t,i,r;this.tabIndex=-1,this.setAttribute("aria-hidden","true"),Gn(this,lt,p0(this)),this.getAttribute(chunkDITZCOYN_cjs.b.MEDIA_CONTROLLER)&&((t=(e=bi(this,lt))==null?void 0:e.associateElement)==null||t.call(e,this)),(i=bi(this,lt))==null||i.addEventListener("pointerdown",this),(r=bi(this,lt))==null||r.addEventListener("click",this);}disconnectedCallback(){var e,t,i,r;this.getAttribute(chunkDITZCOYN_cjs.b.MEDIA_CONTROLLER)&&((t=(e=bi(this,lt))==null?void 0:e.unassociateElement)==null||t.call(e,this)),(i=bi(this,lt))==null||i.removeEventListener("pointerdown",this),(r=bi(this,lt))==null||r.removeEventListener("click",this),Gn(this,lt,null);}handleEvent(e){var t;let i=(t=e.composedPath())==null?void 0:t[0];if(["video","media-controller"].includes(i?.localName)){if(e.type==="pointerdown")this._pointerType=e.pointerType;else if(e.type==="click"){let{clientX:n,clientY:a}=e,{left:o,top:l,width:d,height:c}=this.getBoundingClientRect(),u=n-o,h=a-l;if(u<0||h<0||u>d||h>c||d===0&&c===0)return;let f=this._pointerType||"mouse";if(this._pointerType=void 0,f===chunkDITZCOYN_cjs.i.TOUCH){this.handleTap(e);return}else if(f===chunkDITZCOYN_cjs.i.MOUSE||f===chunkDITZCOYN_cjs.i.PEN){this.handleMouseClick(e);return}}}}get mediaPaused(){return chunkDITZCOYN_cjs.F(this,chunkDITZCOYN_cjs.d.MEDIA_PAUSED)}set mediaPaused(e){chunkDITZCOYN_cjs.G(this,chunkDITZCOYN_cjs.d.MEDIA_PAUSED,e);}handleTap(e){}handleMouseClick(e){let t=this.mediaPaused?chunkDITZCOYN_cjs.a.MEDIA_PLAY_REQUEST:chunkDITZCOYN_cjs.a.MEDIA_PAUSE_REQUEST;this.dispatchEvent(new chunkDITZCOYN_cjs.o.CustomEvent(t,{composed:true,bubbles:true}));}};lt=new WeakMap;ps.shadowRootOptions={mode:"open"};ps.getTemplateHTML=g0;function p0(s){var e;let t=s.getAttribute(chunkDITZCOYN_cjs.b.MEDIA_CONTROLLER);return t?(e=s.getRootNode())==null?void 0:e.getElementById(t):chunkDITZCOYN_cjs.x(s,"media-controller")}chunkDITZCOYN_cjs.o.customElements.get("media-gesture-receiver")||chunkDITZCOYN_cjs.o.customElements.define("media-gesture-receiver",ps);var Hn=ps;var Ll=(s,e,t)=>{if(!e.has(s))throw TypeError("Cannot "+t)},Et=(s,e,t)=>(Ll(s,e,"read from private field"),t?t.call(s):e.get(s)),pt=(s,e,t)=>{if(e.has(s))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(s):e.set(s,t);},$i=(s,e,t,i)=>(Ll(s,e,"write to private field"),e.set(s,t),t),Lt=(s,e,t)=>(Ll(s,e,"access private method"),t),Wn,Es,hr,vs,Kn,bl,kh,ur,Vn,_l,Dh,Il,Ch,fr,Yn,qn,xl,Ts,mr,X={AUDIO:"audio",AUTOHIDE:"autohide",BREAKPOINTS:"breakpoints",GESTURES_DISABLED:"gesturesdisabled",KEYBOARD_CONTROL:"keyboardcontrol",NO_AUTOHIDE:"noautohide",USER_INACTIVE:"userinactive",AUTOHIDE_OVER_CONTROLS:"autohideovercontrols"};function E0(s){return `
9
9
  <style>
10
10
 
11
11
  :host([${chunkDITZCOYN_cjs.d.MEDIA_IS_FULLSCREEN}]) ::slotted([slot=media]) {
@@ -156,10 +156,10 @@
156
156
  <slot part="bottom chrome"></slot>
157
157
  </span>
158
158
  <slot name="dialog" part="layer dialog-layer"></slot>
159
- `}var E0=Object.values(chunkDITZCOYN_cjs.d),v0="sm:384 md:576 lg:768 xl:960";function T0(s){Ch(s.target,s.contentRect.width);}function Ch(s,e){var t;if(!s.isConnected)return;let i=(t=s.getAttribute(X.BREAKPOINTS))!=null?t:v0,r=y0(i),n=S0(r,e),a=false;if(Object.keys(r).forEach(o=>{if(n.includes(o)){s.hasAttribute(`breakpoint${o}`)||(s.setAttribute(`breakpoint${o}`,""),a=true);return}s.hasAttribute(`breakpoint${o}`)&&(s.removeAttribute(`breakpoint${o}`),a=true);}),a){let o=new CustomEvent(chunkDITZCOYN_cjs.e.BREAKPOINTS_CHANGE,{detail:n});s.dispatchEvent(o);}s.breakpointsComputed||(s.breakpointsComputed=true,s.dispatchEvent(new CustomEvent(chunkDITZCOYN_cjs.e.BREAKPOINTS_COMPUTED,{bubbles:true,composed:true})));}function y0(s){let e=s.split(/\s+/);return Object.fromEntries(e.map(t=>t.split(":")))}function S0(s,e){return Object.keys(s).filter(t=>e>=parseInt(s[t]))}var Gi=class extends chunkDITZCOYN_cjs.o.HTMLElement{constructor(){if(super(),pt(this,bl),pt(this,_l),pt(this,Il),pt(this,fr),pt(this,qn),pt(this,Ts),pt(this,Wn,0),pt(this,Es,null),pt(this,hr,null),pt(this,vs,void 0),this.breakpointsComputed=false,pt(this,Kn,new MutationObserver(Lt(this,bl,Rh).bind(this))),pt(this,ur,false),pt(this,Vn,t=>{Et(this,ur)||(setTimeout(()=>{T0(t),$i(this,ur,false);},0),$i(this,ur,true));}),!this.shadowRoot){this.attachShadow(this.constructor.shadowRootOptions);let t=chunkDITZCOYN_cjs.s(this.attributes),i=this.constructor.getTemplateHTML(t);this.shadowRoot.setHTMLUnsafe?this.shadowRoot.setHTMLUnsafe(i):this.shadowRoot.innerHTML=i;}let e=this.querySelector(":scope > slot[slot=media]");e&&e.addEventListener("slotchange",()=>{if(!e.assignedElements({flatten:true}).length){Et(this,Es)&&this.mediaUnsetCallback(Et(this,Es));return}this.handleMediaUpdated(this.media);});}static get observedAttributes(){return [X.AUTOHIDE,X.GESTURES_DISABLED].concat(E0).filter(e=>![chunkDITZCOYN_cjs.d.MEDIA_RENDITION_LIST,chunkDITZCOYN_cjs.d.MEDIA_AUDIO_TRACK_LIST,chunkDITZCOYN_cjs.d.MEDIA_CHAPTERS_CUES,chunkDITZCOYN_cjs.d.MEDIA_WIDTH,chunkDITZCOYN_cjs.d.MEDIA_HEIGHT,chunkDITZCOYN_cjs.d.MEDIA_ERROR,chunkDITZCOYN_cjs.d.MEDIA_ERROR_MESSAGE].includes(e))}attributeChangedCallback(e,t,i){e.toLowerCase()==X.AUTOHIDE&&(this.autohide=i);}get media(){let e=this.querySelector(":scope > [slot=media]");return e?.nodeName=="SLOT"&&(e=e.assignedElements({flatten:true})[0]),e}async handleMediaUpdated(e){e&&($i(this,Es,e),e.localName.includes("-")&&await chunkDITZCOYN_cjs.o.customElements.whenDefined(e.localName),this.mediaSetCallback(e));}connectedCallback(){var e;Et(this,Kn).observe(this,{childList:true,subtree:true}),chunkDITZCOYN_cjs.q(this,Et(this,Vn));let i=this.getAttribute(X.AUDIO)!=null?chunkDITZCOYN_cjs.n("audio player"):chunkDITZCOYN_cjs.n("video player");this.setAttribute("role","region"),this.setAttribute("aria-label",i),this.handleMediaUpdated(this.media),this.setAttribute(X.USER_INACTIVE,""),Ch(this,this.getBoundingClientRect().width),this.addEventListener("pointerdown",this),this.addEventListener("pointermove",this),this.addEventListener("pointerup",this),this.addEventListener("mouseleave",this),this.addEventListener("keyup",this),(e=chunkDITZCOYN_cjs.o.window)==null||e.addEventListener("mouseup",this);}disconnectedCallback(){var e;Et(this,Kn).disconnect(),chunkDITZCOYN_cjs.r(this,Et(this,Vn)),this.media&&this.mediaUnsetCallback(this.media),(e=chunkDITZCOYN_cjs.o.window)==null||e.removeEventListener("mouseup",this);}mediaSetCallback(e){}mediaUnsetCallback(e){$i(this,Es,null);}handleEvent(e){switch(e.type){case "pointerdown":$i(this,Wn,e.timeStamp);break;case "pointermove":Lt(this,_l,kh).call(this,e);break;case "pointerup":Lt(this,Il,Dh).call(this,e);break;case "mouseleave":Lt(this,fr,Yn).call(this);break;case "mouseup":this.removeAttribute(X.KEYBOARD_CONTROL);break;case "keyup":Lt(this,Ts,mr).call(this),this.setAttribute(X.KEYBOARD_CONTROL,"");break}}set autohide(e){let t=Number(e);$i(this,vs,isNaN(t)?0:t);}get autohide(){return (Et(this,vs)===void 0?2:Et(this,vs)).toString()}get breakpoints(){return chunkDITZCOYN_cjs.H(this,X.BREAKPOINTS)}set breakpoints(e){chunkDITZCOYN_cjs.I(this,X.BREAKPOINTS,e);}get audio(){return chunkDITZCOYN_cjs.F(this,X.AUDIO)}set audio(e){chunkDITZCOYN_cjs.G(this,X.AUDIO,e);}get gesturesDisabled(){return chunkDITZCOYN_cjs.F(this,X.GESTURES_DISABLED)}set gesturesDisabled(e){chunkDITZCOYN_cjs.G(this,X.GESTURES_DISABLED,e);}get keyboardControl(){return chunkDITZCOYN_cjs.F(this,X.KEYBOARD_CONTROL)}set keyboardControl(e){chunkDITZCOYN_cjs.G(this,X.KEYBOARD_CONTROL,e);}get noAutohide(){return chunkDITZCOYN_cjs.F(this,X.NO_AUTOHIDE)}set noAutohide(e){chunkDITZCOYN_cjs.G(this,X.NO_AUTOHIDE,e);}get autohideOverControls(){return chunkDITZCOYN_cjs.F(this,X.AUTOHIDE_OVER_CONTROLS)}set autohideOverControls(e){chunkDITZCOYN_cjs.G(this,X.AUTOHIDE_OVER_CONTROLS,e);}get userInteractive(){return chunkDITZCOYN_cjs.F(this,X.USER_INACTIVE)}set userInteractive(e){chunkDITZCOYN_cjs.G(this,X.USER_INACTIVE,e);}};Wn=new WeakMap;Es=new WeakMap;hr=new WeakMap;vs=new WeakMap;Kn=new WeakMap;bl=new WeakSet;Rh=function(s){let e=this.media;for(let t of s){if(t.type!=="childList")continue;let i=t.removedNodes;for(let r of i){if(r.slot!="media"||t.target!=this)continue;let n=t.previousSibling&&t.previousSibling.previousElementSibling;if(!n||!e)this.mediaUnsetCallback(r);else {let a=n.slot!=="media";for(;(n=n.previousSibling)!==null;)n.slot=="media"&&(a=false);a&&this.mediaUnsetCallback(r);}}if(e)for(let r of t.addedNodes)r===e&&this.handleMediaUpdated(e);}};ur=new WeakMap;Vn=new WeakMap;_l=new WeakSet;kh=function(s){if(s.pointerType!=="mouse"&&s.timeStamp-Et(this,Wn)<250)return;Lt(this,qn,xl).call(this),clearTimeout(Et(this,hr));let e=this.hasAttribute(X.AUTOHIDE_OVER_CONTROLS);([this,this.media].includes(s.target)||e)&&Lt(this,Ts,mr).call(this);};Il=new WeakSet;Dh=function(s){if(s.pointerType==="touch"){let e=!this.hasAttribute(X.USER_INACTIVE);[this,this.media].includes(s.target)&&e?Lt(this,fr,Yn).call(this):Lt(this,Ts,mr).call(this);}else s.composedPath().some(e=>["media-play-button","media-fullscreen-button"].includes(e?.localName))&&Lt(this,Ts,mr).call(this);};fr=new WeakSet;Yn=function(){if(Et(this,vs)<0||this.hasAttribute(X.USER_INACTIVE))return;this.setAttribute(X.USER_INACTIVE,"");let s=new chunkDITZCOYN_cjs.o.CustomEvent(chunkDITZCOYN_cjs.e.USER_INACTIVE_CHANGE,{composed:true,bubbles:true,detail:true});this.dispatchEvent(s);};qn=new WeakSet;xl=function(){if(!this.hasAttribute(X.USER_INACTIVE))return;this.removeAttribute(X.USER_INACTIVE);let s=new chunkDITZCOYN_cjs.o.CustomEvent(chunkDITZCOYN_cjs.e.USER_INACTIVE_CHANGE,{composed:true,bubbles:true,detail:false});this.dispatchEvent(s);};Ts=new WeakSet;mr=function(){Lt(this,qn,xl).call(this),clearTimeout(Et(this,hr));let s=parseInt(this.autohide);s<0||$i(this,hr,setTimeout(()=>{Lt(this,fr,Yn).call(this);},s*1e3));};Gi.shadowRootOptions={mode:"open"};Gi.getTemplateHTML=p0;chunkDITZCOYN_cjs.o.customElements.get("media-container")||chunkDITZCOYN_cjs.o.customElements.define("media-container",Gi);var Mh=(s,e,t)=>{if(!e.has(s))throw TypeError("Cannot "+t)},Ye=(s,e,t)=>(Mh(s,e,"read from private field"),t?t.call(s):e.get(s)),gr=(s,e,t)=>{if(e.has(s))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(s):e.set(s,t);},jn=(s,e,t,i)=>(Mh(s,e,"write to private field"),e.set(s,t),t),ys,Ss,zn,Hi,hi,_i,Ii=class{constructor(e,t,{defaultValue:i}={defaultValue:void 0}){gr(this,hi),gr(this,ys,void 0),gr(this,Ss,void 0),gr(this,zn,void 0),gr(this,Hi,new Set),jn(this,ys,e),jn(this,Ss,t),jn(this,zn,new Set(i));}[Symbol.iterator](){return Ye(this,hi,_i).values()}get length(){return Ye(this,hi,_i).size}get value(){var e;return (e=[...Ye(this,hi,_i)].join(" "))!=null?e:""}set value(e){var t;e!==this.value&&(jn(this,Hi,new Set),this.add(...(t=e?.split(" "))!=null?t:[]));}toString(){return this.value}item(e){return [...Ye(this,hi,_i)][e]}values(){return Ye(this,hi,_i).values()}forEach(e,t){Ye(this,hi,_i).forEach(e,t);}add(...e){var t,i;e.forEach(r=>Ye(this,Hi).add(r)),!(this.value===""&&!((t=Ye(this,ys))!=null&&t.hasAttribute(`${Ye(this,Ss)}`)))&&((i=Ye(this,ys))==null||i.setAttribute(`${Ye(this,Ss)}`,`${this.value}`));}remove(...e){var t;e.forEach(i=>Ye(this,Hi).delete(i)),(t=Ye(this,ys))==null||t.setAttribute(`${Ye(this,Ss)}`,`${this.value}`);}contains(e){return Ye(this,hi,_i).has(e)}toggle(e,t){return typeof t<"u"?t?(this.add(e),true):(this.remove(e),false):this.contains(e)?(this.remove(e),false):(this.add(e),true)}replace(e,t){return this.remove(e),this.add(t),e===t}};ys=new WeakMap;Ss=new WeakMap;zn=new WeakMap;Hi=new WeakMap;hi=new WeakSet;_i=function(){return Ye(this,Hi).size?Ye(this,Hi):Ye(this,zn)};var A0=(s="")=>s.split(/\s+/),Ph=(s="")=>{let[e,t,i]=s.split(":"),r=i?decodeURIComponent(i):void 0;return {kind:e==="cc"?chunkDITZCOYN_cjs.g.CAPTIONS:chunkDITZCOYN_cjs.g.SUBTITLES,language:t,label:r}},Ki=(s="",e={})=>A0(s).map(t=>{let i=Ph(t);return {...e,...i}}),Rl=s=>s?Array.isArray(s)?s.map(e=>typeof e=="string"?Ph(e):e):typeof s=="string"?Ki(s):[s]:[],Qn=({kind:s,label:e,language:t}={kind:"subtitles"})=>e?`${s==="captions"?"cc":"sb"}:${t}:${encodeURIComponent(e)}`:t,fi=(s=[])=>Array.prototype.map.call(s,Qn).join(" "),b0=(s,e)=>t=>t[s]===e,wh=s=>{let e=Object.entries(s).map(([t,i])=>b0(t,i));return t=>e.every(i=>i(t))},Vi=(s,e=[],t=[])=>{let i=Rl(t).map(wh),r=n=>i.some(a=>a(n));Array.from(e).filter(r).forEach(n=>{n.mode=s;});},Wi=(s,e=()=>true)=>{if(!s?.textTracks)return [];let t=typeof e=="function"?e:wh(e);return Array.from(s.textTracks).filter(t)},Xn=s=>{var e;return !!((e=s.mediaSubtitlesShowing)!=null&&e.length)||s.hasAttribute(chunkDITZCOYN_cjs.d.MEDIA_SUBTITLES_SHOWING)};var Fh=s=>{var e;let{media:t,fullscreenElement:i}=s;try{let r=i&&"requestFullscreen"in i?"requestFullscreen":i&&"webkitRequestFullScreen"in i?"webkitRequestFullScreen":void 0;if(r){let n=(e=i[r])==null?void 0:e.call(i);if(n instanceof Promise)return n.catch(()=>{})}else t?.webkitEnterFullscreen?t.webkitEnterFullscreen():t?.requestFullscreen&&t.requestFullscreen();}catch(r){console.error(r);}},Oh="exitFullscreen"in chunkDITZCOYN_cjs.p?"exitFullscreen":"webkitExitFullscreen"in chunkDITZCOYN_cjs.p?"webkitExitFullscreen":"webkitCancelFullScreen"in chunkDITZCOYN_cjs.p?"webkitCancelFullScreen":void 0,Nh=s=>{var e;let{documentElement:t}=s;if(Oh){let i=(e=t?.[Oh])==null?void 0:e.call(t);if(i instanceof Promise)return i.catch(()=>{})}},pr="fullscreenElement"in chunkDITZCOYN_cjs.p?"fullscreenElement":"webkitFullscreenElement"in chunkDITZCOYN_cjs.p?"webkitFullscreenElement":void 0,_0=s=>{let{documentElement:e,media:t}=s,i=e?.[pr];return !i&&"webkitDisplayingFullscreen"in t&&"webkitPresentationMode"in t&&t.webkitDisplayingFullscreen&&t.webkitPresentationMode===chunkDITZCOYN_cjs.l.FULLSCREEN?t:i},Uh=s=>{var e;let{media:t,documentElement:i,fullscreenElement:r=t}=s;if(!t||!i)return false;let n=_0(s);if(!n)return false;if(n===r||n===t)return true;if(n.localName.includes("-")){let a=n.shadowRoot;if(!(pr in a))return chunkDITZCOYN_cjs.w(n,r);for(;a?.[pr];){if(a[pr]===r)return true;a=(e=a[pr])==null?void 0:e.shadowRoot;}}return false},I0="fullscreenEnabled"in chunkDITZCOYN_cjs.p?"fullscreenEnabled":"webkitFullscreenEnabled"in chunkDITZCOYN_cjs.p?"webkitFullscreenEnabled":void 0,Bh=s=>{let{documentElement:e,media:t}=s;return !!e?.[I0]||t&&"webkitSupportsFullscreen"in t};var Zn,kl=()=>{var s,e;return Zn||(Zn=(e=(s=chunkDITZCOYN_cjs.p)==null?void 0:s.createElement)==null?void 0:e.call(s,"video"),Zn)},$h=async(s=kl())=>{if(!s)return false;let e=s.volume;s.volume=e/2+.1;let t=new AbortController,i=await Promise.race([L0(s,t.signal),x0(s,e)]);return t.abort(),i},L0=(s,e)=>new Promise(t=>{s.addEventListener("volumechange",()=>t(true),{signal:e});}),x0=async(s,e)=>{for(let t=0;t<10;t++){if(s.volume===e)return false;await $n(10);}return s.volume!==e},R0=/.*Version\/.*Safari\/.*/.test(chunkDITZCOYN_cjs.o.navigator.userAgent),Dl=(s=kl())=>chunkDITZCOYN_cjs.o.matchMedia("(display-mode: standalone)").matches&&R0?false:typeof s?.requestPictureInPicture=="function",Cl=(s=kl())=>Bh({documentElement:chunkDITZCOYN_cjs.p,media:s}),Gh=Cl(),Hh=Dl(),Kh=!!chunkDITZCOYN_cjs.o.WebKitPlaybackTargetAvailabilityEvent,Vh=!!chunkDITZCOYN_cjs.o.chrome;var As=s=>Wi(s.media,e=>[chunkDITZCOYN_cjs.g.SUBTITLES,chunkDITZCOYN_cjs.g.CAPTIONS].includes(e.kind)).sort((e,t)=>e.kind>=t.kind?1:-1),Ml=s=>Wi(s.media,e=>e.mode===chunkDITZCOYN_cjs.h.SHOWING&&[chunkDITZCOYN_cjs.g.SUBTITLES,chunkDITZCOYN_cjs.g.CAPTIONS].includes(e.kind)),Jn=(s,e)=>{let t=As(s),i=Ml(s),r=!!i.length;if(t.length){if(e===false||r&&e!==true)Vi(chunkDITZCOYN_cjs.h.DISABLED,t,i);else if(e===true||!r&&e!==false){let n=t[0],{options:a}=s;if(!a?.noSubtitlesLangPref){let c=globalThis.localStorage.getItem("media-chrome-pref-subtitles-lang"),u=c?[c,...globalThis.navigator.languages]:globalThis.navigator.languages,h=t.filter(f=>u.some(m=>f.language.toLowerCase().startsWith(m.split("-")[0]))).sort((f,m)=>{let p=u.findIndex(v=>f.language.toLowerCase().startsWith(v.split("-")[0])),E=u.findIndex(v=>m.language.toLowerCase().startsWith(v.split("-")[0]));return p-E});h[0]&&(n=h[0]);}let{language:o,label:l,kind:d}=n;Vi(chunkDITZCOYN_cjs.h.DISABLED,t,i),Vi(chunkDITZCOYN_cjs.h.SHOWING,t,[{language:o,label:l,kind:d}]);}}},ea=(s,e)=>s===e?true:s==null||e==null||typeof s!=typeof e?false:typeof s=="number"&&Number.isNaN(s)&&Number.isNaN(e)?true:typeof s!="object"?false:Array.isArray(s)?k0(s,e):Object.entries(s).every(([t,i])=>t in e&&ea(i,e[t])),k0=(s,e)=>{let t=Array.isArray(s),i=Array.isArray(e);return t!==i?false:t||i?s.length!==e.length?false:s.every((r,n)=>ea(r,e[n])):true};var D0=Object.values(chunkDITZCOYN_cjs.k),ta,C0=$h().then(s=>(ta=s,ta)),Wh=async(...s)=>{await Promise.all(s.filter(e=>e).map(async e=>{if(!("localName"in e&&e instanceof chunkDITZCOYN_cjs.o.HTMLElement))return;let t=e.localName;if(!t.includes("-"))return;let i=chunkDITZCOYN_cjs.o.customElements.get(t);i&&e instanceof i||(await chunkDITZCOYN_cjs.o.customElements.whenDefined(t),chunkDITZCOYN_cjs.o.customElements.upgrade(e));}));},M0=new chunkDITZCOYN_cjs.o.DOMParser,P0=s=>s&&(M0.parseFromString(s,"text/html").body.textContent||s),bs={mediaError:{get(s,e){let{media:t}=s;if(e?.type!=="playing")return t?.error},mediaEvents:["emptied","error","playing"]},mediaErrorCode:{get(s,e){var t;let{media:i}=s;if(e?.type!=="playing")return (t=i?.error)==null?void 0:t.code},mediaEvents:["emptied","error","playing"]},mediaErrorMessage:{get(s,e){var t,i;let{media:r}=s;if(e?.type!=="playing")return (i=(t=r?.error)==null?void 0:t.message)!=null?i:""},mediaEvents:["emptied","error","playing"]},mediaWidth:{get(s){var e;let{media:t}=s;return (e=t?.videoWidth)!=null?e:0},mediaEvents:["resize"]},mediaHeight:{get(s){var e;let{media:t}=s;return (e=t?.videoHeight)!=null?e:0},mediaEvents:["resize"]},mediaPaused:{get(s){var e;let{media:t}=s;return (e=t?.paused)!=null?e:true},set(s,e){var t;let{media:i}=e;i&&(s?i.pause():(t=i.play())==null||t.catch(()=>{}));},mediaEvents:["play","playing","pause","emptied"]},mediaHasPlayed:{get(s,e){let{media:t}=s;return t?e?e.type==="playing":!t.paused:false},mediaEvents:["playing","emptied"]},mediaEnded:{get(s){var e;let{media:t}=s;return (e=t?.ended)!=null?e:false},mediaEvents:["seeked","ended","emptied"]},mediaPlaybackRate:{get(s){var e;let{media:t}=s;return (e=t?.playbackRate)!=null?e:1},set(s,e){let{media:t}=e;t&&Number.isFinite(+s)&&(t.playbackRate=+s);},mediaEvents:["ratechange","loadstart"]},mediaMuted:{get(s){var e;let{media:t}=s;return (e=t?.muted)!=null?e:false},set(s,e){let{media:t,options:{noMutedPref:i}={}}=e;if(t){if(!t.hasAttribute("muted")&&!i)try{chunkDITZCOYN_cjs.o.localStorage.setItem("media-chrome-pref-muted",s?"true":"false");}catch(r){console.debug("Error setting muted pref",r);}t.muted=s;}},mediaEvents:["volumechange"],stateOwnersUpdateHandlers:[(s,e)=>{let{options:{noMutedPref:t}}=e,{media:i}=e;if(!(!i||i.muted||t))try{let r=chunkDITZCOYN_cjs.o.localStorage.getItem("media-chrome-pref-muted")==="true";bs.mediaMuted.set(r,e),s(r);}catch(r){console.debug("Error getting muted pref",r);}}]},mediaVolume:{get(s){var e;let{media:t}=s;return (e=t?.volume)!=null?e:1},set(s,e){let{media:t,options:{noVolumePref:i}={}}=e;if(t){try{s==null?chunkDITZCOYN_cjs.o.localStorage.removeItem("media-chrome-pref-volume"):!t.hasAttribute("muted")&&!i&&chunkDITZCOYN_cjs.o.localStorage.setItem("media-chrome-pref-volume",s.toString());}catch(r){console.debug("Error setting volume pref",r);}Number.isFinite(+s)&&(t.volume=+s);}},mediaEvents:["volumechange"],stateOwnersUpdateHandlers:[(s,e)=>{let{options:{noVolumePref:t}}=e;if(!t)try{let{media:i}=e;if(!i)return;let r=chunkDITZCOYN_cjs.o.localStorage.getItem("media-chrome-pref-volume");if(r==null)return;bs.mediaVolume.set(+r,e),s(+r);}catch(i){console.debug("Error getting volume pref",i);}}]},mediaVolumeLevel:{get(s){let{media:e}=s;return typeof e?.volume>"u"?"high":e.muted||e.volume===0?"off":e.volume<.5?"low":e.volume<.75?"medium":"high"},mediaEvents:["volumechange"]},mediaCurrentTime:{get(s){var e;let{media:t}=s;return (e=t?.currentTime)!=null?e:0},set(s,e){let{media:t}=e;!t||!gs(s)||(t.currentTime=s);},mediaEvents:["timeupdate","loadedmetadata"]},mediaDuration:{get(s){let{media:e,options:{defaultDuration:t}={}}=s;return t&&(!e||!e.duration||Number.isNaN(e.duration)||!Number.isFinite(e.duration))?t:Number.isFinite(e?.duration)?e.duration:Number.NaN},mediaEvents:["durationchange","loadedmetadata","emptied"]},mediaLoading:{get(s){let{media:e}=s;return e?.readyState<3},mediaEvents:["waiting","playing","emptied"]},mediaSeekable:{get(s){var e;let{media:t}=s;if(!((e=t?.seekable)!=null&&e.length))return;let i=t.seekable.start(0),r=t.seekable.end(t.seekable.length-1);if(!(!i&&!r))return [Number(i.toFixed(3)),Number(r.toFixed(3))]},mediaEvents:["loadedmetadata","emptied","progress","seekablechange"]},mediaBuffered:{get(s){var e;let{media:t}=s,i=(e=t?.buffered)!=null?e:[];return Array.from(i).map((r,n)=>[Number(i.start(n).toFixed(3)),Number(i.end(n).toFixed(3))])},mediaEvents:["progress","emptied"]},mediaStreamType:{get(s){let{media:e,options:{defaultStreamType:t}={}}=s,i=[chunkDITZCOYN_cjs.k.LIVE,chunkDITZCOYN_cjs.k.ON_DEMAND].includes(t)?t:void 0;if(!e)return i;let{streamType:r}=e;if(D0.includes(r))return r===chunkDITZCOYN_cjs.k.UNKNOWN?i:r;let n=e.duration;return n===1/0?chunkDITZCOYN_cjs.k.LIVE:Number.isFinite(n)?chunkDITZCOYN_cjs.k.ON_DEMAND:i},mediaEvents:["emptied","durationchange","loadedmetadata","streamtypechange"]},mediaTargetLiveWindow:{get(s){let{media:e}=s;if(!e)return Number.NaN;let{targetLiveWindow:t}=e,i=bs.mediaStreamType.get(s);return (t==null||Number.isNaN(t))&&i===chunkDITZCOYN_cjs.k.LIVE?0:t},mediaEvents:["emptied","durationchange","loadedmetadata","streamtypechange","targetlivewindowchange"]},mediaTimeIsLive:{get(s){let{media:e,options:{liveEdgeOffset:t=10}={}}=s;if(!e)return false;if(typeof e.liveEdgeStart=="number")return Number.isNaN(e.liveEdgeStart)?false:e.currentTime>=e.liveEdgeStart;if(!(bs.mediaStreamType.get(s)===chunkDITZCOYN_cjs.k.LIVE))return false;let r=e.seekable;if(!r)return true;if(!r.length)return false;let n=r.end(r.length-1)-t;return e.currentTime>=n},mediaEvents:["playing","timeupdate","progress","waiting","emptied"]},mediaSubtitlesList:{get(s){return As(s).map(({kind:e,label:t,language:i})=>({kind:e,label:t,language:i}))},mediaEvents:["loadstart"],textTracksEvents:["addtrack","removetrack"]},mediaSubtitlesShowing:{get(s){return Ml(s).map(({kind:e,label:t,language:i})=>({kind:e,label:t,language:i}))},mediaEvents:["loadstart"],textTracksEvents:["addtrack","removetrack","change"],stateOwnersUpdateHandlers:[(s,e)=>{var t,i;let{media:r,options:n}=e;if(!r)return;let a=o=>{var l;!n.defaultSubtitles||o&&![chunkDITZCOYN_cjs.g.CAPTIONS,chunkDITZCOYN_cjs.g.SUBTITLES].includes((l=o?.track)==null?void 0:l.kind)||Jn(e,true);};return r.addEventListener("loadstart",a),(t=r.textTracks)==null||t.addEventListener("addtrack",a),(i=r.textTracks)==null||i.addEventListener("removetrack",a),()=>{var o,l;r.removeEventListener("loadstart",a),(o=r.textTracks)==null||o.removeEventListener("addtrack",a),(l=r.textTracks)==null||l.removeEventListener("removetrack",a);}}]},mediaChaptersCues:{get(s){var e;let{media:t}=s;if(!t)return [];let[i]=Wi(t,{kind:chunkDITZCOYN_cjs.g.CHAPTERS});return Array.from((e=i?.cues)!=null?e:[]).map(({text:r,startTime:n,endTime:a})=>({text:P0(r),startTime:n,endTime:a}))},mediaEvents:["loadstart","loadedmetadata"],textTracksEvents:["addtrack","removetrack","change"],stateOwnersUpdateHandlers:[(s,e)=>{var t;let{media:i}=e;if(!i)return;let r=i.querySelector('track[kind="chapters"][default][src]'),n=(t=i.shadowRoot)==null?void 0:t.querySelector(':is(video,audio) > track[kind="chapters"][default][src]');return r?.addEventListener("load",s),n?.addEventListener("load",s),()=>{r?.removeEventListener("load",s),n?.removeEventListener("load",s);}}]},mediaIsPip:{get(s){var e,t;let{media:i,documentElement:r}=s;if(!i||!r||!r.pictureInPictureElement)return false;if(r.pictureInPictureElement===i)return true;if(r.pictureInPictureElement instanceof HTMLMediaElement)return (e=i.localName)!=null&&e.includes("-")?chunkDITZCOYN_cjs.w(i,r.pictureInPictureElement):false;if(r.pictureInPictureElement.localName.includes("-")){let n=r.pictureInPictureElement.shadowRoot;for(;n?.pictureInPictureElement;){if(n.pictureInPictureElement===i)return true;n=(t=n.pictureInPictureElement)==null?void 0:t.shadowRoot;}}return false},set(s,e){let{media:t}=e;if(t)if(s){if(!chunkDITZCOYN_cjs.p.pictureInPictureEnabled){console.warn("MediaChrome: Picture-in-picture is not enabled");return}if(!t.requestPictureInPicture){console.warn("MediaChrome: The current media does not support picture-in-picture");return}let i=()=>{console.warn("MediaChrome: The media is not ready for picture-in-picture. It must have a readyState > 0.");};t.requestPictureInPicture().catch(r=>{if(r.code===11){if(!t.src){console.warn("MediaChrome: The media is not ready for picture-in-picture. It must have a src set.");return}if(t.readyState===0&&t.preload==="none"){let n=()=>{t.removeEventListener("loadedmetadata",a),t.preload="none";},a=()=>{t.requestPictureInPicture().catch(i),n();};t.addEventListener("loadedmetadata",a),t.preload="metadata",setTimeout(()=>{t.readyState===0&&i(),n();},1e3);}else throw r}else throw r});}else chunkDITZCOYN_cjs.p.pictureInPictureElement&&chunkDITZCOYN_cjs.p.exitPictureInPicture();},mediaEvents:["enterpictureinpicture","leavepictureinpicture"]},mediaRenditionList:{get(s){var e;let{media:t}=s;return [...(e=t?.videoRenditions)!=null?e:[]].map(i=>({...i}))},mediaEvents:["emptied","loadstart"],videoRenditionsEvents:["addrendition","removerendition"]},mediaRenditionSelected:{get(s){var e,t,i;let{media:r}=s;return (i=(t=r?.videoRenditions)==null?void 0:t[(e=r.videoRenditions)==null?void 0:e.selectedIndex])==null?void 0:i.id},set(s,e){let{media:t}=e;if(!t?.videoRenditions){console.warn("MediaController: Rendition selection not supported by this media.");return}let i=s,r=Array.prototype.findIndex.call(t.videoRenditions,n=>n.id==i);t.videoRenditions.selectedIndex!=r&&(t.videoRenditions.selectedIndex=r);},mediaEvents:["emptied"],videoRenditionsEvents:["addrendition","removerendition","change"]},mediaAudioTrackList:{get(s){var e;let{media:t}=s;return [...(e=t?.audioTracks)!=null?e:[]]},mediaEvents:["emptied","loadstart"],audioTracksEvents:["addtrack","removetrack"]},mediaAudioTrackEnabled:{get(s){var e,t;let{media:i}=s;return (t=[...(e=i?.audioTracks)!=null?e:[]].find(r=>r.enabled))==null?void 0:t.id},set(s,e){let{media:t}=e;if(!t?.audioTracks){console.warn("MediaChrome: Audio track selection not supported by this media.");return}let i=s;for(let r of t.audioTracks)r.enabled=i==r.id;},mediaEvents:["emptied"],audioTracksEvents:["addtrack","removetrack","change"]},mediaIsFullscreen:{get(s){return Uh(s)},set(s,e,t){var i;s?(Fh(e),t.detail&&((i=e.media)==null||i.focus())):Nh(e);},rootEvents:["fullscreenchange","webkitfullscreenchange"],mediaEvents:["webkitbeginfullscreen","webkitendfullscreen","webkitpresentationmodechanged"]},mediaIsCasting:{get(s){var e;let{media:t}=s;return !t?.remote||((e=t.remote)==null?void 0:e.state)==="disconnected"?false:!!t.remote.state},set(s,e){var t,i;let{media:r}=e;if(r&&!(s&&((t=r.remote)==null?void 0:t.state)!=="disconnected")&&!(!s&&((i=r.remote)==null?void 0:i.state)!=="connected")){if(typeof r.remote.prompt!="function"){console.warn("MediaChrome: Casting is not supported in this environment");return}r.remote.prompt().catch(()=>{});}},remoteEvents:["connect","connecting","disconnect"]},mediaIsAirplaying:{get(){return false},set(s,e){let{media:t}=e;if(t){if(!(t.webkitShowPlaybackTargetPicker&&chunkDITZCOYN_cjs.o.WebKitPlaybackTargetAvailabilityEvent)){console.error("MediaChrome: received a request to select AirPlay but AirPlay is not supported in this environment");return}t.webkitShowPlaybackTargetPicker();}},mediaEvents:["webkitcurrentplaybacktargetiswirelesschanged"]},mediaFullscreenUnavailable:{get(s){let{media:e}=s;if(!Gh||!Cl(e))return chunkDITZCOYN_cjs.j.UNSUPPORTED}},mediaPipUnavailable:{get(s){let{media:e}=s;if(!Hh||!Dl(e))return chunkDITZCOYN_cjs.j.UNSUPPORTED;if(e?.disablePictureInPicture)return chunkDITZCOYN_cjs.j.UNAVAILABLE}},mediaVolumeUnavailable:{get(s){let{media:e}=s;if(ta===false||e?.volume==null)return chunkDITZCOYN_cjs.j.UNSUPPORTED},stateOwnersUpdateHandlers:[s=>{ta==null&&C0.then(e=>s(e?void 0:chunkDITZCOYN_cjs.j.UNSUPPORTED));}]},mediaCastUnavailable:{get(s,{availability:e="not-available"}={}){var t;let{media:i}=s;if(!Vh||!((t=i?.remote)!=null&&t.state))return chunkDITZCOYN_cjs.j.UNSUPPORTED;if(!(e==null||e==="available"))return chunkDITZCOYN_cjs.j.UNAVAILABLE},stateOwnersUpdateHandlers:[(s,e)=>{var t;let{media:i}=e;return i?(i.disableRemotePlayback||i.hasAttribute("disableremoteplayback")||(t=i?.remote)==null||t.watchAvailability(n=>{s({availability:n?"available":"not-available"});}).catch(n=>{n.name==="NotSupportedError"?s({availability:null}):s({availability:"not-available"});}),()=>{var n;(n=i?.remote)==null||n.cancelWatchAvailability().catch(()=>{});}):void 0}]},mediaAirplayUnavailable:{get(s,e){if(!Kh)return chunkDITZCOYN_cjs.j.UNSUPPORTED;if(e?.availability==="not-available")return chunkDITZCOYN_cjs.j.UNAVAILABLE},mediaEvents:["webkitplaybacktargetavailabilitychanged"],stateOwnersUpdateHandlers:[(s,e)=>{var t;let{media:i}=e;return i?(i.disableRemotePlayback||i.hasAttribute("disableremoteplayback")||(t=i?.remote)==null||t.watchAvailability(n=>{s({availability:n?"available":"not-available"});}).catch(n=>{n.name==="NotSupportedError"?s({availability:null}):s({availability:"not-available"});}),()=>{var n;(n=i?.remote)==null||n.cancelWatchAvailability().catch(()=>{});}):void 0}]},mediaRenditionUnavailable:{get(s){var e;let{media:t}=s;if(!t?.videoRenditions)return chunkDITZCOYN_cjs.j.UNSUPPORTED;if(!((e=t.videoRenditions)!=null&&e.length))return chunkDITZCOYN_cjs.j.UNAVAILABLE},mediaEvents:["emptied","loadstart"],videoRenditionsEvents:["addrendition","removerendition"]},mediaAudioTrackUnavailable:{get(s){var e,t;let{media:i}=s;if(!i?.audioTracks)return chunkDITZCOYN_cjs.j.UNSUPPORTED;if(((t=(e=i.audioTracks)==null?void 0:e.length)!=null?t:0)<=1)return chunkDITZCOYN_cjs.j.UNAVAILABLE},mediaEvents:["emptied","loadstart"],audioTracksEvents:["addtrack","removetrack"]},mediaLang:{get(s){let{options:{mediaLang:e}={}}=s;return e??"en"}}};var Yh={[chunkDITZCOYN_cjs.a.MEDIA_PREVIEW_REQUEST](s,e,{detail:t}){var i,r,n;let{media:a}=e,o=t??void 0,l,d;if(a&&o!=null){let[f]=Wi(a,{kind:chunkDITZCOYN_cjs.g.METADATA,label:"thumbnails"}),m=Array.prototype.find.call((i=f?.cues)!=null?i:[],(p,E,v)=>E===0?p.endTime>o:E===v.length-1?p.startTime<=o:p.startTime<=o&&p.endTime>o);if(m){let p=/'^(?:[a-z]+:)?\/\//i.test(m.text)||(r=a?.querySelector('track[label="thumbnails"]'))==null?void 0:r.src,E=new URL(m.text,p);d=new URLSearchParams(E.hash).get("#xywh").split(",").map(T=>+T),l=E.href;}}let c=s.mediaDuration.get(e),h=(n=s.mediaChaptersCues.get(e).find((f,m,p)=>m===p.length-1&&c===f.endTime?f.startTime<=o&&f.endTime>=o:f.startTime<=o&&f.endTime>o))==null?void 0:n.text;return t!=null&&h==null&&(h=""),{mediaPreviewTime:o,mediaPreviewImage:l,mediaPreviewCoords:d,mediaPreviewChapter:h}},[chunkDITZCOYN_cjs.a.MEDIA_PAUSE_REQUEST](s,e){s["mediaPaused"].set(true,e);},[chunkDITZCOYN_cjs.a.MEDIA_PLAY_REQUEST](s,e){var t,i,r,n;let a="mediaPaused",l=s.mediaStreamType.get(e)===chunkDITZCOYN_cjs.k.LIVE,d=!((t=e.options)!=null&&t.noAutoSeekToLive),c=s.mediaTargetLiveWindow.get(e)>0;if(l&&d&&!c){let u=(i=s.mediaSeekable.get(e))==null?void 0:i[1];if(u){let h=(n=(r=e.options)==null?void 0:r.seekToLiveOffset)!=null?n:0,f=u-h;s.mediaCurrentTime.set(f,e);}}s[a].set(false,e);},[chunkDITZCOYN_cjs.a.MEDIA_PLAYBACK_RATE_REQUEST](s,e,{detail:t}){let i="mediaPlaybackRate",r=t;s[i].set(r,e);},[chunkDITZCOYN_cjs.a.MEDIA_MUTE_REQUEST](s,e){s["mediaMuted"].set(true,e);},[chunkDITZCOYN_cjs.a.MEDIA_UNMUTE_REQUEST](s,e){let t="mediaMuted";s.mediaVolume.get(e)||s.mediaVolume.set(.25,e),s[t].set(false,e);},[chunkDITZCOYN_cjs.a.MEDIA_VOLUME_REQUEST](s,e,{detail:t}){let i="mediaVolume",r=t;r&&s.mediaMuted.get(e)&&s.mediaMuted.set(false,e),s[i].set(r,e);},[chunkDITZCOYN_cjs.a.MEDIA_SEEK_REQUEST](s,e,{detail:t}){let i="mediaCurrentTime",r=t;s[i].set(r,e);},[chunkDITZCOYN_cjs.a.MEDIA_SEEK_TO_LIVE_REQUEST](s,e){var t,i,r;let n="mediaCurrentTime",a=(t=s.mediaSeekable.get(e))==null?void 0:t[1];if(Number.isNaN(Number(a)))return;let o=(r=(i=e.options)==null?void 0:i.seekToLiveOffset)!=null?r:0,l=a-o;s[n].set(l,e);},[chunkDITZCOYN_cjs.a.MEDIA_SHOW_SUBTITLES_REQUEST](s,e,{detail:t}){var i;let{options:r}=e,n=As(e),a=Rl(t),o=(i=a[0])==null?void 0:i.language;o&&!r.noSubtitlesLangPref&&chunkDITZCOYN_cjs.o.localStorage.setItem("media-chrome-pref-subtitles-lang",o),Vi(chunkDITZCOYN_cjs.h.SHOWING,n,a);},[chunkDITZCOYN_cjs.a.MEDIA_DISABLE_SUBTITLES_REQUEST](s,e,{detail:t}){let i=As(e),r=t??[];Vi(chunkDITZCOYN_cjs.h.DISABLED,i,r);},[chunkDITZCOYN_cjs.a.MEDIA_TOGGLE_SUBTITLES_REQUEST](s,e,{detail:t}){Jn(e,t);},[chunkDITZCOYN_cjs.a.MEDIA_RENDITION_REQUEST](s,e,{detail:t}){let i="mediaRenditionSelected",r=t;s[i].set(r,e);},[chunkDITZCOYN_cjs.a.MEDIA_AUDIO_TRACK_REQUEST](s,e,{detail:t}){let i="mediaAudioTrackEnabled",r=t;s[i].set(r,e);},[chunkDITZCOYN_cjs.a.MEDIA_ENTER_PIP_REQUEST](s,e){let t="mediaIsPip";s.mediaIsFullscreen.get(e)&&s.mediaIsFullscreen.set(false,e),s[t].set(true,e);},[chunkDITZCOYN_cjs.a.MEDIA_EXIT_PIP_REQUEST](s,e){s["mediaIsPip"].set(false,e);},[chunkDITZCOYN_cjs.a.MEDIA_ENTER_FULLSCREEN_REQUEST](s,e,t){let i="mediaIsFullscreen";s.mediaIsPip.get(e)&&s.mediaIsPip.set(false,e),s[i].set(true,e,t);},[chunkDITZCOYN_cjs.a.MEDIA_EXIT_FULLSCREEN_REQUEST](s,e){s["mediaIsFullscreen"].set(false,e);},[chunkDITZCOYN_cjs.a.MEDIA_ENTER_CAST_REQUEST](s,e){let t="mediaIsCasting";s.mediaIsFullscreen.get(e)&&s.mediaIsFullscreen.set(false,e),s[t].set(true,e);},[chunkDITZCOYN_cjs.a.MEDIA_EXIT_CAST_REQUEST](s,e){s["mediaIsCasting"].set(false,e);},[chunkDITZCOYN_cjs.a.MEDIA_AIRPLAY_REQUEST](s,e){s["mediaIsAirplaying"].set(true,e);}};var qh=({media:s,fullscreenElement:e,documentElement:t,stateMediator:i=bs,requestMap:r=Yh,options:n={},monitorStateOwnersOnlyWithSubscriptions:a=true})=>{let o=[],l={options:{...n}},d=Object.freeze({mediaPreviewTime:void 0,mediaPreviewImage:void 0,mediaPreviewCoords:void 0,mediaPreviewChapter:void 0}),c=p=>{p!=null&&(ea(p,d)||(d=Object.freeze({...d,...p}),o.forEach(E=>E(d))));},u=()=>{let p=Object.entries(i).reduce((E,[v,{get:T}])=>(E[v]=T(l),E),{});c(p);},h={},f,m=async(p,E)=>{var v,T,S,A,b,D,I,k,R,L,M,B,H,j,K,O;let Y=!!f;if(f={...l,...f??{},...p},Y)return;await Wh(...Object.values(p));let $=o.length>0&&E===0&&a,q=l.media!==f.media,Q=((v=l.media)==null?void 0:v.textTracks)!==((T=f.media)==null?void 0:T.textTracks),N=((S=l.media)==null?void 0:S.videoRenditions)!==((A=f.media)==null?void 0:A.videoRenditions),U=((b=l.media)==null?void 0:b.audioTracks)!==((D=f.media)==null?void 0:D.audioTracks),te=((I=l.media)==null?void 0:I.remote)!==((k=f.media)==null?void 0:k.remote),ge=l.documentElement!==f.documentElement,ie=!!l.media&&(q||$),de=!!((R=l.media)!=null&&R.textTracks)&&(Q||$),Be=!!((L=l.media)!=null&&L.videoRenditions)&&(N||$),Fe=!!((M=l.media)!=null&&M.audioTracks)&&(U||$),tt=!!((B=l.media)!=null&&B.remote)&&(te||$),ft=!!l.documentElement&&(ge||$),Kt=ie||de||Be||Fe||tt||ft,Si=o.length===0&&E===1&&a,us=!!f.media&&(q||Si),hs=!!((H=f.media)!=null&&H.textTracks)&&(Q||Si),vl=!!((j=f.media)!=null&&j.videoRenditions)&&(N||Si),he=!!((K=f.media)!=null&&K.audioTracks)&&(U||Si),$e=!!((O=f.media)!=null&&O.remote)&&(te||Si),it=!!f.documentElement&&(ge||Si),Vt=us||hs||vl||he||$e||it;if(!(Kt||Vt)){Object.entries(f).forEach(([fe,mt])=>{l[fe]=mt;}),u(),f=void 0;return}Object.entries(i).forEach(([fe,{get:mt,mediaEvents:kn=[],textTracksEvents:fs=[],videoRenditionsEvents:Dn=[],audioTracksEvents:Ui=[],remoteEvents:Cn=[],rootEvents:Tl=[],stateOwnersUpdateHandlers:Mn=[]}])=>{h[fe]||(h[fe]={});let Ze=Pe=>{let gt=mt(l,Pe);c({[fe]:gt});},Ie;Ie=h[fe].mediaEvents,kn.forEach(Pe=>{Ie&&ie&&(l.media.removeEventListener(Pe,Ie),h[fe].mediaEvents=void 0),us&&(f.media.addEventListener(Pe,Ze),h[fe].mediaEvents=Ze);}),Ie=h[fe].textTracksEvents,fs.forEach(Pe=>{var gt,Ct;Ie&&de&&((gt=l.media.textTracks)==null||gt.removeEventListener(Pe,Ie),h[fe].textTracksEvents=void 0),hs&&((Ct=f.media.textTracks)==null||Ct.addEventListener(Pe,Ze),h[fe].textTracksEvents=Ze);}),Ie=h[fe].videoRenditionsEvents,Dn.forEach(Pe=>{var gt,Ct;Ie&&Be&&((gt=l.media.videoRenditions)==null||gt.removeEventListener(Pe,Ie),h[fe].videoRenditionsEvents=void 0),vl&&((Ct=f.media.videoRenditions)==null||Ct.addEventListener(Pe,Ze),h[fe].videoRenditionsEvents=Ze);}),Ie=h[fe].audioTracksEvents,Ui.forEach(Pe=>{var gt,Ct;Ie&&Fe&&((gt=l.media.audioTracks)==null||gt.removeEventListener(Pe,Ie),h[fe].audioTracksEvents=void 0),he&&((Ct=f.media.audioTracks)==null||Ct.addEventListener(Pe,Ze),h[fe].audioTracksEvents=Ze);}),Ie=h[fe].remoteEvents,Cn.forEach(Pe=>{var gt,Ct;Ie&&tt&&((gt=l.media.remote)==null||gt.removeEventListener(Pe,Ie),h[fe].remoteEvents=void 0),$e&&((Ct=f.media.remote)==null||Ct.addEventListener(Pe,Ze),h[fe].remoteEvents=Ze);}),Ie=h[fe].rootEvents,Tl.forEach(Pe=>{Ie&&ft&&(l.documentElement.removeEventListener(Pe,Ie),h[fe].rootEvents=void 0),it&&(f.documentElement.addEventListener(Pe,Ze),h[fe].rootEvents=Ze);});let rh=h[fe].stateOwnersUpdateHandlers;Mn.forEach(Pe=>{rh&&Kt&&rh(),Vt&&(h[fe].stateOwnersUpdateHandlers=Pe(Ze,f));});}),Object.entries(f).forEach(([fe,mt])=>{l[fe]=mt;}),u(),f=void 0;};return m({media:s,fullscreenElement:e,documentElement:t,options:n}),{dispatch(p){let{type:E,detail:v}=p;if(r[E]&&d.mediaErrorCode==null){c(r[E](i,l,p));return}E==="mediaelementchangerequest"?m({media:v}):E==="fullscreenelementchangerequest"?m({fullscreenElement:v}):E==="documentelementchangerequest"?m({documentElement:v}):E==="optionschangerequest"&&(Object.entries(v??{}).forEach(([T,S])=>{l.options[T]=S;}),u());},getState(){return d},subscribe(p){return m({},o.length+1),o.push(p),p(d),()=>{let E=o.indexOf(p);E>=0&&(m({},o.length-1),o.splice(E,1));}}}};var Nl=(s,e,t)=>{if(!e.has(s))throw TypeError("Cannot "+t)},se=(s,e,t)=>(Nl(s,e,"read from private field"),t?t.call(s):e.get(s)),mi=(s,e,t)=>{if(e.has(s))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(s):e.set(s,t);},Li=(s,e,t,i)=>(Nl(s,e,"write to private field"),e.set(s,t),t),xi=(s,e,t)=>(Nl(s,e,"access private method"),t),qi,Er,Ee,vr,Yt,ia,sa,Pl,_s,Tr,ra,wl,Jh=["ArrowLeft","ArrowRight","ArrowUp","ArrowDown","Enter"," ","f","m","k","c"],jh=10,zh=.025,F={DEFAULT_SUBTITLES:"defaultsubtitles",DEFAULT_STREAM_TYPE:"defaultstreamtype",DEFAULT_DURATION:"defaultduration",FULLSCREEN_ELEMENT:"fullscreenelement",HOTKEYS:"hotkeys",KEYS_USED:"keysused",LIVE_EDGE_OFFSET:"liveedgeoffset",SEEK_TO_LIVE_OFFSET:"seektoliveoffset",NO_AUTO_SEEK_TO_LIVE:"noautoseektolive",NO_HOTKEYS:"nohotkeys",NO_VOLUME_PREF:"novolumepref",NO_MUTED_PREF:"nomutedpref",NO_SUBTITLES_LANG_PREF:"nosubtitleslangpref",NO_DEFAULT_STORE:"nodefaultstore",KEYBOARD_FORWARD_SEEK_OFFSET:"keyboardforwardseekoffset",KEYBOARD_BACKWARD_SEEK_OFFSET:"keyboardbackwardseekoffset",KEYBOARD_UP_VOLUME_STEP:"keyboardupvolumestep",KEYBOARD_DOWN_VOLUME_STEP:"keyboarddownvolumestep",LANG:"lang"},Ol=class extends Gi{constructor(){super(),mi(this,sa),mi(this,_s),mi(this,ra),this.mediaStateReceivers=[],this.associatedElementSubscriptions=new Map,mi(this,qi,new Ii(this,F.HOTKEYS)),mi(this,Er,void 0),mi(this,Ee,void 0),mi(this,vr,void 0),mi(this,Yt,void 0),mi(this,ia,t=>{var i;(i=se(this,Ee))==null||i.dispatch(t);}),this.associateElement(this);let e={};Li(this,vr,t=>{Object.entries(t).forEach(([i,r])=>{if(i in e&&e[i]===r)return;this.propagateMediaState(i,r);let n=i.toLowerCase(),a=new chunkDITZCOYN_cjs.o.CustomEvent(chunkDITZCOYN_cjs.f[n],{composed:true,detail:r});this.dispatchEvent(a);}),e=t;}),this.hasAttribute(F.NO_HOTKEYS)?this.disableHotkeys():this.enableHotkeys();}static get observedAttributes(){return super.observedAttributes.concat(F.NO_HOTKEYS,F.HOTKEYS,F.DEFAULT_STREAM_TYPE,F.DEFAULT_SUBTITLES,F.DEFAULT_DURATION,F.NO_MUTED_PREF,F.NO_VOLUME_PREF,F.LANG)}get mediaStore(){return se(this,Ee)}set mediaStore(e){var t,i;if(se(this,Ee)&&((t=se(this,Yt))==null||t.call(this),Li(this,Yt,void 0)),Li(this,Ee,e),!se(this,Ee)&&!this.hasAttribute(F.NO_DEFAULT_STORE)){xi(this,sa,Pl).call(this);return}Li(this,Yt,(i=se(this,Ee))==null?void 0:i.subscribe(se(this,vr)));}get fullscreenElement(){var e;return (e=se(this,Er))!=null?e:this}set fullscreenElement(e){var t;this.hasAttribute(F.FULLSCREEN_ELEMENT)&&this.removeAttribute(F.FULLSCREEN_ELEMENT),Li(this,Er,e),(t=se(this,Ee))==null||t.dispatch({type:"fullscreenelementchangerequest",detail:this.fullscreenElement});}get defaultSubtitles(){return chunkDITZCOYN_cjs.F(this,F.DEFAULT_SUBTITLES)}set defaultSubtitles(e){chunkDITZCOYN_cjs.G(this,F.DEFAULT_SUBTITLES,e);}get defaultStreamType(){return chunkDITZCOYN_cjs.H(this,F.DEFAULT_STREAM_TYPE)}set defaultStreamType(e){chunkDITZCOYN_cjs.I(this,F.DEFAULT_STREAM_TYPE,e);}get defaultDuration(){return chunkDITZCOYN_cjs.D(this,F.DEFAULT_DURATION)}set defaultDuration(e){chunkDITZCOYN_cjs.E(this,F.DEFAULT_DURATION,e);}get noHotkeys(){return chunkDITZCOYN_cjs.F(this,F.NO_HOTKEYS)}set noHotkeys(e){chunkDITZCOYN_cjs.G(this,F.NO_HOTKEYS,e);}get keysUsed(){return chunkDITZCOYN_cjs.H(this,F.KEYS_USED)}set keysUsed(e){chunkDITZCOYN_cjs.I(this,F.KEYS_USED,e);}get liveEdgeOffset(){return chunkDITZCOYN_cjs.D(this,F.LIVE_EDGE_OFFSET)}set liveEdgeOffset(e){chunkDITZCOYN_cjs.E(this,F.LIVE_EDGE_OFFSET,e);}get noAutoSeekToLive(){return chunkDITZCOYN_cjs.F(this,F.NO_AUTO_SEEK_TO_LIVE)}set noAutoSeekToLive(e){chunkDITZCOYN_cjs.G(this,F.NO_AUTO_SEEK_TO_LIVE,e);}get noVolumePref(){return chunkDITZCOYN_cjs.F(this,F.NO_VOLUME_PREF)}set noVolumePref(e){chunkDITZCOYN_cjs.G(this,F.NO_VOLUME_PREF,e);}get noMutedPref(){return chunkDITZCOYN_cjs.F(this,F.NO_MUTED_PREF)}set noMutedPref(e){chunkDITZCOYN_cjs.G(this,F.NO_MUTED_PREF,e);}get noSubtitlesLangPref(){return chunkDITZCOYN_cjs.F(this,F.NO_SUBTITLES_LANG_PREF)}set noSubtitlesLangPref(e){chunkDITZCOYN_cjs.G(this,F.NO_SUBTITLES_LANG_PREF,e);}get noDefaultStore(){return chunkDITZCOYN_cjs.F(this,F.NO_DEFAULT_STORE)}set noDefaultStore(e){chunkDITZCOYN_cjs.G(this,F.NO_DEFAULT_STORE,e);}attributeChangedCallback(e,t,i){var r,n,a,o,l,d,c,u,h,f,m;if(super.attributeChangedCallback(e,t,i),e===F.NO_HOTKEYS)i!==t&&i===""?(this.hasAttribute(F.HOTKEYS)&&console.warn("Media Chrome: Both `hotkeys` and `nohotkeys` have been set. All hotkeys will be disabled."),this.disableHotkeys()):i!==t&&i===null&&this.enableHotkeys();else if(e===F.HOTKEYS)se(this,qi).value=i;else if(e===F.DEFAULT_SUBTITLES&&i!==t)(r=se(this,Ee))==null||r.dispatch({type:"optionschangerequest",detail:{defaultSubtitles:this.hasAttribute(F.DEFAULT_SUBTITLES)}});else if(e===F.DEFAULT_STREAM_TYPE)(a=se(this,Ee))==null||a.dispatch({type:"optionschangerequest",detail:{defaultStreamType:(n=this.getAttribute(F.DEFAULT_STREAM_TYPE))!=null?n:void 0}});else if(e===F.LIVE_EDGE_OFFSET)(o=se(this,Ee))==null||o.dispatch({type:"optionschangerequest",detail:{liveEdgeOffset:this.hasAttribute(F.LIVE_EDGE_OFFSET)?+this.getAttribute(F.LIVE_EDGE_OFFSET):void 0,seekToLiveOffset:this.hasAttribute(F.SEEK_TO_LIVE_OFFSET)?void 0:+this.getAttribute(F.LIVE_EDGE_OFFSET)}});else if(e===F.SEEK_TO_LIVE_OFFSET)(l=se(this,Ee))==null||l.dispatch({type:"optionschangerequest",detail:{seekToLiveOffset:this.hasAttribute(F.SEEK_TO_LIVE_OFFSET)?+this.getAttribute(F.SEEK_TO_LIVE_OFFSET):void 0}});else if(e===F.NO_AUTO_SEEK_TO_LIVE)(d=se(this,Ee))==null||d.dispatch({type:"optionschangerequest",detail:{noAutoSeekToLive:this.hasAttribute(F.NO_AUTO_SEEK_TO_LIVE)}});else if(e===F.FULLSCREEN_ELEMENT){let p=i?(c=this.getRootNode())==null?void 0:c.getElementById(i):void 0;Li(this,Er,p),(u=se(this,Ee))==null||u.dispatch({type:"fullscreenelementchangerequest",detail:this.fullscreenElement});}else e===F.LANG&&i!==t?(chunkDITZCOYN_cjs.m(i),(h=se(this,Ee))==null||h.dispatch({type:"optionschangerequest",detail:{mediaLang:i}})):e===F.NO_VOLUME_PREF&&i!==t?(f=se(this,Ee))==null||f.dispatch({type:"optionschangerequest",detail:{noVolumePref:this.hasAttribute(F.NO_VOLUME_PREF)}}):e===F.NO_MUTED_PREF&&i!==t&&((m=se(this,Ee))==null||m.dispatch({type:"optionschangerequest",detail:{noMutedPref:this.hasAttribute(F.NO_MUTED_PREF)}}));}connectedCallback(){var e,t;!se(this,Ee)&&!this.hasAttribute(F.NO_DEFAULT_STORE)&&xi(this,sa,Pl).call(this),(e=se(this,Ee))==null||e.dispatch({type:"documentelementchangerequest",detail:chunkDITZCOYN_cjs.p}),super.connectedCallback(),se(this,Ee)&&!se(this,Yt)&&Li(this,Yt,(t=se(this,Ee))==null?void 0:t.subscribe(se(this,vr))),this.hasAttribute(F.NO_HOTKEYS)?this.disableHotkeys():this.enableHotkeys();}disconnectedCallback(){var e,t,i,r;(e=super.disconnectedCallback)==null||e.call(this),se(this,Ee)&&((t=se(this,Ee))==null||t.dispatch({type:"documentelementchangerequest",detail:void 0}),(i=se(this,Ee))==null||i.dispatch({type:chunkDITZCOYN_cjs.a.MEDIA_TOGGLE_SUBTITLES_REQUEST,detail:false})),se(this,Yt)&&((r=se(this,Yt))==null||r.call(this),Li(this,Yt,void 0));}mediaSetCallback(e){var t;super.mediaSetCallback(e),(t=se(this,Ee))==null||t.dispatch({type:"mediaelementchangerequest",detail:e}),e.hasAttribute("tabindex")||(e.tabIndex=-1);}mediaUnsetCallback(e){var t;super.mediaUnsetCallback(e),(t=se(this,Ee))==null||t.dispatch({type:"mediaelementchangerequest",detail:void 0});}propagateMediaState(e,t){Zh(this.mediaStateReceivers,e,t);}associateElement(e){if(!e)return;let{associatedElementSubscriptions:t}=this;if(t.has(e))return;let i=this.registerMediaStateReceiver.bind(this),r=this.unregisterMediaStateReceiver.bind(this),n=B0(e,i,r);Object.values(chunkDITZCOYN_cjs.a).forEach(a=>{e.addEventListener(a,se(this,ia));}),t.set(e,n);}unassociateElement(e){if(!e)return;let{associatedElementSubscriptions:t}=this;if(!t.has(e))return;t.get(e)(),t.delete(e),Object.values(chunkDITZCOYN_cjs.a).forEach(r=>{e.removeEventListener(r,se(this,ia));});}registerMediaStateReceiver(e){if(!e)return;let t=this.mediaStateReceivers;t.indexOf(e)>-1||(t.push(e),se(this,Ee)&&Object.entries(se(this,Ee).getState()).forEach(([r,n])=>{Zh([e],r,n);}));}unregisterMediaStateReceiver(e){let t=this.mediaStateReceivers,i=t.indexOf(e);i<0||t.splice(i,1);}enableHotkeys(){this.addEventListener("keydown",xi(this,ra,wl));}disableHotkeys(){this.removeEventListener("keydown",xi(this,ra,wl)),this.removeEventListener("keyup",xi(this,_s,Tr));}get hotkeys(){return chunkDITZCOYN_cjs.H(this,F.HOTKEYS)}set hotkeys(e){chunkDITZCOYN_cjs.I(this,F.HOTKEYS,e);}keyboardShortcutHandler(e){var t,i,r,n,a,o,l;let d=e.target;if(((r=(i=(t=d.getAttribute(F.KEYS_USED))==null?void 0:t.split(" "))!=null?i:d?.keysUsed)!=null?r:[]).map(m=>m==="Space"?" ":m).filter(Boolean).includes(e.key))return;let u,h,f;if(!se(this,qi).contains(`no${e.key.toLowerCase()}`)&&!(e.key===" "&&se(this,qi).contains("nospace")))switch(e.key){case " ":case "k":u=se(this,Ee).getState().mediaPaused?chunkDITZCOYN_cjs.a.MEDIA_PLAY_REQUEST:chunkDITZCOYN_cjs.a.MEDIA_PAUSE_REQUEST,this.dispatchEvent(new chunkDITZCOYN_cjs.o.CustomEvent(u,{composed:true,bubbles:true}));break;case "m":u=this.mediaStore.getState().mediaVolumeLevel==="off"?chunkDITZCOYN_cjs.a.MEDIA_UNMUTE_REQUEST:chunkDITZCOYN_cjs.a.MEDIA_MUTE_REQUEST,this.dispatchEvent(new chunkDITZCOYN_cjs.o.CustomEvent(u,{composed:true,bubbles:true}));break;case "f":u=this.mediaStore.getState().mediaIsFullscreen?chunkDITZCOYN_cjs.a.MEDIA_EXIT_FULLSCREEN_REQUEST:chunkDITZCOYN_cjs.a.MEDIA_ENTER_FULLSCREEN_REQUEST,this.dispatchEvent(new chunkDITZCOYN_cjs.o.CustomEvent(u,{composed:true,bubbles:true}));break;case "c":this.dispatchEvent(new chunkDITZCOYN_cjs.o.CustomEvent(chunkDITZCOYN_cjs.a.MEDIA_TOGGLE_SUBTITLES_REQUEST,{composed:true,bubbles:true}));break;case "ArrowLeft":{let m=this.hasAttribute(F.KEYBOARD_BACKWARD_SEEK_OFFSET)?+this.getAttribute(F.KEYBOARD_BACKWARD_SEEK_OFFSET):jh;h=Math.max(((n=this.mediaStore.getState().mediaCurrentTime)!=null?n:0)-m,0),f=new chunkDITZCOYN_cjs.o.CustomEvent(chunkDITZCOYN_cjs.a.MEDIA_SEEK_REQUEST,{composed:true,bubbles:true,detail:h}),this.dispatchEvent(f);break}case "ArrowRight":{let m=this.hasAttribute(F.KEYBOARD_FORWARD_SEEK_OFFSET)?+this.getAttribute(F.KEYBOARD_FORWARD_SEEK_OFFSET):jh;h=Math.max(((a=this.mediaStore.getState().mediaCurrentTime)!=null?a:0)+m,0),f=new chunkDITZCOYN_cjs.o.CustomEvent(chunkDITZCOYN_cjs.a.MEDIA_SEEK_REQUEST,{composed:true,bubbles:true,detail:h}),this.dispatchEvent(f);break}case "ArrowUp":{let m=this.hasAttribute(F.KEYBOARD_UP_VOLUME_STEP)?+this.getAttribute(F.KEYBOARD_UP_VOLUME_STEP):zh;h=Math.min(((o=this.mediaStore.getState().mediaVolume)!=null?o:1)+m,1),f=new chunkDITZCOYN_cjs.o.CustomEvent(chunkDITZCOYN_cjs.a.MEDIA_VOLUME_REQUEST,{composed:true,bubbles:true,detail:h}),this.dispatchEvent(f);break}case "ArrowDown":{let m=this.hasAttribute(F.KEYBOARD_DOWN_VOLUME_STEP)?+this.getAttribute(F.KEYBOARD_DOWN_VOLUME_STEP):zh;h=Math.max(((l=this.mediaStore.getState().mediaVolume)!=null?l:1)-m,0),f=new chunkDITZCOYN_cjs.o.CustomEvent(chunkDITZCOYN_cjs.a.MEDIA_VOLUME_REQUEST,{composed:true,bubbles:true,detail:h}),this.dispatchEvent(f);break}}}};qi=new WeakMap;Er=new WeakMap;Ee=new WeakMap;vr=new WeakMap;Yt=new WeakMap;ia=new WeakMap;sa=new WeakSet;Pl=function(){var s;this.mediaStore=qh({media:this.media,fullscreenElement:this.fullscreenElement,options:{defaultSubtitles:this.hasAttribute(F.DEFAULT_SUBTITLES),defaultDuration:this.hasAttribute(F.DEFAULT_DURATION)?+this.getAttribute(F.DEFAULT_DURATION):void 0,defaultStreamType:(s=this.getAttribute(F.DEFAULT_STREAM_TYPE))!=null?s:void 0,liveEdgeOffset:this.hasAttribute(F.LIVE_EDGE_OFFSET)?+this.getAttribute(F.LIVE_EDGE_OFFSET):void 0,seekToLiveOffset:this.hasAttribute(F.SEEK_TO_LIVE_OFFSET)?+this.getAttribute(F.SEEK_TO_LIVE_OFFSET):this.hasAttribute(F.LIVE_EDGE_OFFSET)?+this.getAttribute(F.LIVE_EDGE_OFFSET):void 0,noAutoSeekToLive:this.hasAttribute(F.NO_AUTO_SEEK_TO_LIVE),noVolumePref:this.hasAttribute(F.NO_VOLUME_PREF),noMutedPref:this.hasAttribute(F.NO_MUTED_PREF),noSubtitlesLangPref:this.hasAttribute(F.NO_SUBTITLES_LANG_PREF)}});};_s=new WeakSet;Tr=function(s){let{key:e}=s;if(!Jh.includes(e)){this.removeEventListener("keyup",xi(this,_s,Tr));return}this.keyboardShortcutHandler(s);};ra=new WeakSet;wl=function(s){let{metaKey:e,altKey:t,key:i}=s;if(e||t||!Jh.includes(i)){this.removeEventListener("keyup",xi(this,_s,Tr));return}let r=s.target,n=r instanceof HTMLElement&&(r.tagName.toLowerCase()==="media-volume-range"||r.tagName.toLowerCase()==="media-time-range");[" ","ArrowLeft","ArrowRight","ArrowUp","ArrowDown"].includes(i)&&!(se(this,qi).contains(`no${i.toLowerCase()}`)||i===" "&&se(this,qi).contains("nospace"))&&!n&&s.preventDefault(),this.addEventListener("keyup",xi(this,_s,Tr),{once:true});};var w0=Object.values(chunkDITZCOYN_cjs.d),O0=Object.values(chunkDITZCOYN_cjs.c),ef=s=>{var e,t,i,r;let{observedAttributes:n}=s.constructor;!n&&((e=s.nodeName)!=null&&e.includes("-"))&&(chunkDITZCOYN_cjs.o.customElements.upgrade(s),{observedAttributes:n}=s.constructor);let a=(r=(i=(t=s?.getAttribute)==null?void 0:t.call(s,chunkDITZCOYN_cjs.b.MEDIA_CHROME_ATTRIBUTES))==null?void 0:i.split)==null?void 0:r.call(i,/\s+/);return Array.isArray(n||a)?(n||a).filter(o=>w0.includes(o)):[]},F0=s=>{var e,t;return (e=s.nodeName)!=null&&e.includes("-")&&chunkDITZCOYN_cjs.o.customElements.get((t=s.nodeName)==null?void 0:t.toLowerCase())&&!(s instanceof chunkDITZCOYN_cjs.o.customElements.get(s.nodeName.toLowerCase()))&&chunkDITZCOYN_cjs.o.customElements.upgrade(s),O0.some(i=>i in s)},Fl=s=>F0(s)||!!ef(s).length,Qh=s=>{var e;return (e=s?.join)==null?void 0:e.call(s,":")},Xh={[chunkDITZCOYN_cjs.d.MEDIA_SUBTITLES_LIST]:fi,[chunkDITZCOYN_cjs.d.MEDIA_SUBTITLES_SHOWING]:fi,[chunkDITZCOYN_cjs.d.MEDIA_SEEKABLE]:Qh,[chunkDITZCOYN_cjs.d.MEDIA_BUFFERED]:s=>s?.map(Qh).join(" "),[chunkDITZCOYN_cjs.d.MEDIA_PREVIEW_COORDS]:s=>s?.join(" "),[chunkDITZCOYN_cjs.d.MEDIA_RENDITION_LIST]:Ah,[chunkDITZCOYN_cjs.d.MEDIA_AUDIO_TRACK_LIST]:_h},N0=async(s,e,t)=>{var i,r;if(s.isConnected||await $n(0),typeof t=="boolean"||t==null)return chunkDITZCOYN_cjs.G(s,e,t);if(typeof t=="number")return chunkDITZCOYN_cjs.E(s,e,t);if(typeof t=="string")return chunkDITZCOYN_cjs.I(s,e,t);if(Array.isArray(t)&&!t.length)return s.removeAttribute(e);let n=(r=(i=Xh[e])==null?void 0:i.call(Xh,t))!=null?r:t;return s.setAttribute(e,n)},U0=s=>{var e;return !!((e=s.closest)!=null&&e.call(s,'*[slot="media"]'))},Yi=(s,e)=>{if(U0(s))return;let t=(r,n)=>{var a,o;Fl(r)&&n(r);let{children:l=[]}=r??{},d=(o=(a=r?.shadowRoot)==null?void 0:a.children)!=null?o:[];[...l,...d].forEach(u=>Yi(u,n));},i=s?.nodeName.toLowerCase();if(i.includes("-")&&!Fl(s)){chunkDITZCOYN_cjs.o.customElements.whenDefined(i).then(()=>{t(s,e);});return}t(s,e);},Zh=(s,e,t)=>{s.forEach(i=>{if(e in i){i[e]=t;return}let r=ef(i),n=e.toLowerCase();r.includes(n)&&N0(i,n,t);});},B0=(s,e,t)=>{Yi(s,e);let i=c=>{var u;let h=(u=c?.composedPath()[0])!=null?u:c.target;e(h);},r=c=>{var u;let h=(u=c?.composedPath()[0])!=null?u:c.target;t(h);};s.addEventListener(chunkDITZCOYN_cjs.a.REGISTER_MEDIA_STATE_RECEIVER,i),s.addEventListener(chunkDITZCOYN_cjs.a.UNREGISTER_MEDIA_STATE_RECEIVER,r);let n=c=>{c.forEach(u=>{let{addedNodes:h=[],removedNodes:f=[],type:m,target:p,attributeName:E}=u;m==="childList"?(Array.prototype.forEach.call(h,v=>Yi(v,e)),Array.prototype.forEach.call(f,v=>Yi(v,t))):m==="attributes"&&E===chunkDITZCOYN_cjs.b.MEDIA_CHROME_ATTRIBUTES&&(Fl(p)?e(p):t(p));});},a=[],o=c=>{let u=c.target;u.name!=="media"&&(a.forEach(h=>Yi(h,t)),a=[...u.assignedElements({flatten:true})],a.forEach(h=>Yi(h,e)));};s.addEventListener("slotchange",o);let l=new MutationObserver(n);return l.observe(s,{childList:true,attributes:true,subtree:true}),()=>{Yi(s,t),s.removeEventListener("slotchange",o),l.disconnect(),s.removeEventListener(chunkDITZCOYN_cjs.a.REGISTER_MEDIA_STATE_RECEIVER,i),s.removeEventListener(chunkDITZCOYN_cjs.a.UNREGISTER_MEDIA_STATE_RECEIVER,r);}};chunkDITZCOYN_cjs.o.customElements.get("media-controller")||chunkDITZCOYN_cjs.o.customElements.define("media-controller",Ol);var tf=`<svg aria-hidden="true" viewBox="0 0 26 24">
159
+ `}var v0=Object.values(chunkDITZCOYN_cjs.d),T0="sm:384 md:576 lg:768 xl:960";function y0(s){Mh(s.target,s.contentRect.width);}function Mh(s,e){var t;if(!s.isConnected)return;let i=(t=s.getAttribute(X.BREAKPOINTS))!=null?t:T0,r=S0(i),n=A0(r,e),a=false;if(Object.keys(r).forEach(o=>{if(n.includes(o)){s.hasAttribute(`breakpoint${o}`)||(s.setAttribute(`breakpoint${o}`,""),a=true);return}s.hasAttribute(`breakpoint${o}`)&&(s.removeAttribute(`breakpoint${o}`),a=true);}),a){let o=new CustomEvent(chunkDITZCOYN_cjs.e.BREAKPOINTS_CHANGE,{detail:n});s.dispatchEvent(o);}s.breakpointsComputed||(s.breakpointsComputed=true,s.dispatchEvent(new CustomEvent(chunkDITZCOYN_cjs.e.BREAKPOINTS_COMPUTED,{bubbles:true,composed:true})));}function S0(s){let e=s.split(/\s+/);return Object.fromEntries(e.map(t=>t.split(":")))}function A0(s,e){return Object.keys(s).filter(t=>e>=parseInt(s[t]))}var Gi=class extends chunkDITZCOYN_cjs.o.HTMLElement{constructor(){if(super(),pt(this,bl),pt(this,_l),pt(this,Il),pt(this,fr),pt(this,qn),pt(this,Ts),pt(this,Wn,0),pt(this,Es,null),pt(this,hr,null),pt(this,vs,void 0),this.breakpointsComputed=false,pt(this,Kn,new MutationObserver(Lt(this,bl,kh).bind(this))),pt(this,ur,false),pt(this,Vn,t=>{Et(this,ur)||(setTimeout(()=>{y0(t),$i(this,ur,false);},0),$i(this,ur,true));}),!this.shadowRoot){this.attachShadow(this.constructor.shadowRootOptions);let t=chunkDITZCOYN_cjs.s(this.attributes),i=this.constructor.getTemplateHTML(t);this.shadowRoot.setHTMLUnsafe?this.shadowRoot.setHTMLUnsafe(i):this.shadowRoot.innerHTML=i;}let e=this.querySelector(":scope > slot[slot=media]");e&&e.addEventListener("slotchange",()=>{if(!e.assignedElements({flatten:true}).length){Et(this,Es)&&this.mediaUnsetCallback(Et(this,Es));return}this.handleMediaUpdated(this.media);});}static get observedAttributes(){return [X.AUTOHIDE,X.GESTURES_DISABLED].concat(v0).filter(e=>![chunkDITZCOYN_cjs.d.MEDIA_RENDITION_LIST,chunkDITZCOYN_cjs.d.MEDIA_AUDIO_TRACK_LIST,chunkDITZCOYN_cjs.d.MEDIA_CHAPTERS_CUES,chunkDITZCOYN_cjs.d.MEDIA_WIDTH,chunkDITZCOYN_cjs.d.MEDIA_HEIGHT,chunkDITZCOYN_cjs.d.MEDIA_ERROR,chunkDITZCOYN_cjs.d.MEDIA_ERROR_MESSAGE].includes(e))}attributeChangedCallback(e,t,i){e.toLowerCase()==X.AUTOHIDE&&(this.autohide=i);}get media(){let e=this.querySelector(":scope > [slot=media]");return e?.nodeName=="SLOT"&&(e=e.assignedElements({flatten:true})[0]),e}async handleMediaUpdated(e){e&&($i(this,Es,e),e.localName.includes("-")&&await chunkDITZCOYN_cjs.o.customElements.whenDefined(e.localName),this.mediaSetCallback(e));}connectedCallback(){var e;Et(this,Kn).observe(this,{childList:true,subtree:true}),chunkDITZCOYN_cjs.q(this,Et(this,Vn));let i=this.getAttribute(X.AUDIO)!=null?chunkDITZCOYN_cjs.n("audio player"):chunkDITZCOYN_cjs.n("video player");this.setAttribute("role","region"),this.setAttribute("aria-label",i),this.handleMediaUpdated(this.media),this.setAttribute(X.USER_INACTIVE,""),Mh(this,this.getBoundingClientRect().width),this.addEventListener("pointerdown",this),this.addEventListener("pointermove",this),this.addEventListener("pointerup",this),this.addEventListener("mouseleave",this),this.addEventListener("keyup",this),(e=chunkDITZCOYN_cjs.o.window)==null||e.addEventListener("mouseup",this);}disconnectedCallback(){var e;Et(this,Kn).disconnect(),chunkDITZCOYN_cjs.r(this,Et(this,Vn)),this.media&&this.mediaUnsetCallback(this.media),(e=chunkDITZCOYN_cjs.o.window)==null||e.removeEventListener("mouseup",this);}mediaSetCallback(e){}mediaUnsetCallback(e){$i(this,Es,null);}handleEvent(e){switch(e.type){case "pointerdown":$i(this,Wn,e.timeStamp);break;case "pointermove":Lt(this,_l,Dh).call(this,e);break;case "pointerup":Lt(this,Il,Ch).call(this,e);break;case "mouseleave":Lt(this,fr,Yn).call(this);break;case "mouseup":this.removeAttribute(X.KEYBOARD_CONTROL);break;case "keyup":Lt(this,Ts,mr).call(this),this.setAttribute(X.KEYBOARD_CONTROL,"");break}}set autohide(e){let t=Number(e);$i(this,vs,isNaN(t)?0:t);}get autohide(){return (Et(this,vs)===void 0?2:Et(this,vs)).toString()}get breakpoints(){return chunkDITZCOYN_cjs.H(this,X.BREAKPOINTS)}set breakpoints(e){chunkDITZCOYN_cjs.I(this,X.BREAKPOINTS,e);}get audio(){return chunkDITZCOYN_cjs.F(this,X.AUDIO)}set audio(e){chunkDITZCOYN_cjs.G(this,X.AUDIO,e);}get gesturesDisabled(){return chunkDITZCOYN_cjs.F(this,X.GESTURES_DISABLED)}set gesturesDisabled(e){chunkDITZCOYN_cjs.G(this,X.GESTURES_DISABLED,e);}get keyboardControl(){return chunkDITZCOYN_cjs.F(this,X.KEYBOARD_CONTROL)}set keyboardControl(e){chunkDITZCOYN_cjs.G(this,X.KEYBOARD_CONTROL,e);}get noAutohide(){return chunkDITZCOYN_cjs.F(this,X.NO_AUTOHIDE)}set noAutohide(e){chunkDITZCOYN_cjs.G(this,X.NO_AUTOHIDE,e);}get autohideOverControls(){return chunkDITZCOYN_cjs.F(this,X.AUTOHIDE_OVER_CONTROLS)}set autohideOverControls(e){chunkDITZCOYN_cjs.G(this,X.AUTOHIDE_OVER_CONTROLS,e);}get userInteractive(){return chunkDITZCOYN_cjs.F(this,X.USER_INACTIVE)}set userInteractive(e){chunkDITZCOYN_cjs.G(this,X.USER_INACTIVE,e);}};Wn=new WeakMap;Es=new WeakMap;hr=new WeakMap;vs=new WeakMap;Kn=new WeakMap;bl=new WeakSet;kh=function(s){let e=this.media;for(let t of s){if(t.type!=="childList")continue;let i=t.removedNodes;for(let r of i){if(r.slot!="media"||t.target!=this)continue;let n=t.previousSibling&&t.previousSibling.previousElementSibling;if(!n||!e)this.mediaUnsetCallback(r);else {let a=n.slot!=="media";for(;(n=n.previousSibling)!==null;)n.slot=="media"&&(a=false);a&&this.mediaUnsetCallback(r);}}if(e)for(let r of t.addedNodes)r===e&&this.handleMediaUpdated(e);}};ur=new WeakMap;Vn=new WeakMap;_l=new WeakSet;Dh=function(s){if(s.pointerType!=="mouse"&&s.timeStamp-Et(this,Wn)<250)return;Lt(this,qn,xl).call(this),clearTimeout(Et(this,hr));let e=this.hasAttribute(X.AUTOHIDE_OVER_CONTROLS);([this,this.media].includes(s.target)||e)&&Lt(this,Ts,mr).call(this);};Il=new WeakSet;Ch=function(s){if(s.pointerType==="touch"){let e=!this.hasAttribute(X.USER_INACTIVE);[this,this.media].includes(s.target)&&e?Lt(this,fr,Yn).call(this):Lt(this,Ts,mr).call(this);}else s.composedPath().some(e=>["media-play-button","media-fullscreen-button"].includes(e?.localName))&&Lt(this,Ts,mr).call(this);};fr=new WeakSet;Yn=function(){if(Et(this,vs)<0||this.hasAttribute(X.USER_INACTIVE))return;this.setAttribute(X.USER_INACTIVE,"");let s=new chunkDITZCOYN_cjs.o.CustomEvent(chunkDITZCOYN_cjs.e.USER_INACTIVE_CHANGE,{composed:true,bubbles:true,detail:true});this.dispatchEvent(s);};qn=new WeakSet;xl=function(){if(!this.hasAttribute(X.USER_INACTIVE))return;this.removeAttribute(X.USER_INACTIVE);let s=new chunkDITZCOYN_cjs.o.CustomEvent(chunkDITZCOYN_cjs.e.USER_INACTIVE_CHANGE,{composed:true,bubbles:true,detail:false});this.dispatchEvent(s);};Ts=new WeakSet;mr=function(){Lt(this,qn,xl).call(this),clearTimeout(Et(this,hr));let s=parseInt(this.autohide);s<0||$i(this,hr,setTimeout(()=>{Lt(this,fr,Yn).call(this);},s*1e3));};Gi.shadowRootOptions={mode:"open"};Gi.getTemplateHTML=E0;chunkDITZCOYN_cjs.o.customElements.get("media-container")||chunkDITZCOYN_cjs.o.customElements.define("media-container",Gi);var Ph=(s,e,t)=>{if(!e.has(s))throw TypeError("Cannot "+t)},Ye=(s,e,t)=>(Ph(s,e,"read from private field"),t?t.call(s):e.get(s)),gr=(s,e,t)=>{if(e.has(s))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(s):e.set(s,t);},jn=(s,e,t,i)=>(Ph(s,e,"write to private field"),e.set(s,t),t),ys,Ss,zn,Hi,hi,_i,Ii=class{constructor(e,t,{defaultValue:i}={defaultValue:void 0}){gr(this,hi),gr(this,ys,void 0),gr(this,Ss,void 0),gr(this,zn,void 0),gr(this,Hi,new Set),jn(this,ys,e),jn(this,Ss,t),jn(this,zn,new Set(i));}[Symbol.iterator](){return Ye(this,hi,_i).values()}get length(){return Ye(this,hi,_i).size}get value(){var e;return (e=[...Ye(this,hi,_i)].join(" "))!=null?e:""}set value(e){var t;e!==this.value&&(jn(this,Hi,new Set),this.add(...(t=e?.split(" "))!=null?t:[]));}toString(){return this.value}item(e){return [...Ye(this,hi,_i)][e]}values(){return Ye(this,hi,_i).values()}forEach(e,t){Ye(this,hi,_i).forEach(e,t);}add(...e){var t,i;e.forEach(r=>Ye(this,Hi).add(r)),!(this.value===""&&!((t=Ye(this,ys))!=null&&t.hasAttribute(`${Ye(this,Ss)}`)))&&((i=Ye(this,ys))==null||i.setAttribute(`${Ye(this,Ss)}`,`${this.value}`));}remove(...e){var t;e.forEach(i=>Ye(this,Hi).delete(i)),(t=Ye(this,ys))==null||t.setAttribute(`${Ye(this,Ss)}`,`${this.value}`);}contains(e){return Ye(this,hi,_i).has(e)}toggle(e,t){return typeof t<"u"?t?(this.add(e),true):(this.remove(e),false):this.contains(e)?(this.remove(e),false):(this.add(e),true)}replace(e,t){return this.remove(e),this.add(t),e===t}};ys=new WeakMap;Ss=new WeakMap;zn=new WeakMap;Hi=new WeakMap;hi=new WeakSet;_i=function(){return Ye(this,Hi).size?Ye(this,Hi):Ye(this,zn)};var b0=(s="")=>s.split(/\s+/),wh=(s="")=>{let[e,t,i]=s.split(":"),r=i?decodeURIComponent(i):void 0;return {kind:e==="cc"?chunkDITZCOYN_cjs.g.CAPTIONS:chunkDITZCOYN_cjs.g.SUBTITLES,language:t,label:r}},Ki=(s="",e={})=>b0(s).map(t=>{let i=wh(t);return {...e,...i}}),Rl=s=>s?Array.isArray(s)?s.map(e=>typeof e=="string"?wh(e):e):typeof s=="string"?Ki(s):[s]:[],Qn=({kind:s,label:e,language:t}={kind:"subtitles"})=>e?`${s==="captions"?"cc":"sb"}:${t}:${encodeURIComponent(e)}`:t,fi=(s=[])=>Array.prototype.map.call(s,Qn).join(" "),_0=(s,e)=>t=>t[s]===e,Oh=s=>{let e=Object.entries(s).map(([t,i])=>_0(t,i));return t=>e.every(i=>i(t))},Vi=(s,e=[],t=[])=>{let i=Rl(t).map(Oh),r=n=>i.some(a=>a(n));Array.from(e).filter(r).forEach(n=>{n.mode=s;});},Wi=(s,e=()=>true)=>{if(!s?.textTracks)return [];let t=typeof e=="function"?e:Oh(e);return Array.from(s.textTracks).filter(t)},Xn=s=>{var e;return !!((e=s.mediaSubtitlesShowing)!=null&&e.length)||s.hasAttribute(chunkDITZCOYN_cjs.d.MEDIA_SUBTITLES_SHOWING)};var Nh=s=>{var e;let{media:t,fullscreenElement:i}=s;try{let r=i&&"requestFullscreen"in i?"requestFullscreen":i&&"webkitRequestFullScreen"in i?"webkitRequestFullScreen":void 0;if(r){let n=(e=i[r])==null?void 0:e.call(i);if(n instanceof Promise)return n.catch(()=>{})}else t?.webkitEnterFullscreen?t.webkitEnterFullscreen():t?.requestFullscreen&&t.requestFullscreen();}catch(r){console.error(r);}},Fh="exitFullscreen"in chunkDITZCOYN_cjs.p?"exitFullscreen":"webkitExitFullscreen"in chunkDITZCOYN_cjs.p?"webkitExitFullscreen":"webkitCancelFullScreen"in chunkDITZCOYN_cjs.p?"webkitCancelFullScreen":void 0,Uh=s=>{var e;let{documentElement:t}=s;if(Fh){let i=(e=t?.[Fh])==null?void 0:e.call(t);if(i instanceof Promise)return i.catch(()=>{})}},pr="fullscreenElement"in chunkDITZCOYN_cjs.p?"fullscreenElement":"webkitFullscreenElement"in chunkDITZCOYN_cjs.p?"webkitFullscreenElement":void 0,I0=s=>{let{documentElement:e,media:t}=s,i=e?.[pr];return !i&&"webkitDisplayingFullscreen"in t&&"webkitPresentationMode"in t&&t.webkitDisplayingFullscreen&&t.webkitPresentationMode===chunkDITZCOYN_cjs.l.FULLSCREEN?t:i},Bh=s=>{var e;let{media:t,documentElement:i,fullscreenElement:r=t}=s;if(!t||!i)return false;let n=I0(s);if(!n)return false;if(n===r||n===t)return true;if(n.localName.includes("-")){let a=n.shadowRoot;if(!(pr in a))return chunkDITZCOYN_cjs.w(n,r);for(;a?.[pr];){if(a[pr]===r)return true;a=(e=a[pr])==null?void 0:e.shadowRoot;}}return false},L0="fullscreenEnabled"in chunkDITZCOYN_cjs.p?"fullscreenEnabled":"webkitFullscreenEnabled"in chunkDITZCOYN_cjs.p?"webkitFullscreenEnabled":void 0,$h=s=>{let{documentElement:e,media:t}=s;return !!e?.[L0]||t&&"webkitSupportsFullscreen"in t};var Zn,kl=()=>{var s,e;return Zn||(Zn=(e=(s=chunkDITZCOYN_cjs.p)==null?void 0:s.createElement)==null?void 0:e.call(s,"video"),Zn)},Gh=async(s=kl())=>{if(!s)return false;let e=s.volume;s.volume=e/2+.1;let t=new AbortController,i=await Promise.race([x0(s,t.signal),R0(s,e)]);return t.abort(),i},x0=(s,e)=>new Promise(t=>{s.addEventListener("volumechange",()=>t(true),{signal:e});}),R0=async(s,e)=>{for(let t=0;t<10;t++){if(s.volume===e)return false;await $n(10);}return s.volume!==e},k0=/.*Version\/.*Safari\/.*/.test(chunkDITZCOYN_cjs.o.navigator.userAgent),Dl=(s=kl())=>chunkDITZCOYN_cjs.o.matchMedia("(display-mode: standalone)").matches&&k0?false:typeof s?.requestPictureInPicture=="function",Cl=(s=kl())=>$h({documentElement:chunkDITZCOYN_cjs.p,media:s}),Hh=Cl(),Kh=Dl(),Vh=!!chunkDITZCOYN_cjs.o.WebKitPlaybackTargetAvailabilityEvent,Wh=!!chunkDITZCOYN_cjs.o.chrome;var As=s=>Wi(s.media,e=>[chunkDITZCOYN_cjs.g.SUBTITLES,chunkDITZCOYN_cjs.g.CAPTIONS].includes(e.kind)).sort((e,t)=>e.kind>=t.kind?1:-1),Ml=s=>Wi(s.media,e=>e.mode===chunkDITZCOYN_cjs.h.SHOWING&&[chunkDITZCOYN_cjs.g.SUBTITLES,chunkDITZCOYN_cjs.g.CAPTIONS].includes(e.kind)),Jn=(s,e)=>{let t=As(s),i=Ml(s),r=!!i.length;if(t.length){if(e===false||r&&e!==true)Vi(chunkDITZCOYN_cjs.h.DISABLED,t,i);else if(e===true||!r&&e!==false){let n=t[0],{options:a}=s;if(!a?.noSubtitlesLangPref){let c=globalThis.localStorage.getItem("media-chrome-pref-subtitles-lang"),u=c?[c,...globalThis.navigator.languages]:globalThis.navigator.languages,h=t.filter(f=>u.some(m=>f.language.toLowerCase().startsWith(m.split("-")[0]))).sort((f,m)=>{let p=u.findIndex(v=>f.language.toLowerCase().startsWith(v.split("-")[0])),E=u.findIndex(v=>m.language.toLowerCase().startsWith(v.split("-")[0]));return p-E});h[0]&&(n=h[0]);}let{language:o,label:l,kind:d}=n;Vi(chunkDITZCOYN_cjs.h.DISABLED,t,i),Vi(chunkDITZCOYN_cjs.h.SHOWING,t,[{language:o,label:l,kind:d}]);}}},ea=(s,e)=>s===e?true:s==null||e==null||typeof s!=typeof e?false:typeof s=="number"&&Number.isNaN(s)&&Number.isNaN(e)?true:typeof s!="object"?false:Array.isArray(s)?D0(s,e):Object.entries(s).every(([t,i])=>t in e&&ea(i,e[t])),D0=(s,e)=>{let t=Array.isArray(s),i=Array.isArray(e);return t!==i?false:t||i?s.length!==e.length?false:s.every((r,n)=>ea(r,e[n])):true};var C0=Object.values(chunkDITZCOYN_cjs.k),ta,M0=Gh().then(s=>(ta=s,ta)),Yh=async(...s)=>{await Promise.all(s.filter(e=>e).map(async e=>{if(!("localName"in e&&e instanceof chunkDITZCOYN_cjs.o.HTMLElement))return;let t=e.localName;if(!t.includes("-"))return;let i=chunkDITZCOYN_cjs.o.customElements.get(t);i&&e instanceof i||(await chunkDITZCOYN_cjs.o.customElements.whenDefined(t),chunkDITZCOYN_cjs.o.customElements.upgrade(e));}));},P0=new chunkDITZCOYN_cjs.o.DOMParser,w0=s=>s&&(P0.parseFromString(s,"text/html").body.textContent||s),bs={mediaError:{get(s,e){let{media:t}=s;if(e?.type!=="playing")return t?.error},mediaEvents:["emptied","error","playing"]},mediaErrorCode:{get(s,e){var t;let{media:i}=s;if(e?.type!=="playing")return (t=i?.error)==null?void 0:t.code},mediaEvents:["emptied","error","playing"]},mediaErrorMessage:{get(s,e){var t,i;let{media:r}=s;if(e?.type!=="playing")return (i=(t=r?.error)==null?void 0:t.message)!=null?i:""},mediaEvents:["emptied","error","playing"]},mediaWidth:{get(s){var e;let{media:t}=s;return (e=t?.videoWidth)!=null?e:0},mediaEvents:["resize"]},mediaHeight:{get(s){var e;let{media:t}=s;return (e=t?.videoHeight)!=null?e:0},mediaEvents:["resize"]},mediaPaused:{get(s){var e;let{media:t}=s;return (e=t?.paused)!=null?e:true},set(s,e){var t;let{media:i}=e;i&&(s?i.pause():(t=i.play())==null||t.catch(()=>{}));},mediaEvents:["play","playing","pause","emptied"]},mediaHasPlayed:{get(s,e){let{media:t}=s;return t?e?e.type==="playing":!t.paused:false},mediaEvents:["playing","emptied"]},mediaEnded:{get(s){var e;let{media:t}=s;return (e=t?.ended)!=null?e:false},mediaEvents:["seeked","ended","emptied"]},mediaPlaybackRate:{get(s){var e;let{media:t}=s;return (e=t?.playbackRate)!=null?e:1},set(s,e){let{media:t}=e;t&&Number.isFinite(+s)&&(t.playbackRate=+s);},mediaEvents:["ratechange","loadstart"]},mediaMuted:{get(s){var e;let{media:t}=s;return (e=t?.muted)!=null?e:false},set(s,e){let{media:t,options:{noMutedPref:i}={}}=e;if(t){if(!t.hasAttribute("muted")&&!i)try{chunkDITZCOYN_cjs.o.localStorage.setItem("media-chrome-pref-muted",s?"true":"false");}catch(r){console.debug("Error setting muted pref",r);}t.muted=s;}},mediaEvents:["volumechange"],stateOwnersUpdateHandlers:[(s,e)=>{let{options:{noMutedPref:t}}=e,{media:i}=e;if(!(!i||i.muted||t))try{let r=chunkDITZCOYN_cjs.o.localStorage.getItem("media-chrome-pref-muted")==="true";bs.mediaMuted.set(r,e),s(r);}catch(r){console.debug("Error getting muted pref",r);}}]},mediaVolume:{get(s){var e;let{media:t}=s;return (e=t?.volume)!=null?e:1},set(s,e){let{media:t,options:{noVolumePref:i}={}}=e;if(t){try{s==null?chunkDITZCOYN_cjs.o.localStorage.removeItem("media-chrome-pref-volume"):!t.hasAttribute("muted")&&!i&&chunkDITZCOYN_cjs.o.localStorage.setItem("media-chrome-pref-volume",s.toString());}catch(r){console.debug("Error setting volume pref",r);}Number.isFinite(+s)&&(t.volume=+s);}},mediaEvents:["volumechange"],stateOwnersUpdateHandlers:[(s,e)=>{let{options:{noVolumePref:t}}=e;if(!t)try{let{media:i}=e;if(!i)return;let r=chunkDITZCOYN_cjs.o.localStorage.getItem("media-chrome-pref-volume");if(r==null)return;bs.mediaVolume.set(+r,e),s(+r);}catch(i){console.debug("Error getting volume pref",i);}}]},mediaVolumeLevel:{get(s){let{media:e}=s;return typeof e?.volume>"u"?"high":e.muted||e.volume===0?"off":e.volume<.5?"low":e.volume<.75?"medium":"high"},mediaEvents:["volumechange"]},mediaCurrentTime:{get(s){var e;let{media:t}=s;return (e=t?.currentTime)!=null?e:0},set(s,e){let{media:t}=e;!t||!gs(s)||(t.currentTime=s);},mediaEvents:["timeupdate","loadedmetadata"]},mediaDuration:{get(s){let{media:e,options:{defaultDuration:t}={}}=s;return t&&(!e||!e.duration||Number.isNaN(e.duration)||!Number.isFinite(e.duration))?t:Number.isFinite(e?.duration)?e.duration:Number.NaN},mediaEvents:["durationchange","loadedmetadata","emptied"]},mediaLoading:{get(s){let{media:e}=s;return e?.readyState<3},mediaEvents:["waiting","playing","emptied"]},mediaSeekable:{get(s){var e;let{media:t}=s;if(!((e=t?.seekable)!=null&&e.length))return;let i=t.seekable.start(0),r=t.seekable.end(t.seekable.length-1);if(!(!i&&!r))return [Number(i.toFixed(3)),Number(r.toFixed(3))]},mediaEvents:["loadedmetadata","emptied","progress","seekablechange"]},mediaBuffered:{get(s){var e;let{media:t}=s,i=(e=t?.buffered)!=null?e:[];return Array.from(i).map((r,n)=>[Number(i.start(n).toFixed(3)),Number(i.end(n).toFixed(3))])},mediaEvents:["progress","emptied"]},mediaStreamType:{get(s){let{media:e,options:{defaultStreamType:t}={}}=s,i=[chunkDITZCOYN_cjs.k.LIVE,chunkDITZCOYN_cjs.k.ON_DEMAND].includes(t)?t:void 0;if(!e)return i;let{streamType:r}=e;if(C0.includes(r))return r===chunkDITZCOYN_cjs.k.UNKNOWN?i:r;let n=e.duration;return n===1/0?chunkDITZCOYN_cjs.k.LIVE:Number.isFinite(n)?chunkDITZCOYN_cjs.k.ON_DEMAND:i},mediaEvents:["emptied","durationchange","loadedmetadata","streamtypechange"]},mediaTargetLiveWindow:{get(s){let{media:e}=s;if(!e)return Number.NaN;let{targetLiveWindow:t}=e,i=bs.mediaStreamType.get(s);return (t==null||Number.isNaN(t))&&i===chunkDITZCOYN_cjs.k.LIVE?0:t},mediaEvents:["emptied","durationchange","loadedmetadata","streamtypechange","targetlivewindowchange"]},mediaTimeIsLive:{get(s){let{media:e,options:{liveEdgeOffset:t=10}={}}=s;if(!e)return false;if(typeof e.liveEdgeStart=="number")return Number.isNaN(e.liveEdgeStart)?false:e.currentTime>=e.liveEdgeStart;if(!(bs.mediaStreamType.get(s)===chunkDITZCOYN_cjs.k.LIVE))return false;let r=e.seekable;if(!r)return true;if(!r.length)return false;let n=r.end(r.length-1)-t;return e.currentTime>=n},mediaEvents:["playing","timeupdate","progress","waiting","emptied"]},mediaSubtitlesList:{get(s){return As(s).map(({kind:e,label:t,language:i})=>({kind:e,label:t,language:i}))},mediaEvents:["loadstart"],textTracksEvents:["addtrack","removetrack"]},mediaSubtitlesShowing:{get(s){return Ml(s).map(({kind:e,label:t,language:i})=>({kind:e,label:t,language:i}))},mediaEvents:["loadstart"],textTracksEvents:["addtrack","removetrack","change"],stateOwnersUpdateHandlers:[(s,e)=>{var t,i;let{media:r,options:n}=e;if(!r)return;let a=o=>{var l;!n.defaultSubtitles||o&&![chunkDITZCOYN_cjs.g.CAPTIONS,chunkDITZCOYN_cjs.g.SUBTITLES].includes((l=o?.track)==null?void 0:l.kind)||Jn(e,true);};return r.addEventListener("loadstart",a),(t=r.textTracks)==null||t.addEventListener("addtrack",a),(i=r.textTracks)==null||i.addEventListener("removetrack",a),()=>{var o,l;r.removeEventListener("loadstart",a),(o=r.textTracks)==null||o.removeEventListener("addtrack",a),(l=r.textTracks)==null||l.removeEventListener("removetrack",a);}}]},mediaChaptersCues:{get(s){var e;let{media:t}=s;if(!t)return [];let[i]=Wi(t,{kind:chunkDITZCOYN_cjs.g.CHAPTERS});return Array.from((e=i?.cues)!=null?e:[]).map(({text:r,startTime:n,endTime:a})=>({text:w0(r),startTime:n,endTime:a}))},mediaEvents:["loadstart","loadedmetadata"],textTracksEvents:["addtrack","removetrack","change"],stateOwnersUpdateHandlers:[(s,e)=>{var t;let{media:i}=e;if(!i)return;let r=i.querySelector('track[kind="chapters"][default][src]'),n=(t=i.shadowRoot)==null?void 0:t.querySelector(':is(video,audio) > track[kind="chapters"][default][src]');return r?.addEventListener("load",s),n?.addEventListener("load",s),()=>{r?.removeEventListener("load",s),n?.removeEventListener("load",s);}}]},mediaIsPip:{get(s){var e,t;let{media:i,documentElement:r}=s;if(!i||!r||!r.pictureInPictureElement)return false;if(r.pictureInPictureElement===i)return true;if(r.pictureInPictureElement instanceof HTMLMediaElement)return (e=i.localName)!=null&&e.includes("-")?chunkDITZCOYN_cjs.w(i,r.pictureInPictureElement):false;if(r.pictureInPictureElement.localName.includes("-")){let n=r.pictureInPictureElement.shadowRoot;for(;n?.pictureInPictureElement;){if(n.pictureInPictureElement===i)return true;n=(t=n.pictureInPictureElement)==null?void 0:t.shadowRoot;}}return false},set(s,e){let{media:t}=e;if(t)if(s){if(!chunkDITZCOYN_cjs.p.pictureInPictureEnabled){console.warn("MediaChrome: Picture-in-picture is not enabled");return}if(!t.requestPictureInPicture){console.warn("MediaChrome: The current media does not support picture-in-picture");return}let i=()=>{console.warn("MediaChrome: The media is not ready for picture-in-picture. It must have a readyState > 0.");};t.requestPictureInPicture().catch(r=>{if(r.code===11){if(!t.src){console.warn("MediaChrome: The media is not ready for picture-in-picture. It must have a src set.");return}if(t.readyState===0&&t.preload==="none"){let n=()=>{t.removeEventListener("loadedmetadata",a),t.preload="none";},a=()=>{t.requestPictureInPicture().catch(i),n();};t.addEventListener("loadedmetadata",a),t.preload="metadata",setTimeout(()=>{t.readyState===0&&i(),n();},1e3);}else throw r}else throw r});}else chunkDITZCOYN_cjs.p.pictureInPictureElement&&chunkDITZCOYN_cjs.p.exitPictureInPicture();},mediaEvents:["enterpictureinpicture","leavepictureinpicture"]},mediaRenditionList:{get(s){var e;let{media:t}=s;return [...(e=t?.videoRenditions)!=null?e:[]].map(i=>({...i}))},mediaEvents:["emptied","loadstart"],videoRenditionsEvents:["addrendition","removerendition"]},mediaRenditionSelected:{get(s){var e,t,i;let{media:r}=s;return (i=(t=r?.videoRenditions)==null?void 0:t[(e=r.videoRenditions)==null?void 0:e.selectedIndex])==null?void 0:i.id},set(s,e){let{media:t}=e;if(!t?.videoRenditions){console.warn("MediaController: Rendition selection not supported by this media.");return}let i=s,r=Array.prototype.findIndex.call(t.videoRenditions,n=>n.id==i);t.videoRenditions.selectedIndex!=r&&(t.videoRenditions.selectedIndex=r);},mediaEvents:["emptied"],videoRenditionsEvents:["addrendition","removerendition","change"]},mediaAudioTrackList:{get(s){var e;let{media:t}=s;return [...(e=t?.audioTracks)!=null?e:[]]},mediaEvents:["emptied","loadstart"],audioTracksEvents:["addtrack","removetrack"]},mediaAudioTrackEnabled:{get(s){var e,t;let{media:i}=s;return (t=[...(e=i?.audioTracks)!=null?e:[]].find(r=>r.enabled))==null?void 0:t.id},set(s,e){let{media:t}=e;if(!t?.audioTracks){console.warn("MediaChrome: Audio track selection not supported by this media.");return}let i=s;for(let r of t.audioTracks)r.enabled=i==r.id;},mediaEvents:["emptied"],audioTracksEvents:["addtrack","removetrack","change"]},mediaIsFullscreen:{get(s){return Bh(s)},set(s,e,t){var i;s?(Nh(e),t.detail&&((i=e.media)==null||i.focus())):Uh(e);},rootEvents:["fullscreenchange","webkitfullscreenchange"],mediaEvents:["webkitbeginfullscreen","webkitendfullscreen","webkitpresentationmodechanged"]},mediaIsCasting:{get(s){var e;let{media:t}=s;return !t?.remote||((e=t.remote)==null?void 0:e.state)==="disconnected"?false:!!t.remote.state},set(s,e){var t,i;let{media:r}=e;if(r&&!(s&&((t=r.remote)==null?void 0:t.state)!=="disconnected")&&!(!s&&((i=r.remote)==null?void 0:i.state)!=="connected")){if(typeof r.remote.prompt!="function"){console.warn("MediaChrome: Casting is not supported in this environment");return}r.remote.prompt().catch(()=>{});}},remoteEvents:["connect","connecting","disconnect"]},mediaIsAirplaying:{get(){return false},set(s,e){let{media:t}=e;if(t){if(!(t.webkitShowPlaybackTargetPicker&&chunkDITZCOYN_cjs.o.WebKitPlaybackTargetAvailabilityEvent)){console.error("MediaChrome: received a request to select AirPlay but AirPlay is not supported in this environment");return}t.webkitShowPlaybackTargetPicker();}},mediaEvents:["webkitcurrentplaybacktargetiswirelesschanged"]},mediaFullscreenUnavailable:{get(s){let{media:e}=s;if(!Hh||!Cl(e))return chunkDITZCOYN_cjs.j.UNSUPPORTED}},mediaPipUnavailable:{get(s){let{media:e}=s;if(!Kh||!Dl(e))return chunkDITZCOYN_cjs.j.UNSUPPORTED;if(e?.disablePictureInPicture)return chunkDITZCOYN_cjs.j.UNAVAILABLE}},mediaVolumeUnavailable:{get(s){let{media:e}=s;if(ta===false||e?.volume==null)return chunkDITZCOYN_cjs.j.UNSUPPORTED},stateOwnersUpdateHandlers:[s=>{ta==null&&M0.then(e=>s(e?void 0:chunkDITZCOYN_cjs.j.UNSUPPORTED));}]},mediaCastUnavailable:{get(s,{availability:e="not-available"}={}){var t;let{media:i}=s;if(!Wh||!((t=i?.remote)!=null&&t.state))return chunkDITZCOYN_cjs.j.UNSUPPORTED;if(!(e==null||e==="available"))return chunkDITZCOYN_cjs.j.UNAVAILABLE},stateOwnersUpdateHandlers:[(s,e)=>{var t;let{media:i}=e;return i?(i.disableRemotePlayback||i.hasAttribute("disableremoteplayback")||(t=i?.remote)==null||t.watchAvailability(n=>{s({availability:n?"available":"not-available"});}).catch(n=>{n.name==="NotSupportedError"?s({availability:null}):s({availability:"not-available"});}),()=>{var n;(n=i?.remote)==null||n.cancelWatchAvailability().catch(()=>{});}):void 0}]},mediaAirplayUnavailable:{get(s,e){if(!Vh)return chunkDITZCOYN_cjs.j.UNSUPPORTED;if(e?.availability==="not-available")return chunkDITZCOYN_cjs.j.UNAVAILABLE},mediaEvents:["webkitplaybacktargetavailabilitychanged"],stateOwnersUpdateHandlers:[(s,e)=>{var t;let{media:i}=e;return i?(i.disableRemotePlayback||i.hasAttribute("disableremoteplayback")||(t=i?.remote)==null||t.watchAvailability(n=>{s({availability:n?"available":"not-available"});}).catch(n=>{n.name==="NotSupportedError"?s({availability:null}):s({availability:"not-available"});}),()=>{var n;(n=i?.remote)==null||n.cancelWatchAvailability().catch(()=>{});}):void 0}]},mediaRenditionUnavailable:{get(s){var e;let{media:t}=s;if(!t?.videoRenditions)return chunkDITZCOYN_cjs.j.UNSUPPORTED;if(!((e=t.videoRenditions)!=null&&e.length))return chunkDITZCOYN_cjs.j.UNAVAILABLE},mediaEvents:["emptied","loadstart"],videoRenditionsEvents:["addrendition","removerendition"]},mediaAudioTrackUnavailable:{get(s){var e,t;let{media:i}=s;if(!i?.audioTracks)return chunkDITZCOYN_cjs.j.UNSUPPORTED;if(((t=(e=i.audioTracks)==null?void 0:e.length)!=null?t:0)<=1)return chunkDITZCOYN_cjs.j.UNAVAILABLE},mediaEvents:["emptied","loadstart"],audioTracksEvents:["addtrack","removetrack"]},mediaLang:{get(s){let{options:{mediaLang:e}={}}=s;return e??"en"}}};var qh={[chunkDITZCOYN_cjs.a.MEDIA_PREVIEW_REQUEST](s,e,{detail:t}){var i,r,n;let{media:a}=e,o=t??void 0,l,d;if(a&&o!=null){let[f]=Wi(a,{kind:chunkDITZCOYN_cjs.g.METADATA,label:"thumbnails"}),m=Array.prototype.find.call((i=f?.cues)!=null?i:[],(p,E,v)=>E===0?p.endTime>o:E===v.length-1?p.startTime<=o:p.startTime<=o&&p.endTime>o);if(m){let p=/'^(?:[a-z]+:)?\/\//i.test(m.text)||(r=a?.querySelector('track[label="thumbnails"]'))==null?void 0:r.src,E=new URL(m.text,p);d=new URLSearchParams(E.hash).get("#xywh").split(",").map(T=>+T),l=E.href;}}let c=s.mediaDuration.get(e),h=(n=s.mediaChaptersCues.get(e).find((f,m,p)=>m===p.length-1&&c===f.endTime?f.startTime<=o&&f.endTime>=o:f.startTime<=o&&f.endTime>o))==null?void 0:n.text;return t!=null&&h==null&&(h=""),{mediaPreviewTime:o,mediaPreviewImage:l,mediaPreviewCoords:d,mediaPreviewChapter:h}},[chunkDITZCOYN_cjs.a.MEDIA_PAUSE_REQUEST](s,e){s["mediaPaused"].set(true,e);},[chunkDITZCOYN_cjs.a.MEDIA_PLAY_REQUEST](s,e){var t,i,r,n;let a="mediaPaused",l=s.mediaStreamType.get(e)===chunkDITZCOYN_cjs.k.LIVE,d=!((t=e.options)!=null&&t.noAutoSeekToLive),c=s.mediaTargetLiveWindow.get(e)>0;if(l&&d&&!c){let u=(i=s.mediaSeekable.get(e))==null?void 0:i[1];if(u){let h=(n=(r=e.options)==null?void 0:r.seekToLiveOffset)!=null?n:0,f=u-h;s.mediaCurrentTime.set(f,e);}}s[a].set(false,e);},[chunkDITZCOYN_cjs.a.MEDIA_PLAYBACK_RATE_REQUEST](s,e,{detail:t}){let i="mediaPlaybackRate",r=t;s[i].set(r,e);},[chunkDITZCOYN_cjs.a.MEDIA_MUTE_REQUEST](s,e){s["mediaMuted"].set(true,e);},[chunkDITZCOYN_cjs.a.MEDIA_UNMUTE_REQUEST](s,e){let t="mediaMuted";s.mediaVolume.get(e)||s.mediaVolume.set(.25,e),s[t].set(false,e);},[chunkDITZCOYN_cjs.a.MEDIA_VOLUME_REQUEST](s,e,{detail:t}){let i="mediaVolume",r=t;r&&s.mediaMuted.get(e)&&s.mediaMuted.set(false,e),s[i].set(r,e);},[chunkDITZCOYN_cjs.a.MEDIA_SEEK_REQUEST](s,e,{detail:t}){let i="mediaCurrentTime",r=t;s[i].set(r,e);},[chunkDITZCOYN_cjs.a.MEDIA_SEEK_TO_LIVE_REQUEST](s,e){var t,i,r;let n="mediaCurrentTime",a=(t=s.mediaSeekable.get(e))==null?void 0:t[1];if(Number.isNaN(Number(a)))return;let o=(r=(i=e.options)==null?void 0:i.seekToLiveOffset)!=null?r:0,l=a-o;s[n].set(l,e);},[chunkDITZCOYN_cjs.a.MEDIA_SHOW_SUBTITLES_REQUEST](s,e,{detail:t}){var i;let{options:r}=e,n=As(e),a=Rl(t),o=(i=a[0])==null?void 0:i.language;o&&!r.noSubtitlesLangPref&&chunkDITZCOYN_cjs.o.localStorage.setItem("media-chrome-pref-subtitles-lang",o),Vi(chunkDITZCOYN_cjs.h.SHOWING,n,a);},[chunkDITZCOYN_cjs.a.MEDIA_DISABLE_SUBTITLES_REQUEST](s,e,{detail:t}){let i=As(e),r=t??[];Vi(chunkDITZCOYN_cjs.h.DISABLED,i,r);},[chunkDITZCOYN_cjs.a.MEDIA_TOGGLE_SUBTITLES_REQUEST](s,e,{detail:t}){Jn(e,t);},[chunkDITZCOYN_cjs.a.MEDIA_RENDITION_REQUEST](s,e,{detail:t}){let i="mediaRenditionSelected",r=t;s[i].set(r,e);},[chunkDITZCOYN_cjs.a.MEDIA_AUDIO_TRACK_REQUEST](s,e,{detail:t}){let i="mediaAudioTrackEnabled",r=t;s[i].set(r,e);},[chunkDITZCOYN_cjs.a.MEDIA_ENTER_PIP_REQUEST](s,e){let t="mediaIsPip";s.mediaIsFullscreen.get(e)&&s.mediaIsFullscreen.set(false,e),s[t].set(true,e);},[chunkDITZCOYN_cjs.a.MEDIA_EXIT_PIP_REQUEST](s,e){s["mediaIsPip"].set(false,e);},[chunkDITZCOYN_cjs.a.MEDIA_ENTER_FULLSCREEN_REQUEST](s,e,t){let i="mediaIsFullscreen";s.mediaIsPip.get(e)&&s.mediaIsPip.set(false,e),s[i].set(true,e,t);},[chunkDITZCOYN_cjs.a.MEDIA_EXIT_FULLSCREEN_REQUEST](s,e){s["mediaIsFullscreen"].set(false,e);},[chunkDITZCOYN_cjs.a.MEDIA_ENTER_CAST_REQUEST](s,e){let t="mediaIsCasting";s.mediaIsFullscreen.get(e)&&s.mediaIsFullscreen.set(false,e),s[t].set(true,e);},[chunkDITZCOYN_cjs.a.MEDIA_EXIT_CAST_REQUEST](s,e){s["mediaIsCasting"].set(false,e);},[chunkDITZCOYN_cjs.a.MEDIA_AIRPLAY_REQUEST](s,e){s["mediaIsAirplaying"].set(true,e);}};var jh=({media:s,fullscreenElement:e,documentElement:t,stateMediator:i=bs,requestMap:r=qh,options:n={},monitorStateOwnersOnlyWithSubscriptions:a=true})=>{let o=[],l={options:{...n}},d=Object.freeze({mediaPreviewTime:void 0,mediaPreviewImage:void 0,mediaPreviewCoords:void 0,mediaPreviewChapter:void 0}),c=p=>{p!=null&&(ea(p,d)||(d=Object.freeze({...d,...p}),o.forEach(E=>E(d))));},u=()=>{let p=Object.entries(i).reduce((E,[v,{get:T}])=>(E[v]=T(l),E),{});c(p);},h={},f,m=async(p,E)=>{var v,T,S,A,b,D,I,k,R,L,M,B,K,j,V,O;let Y=!!f;if(f={...l,...f??{},...p},Y)return;await Yh(...Object.values(p));let $=o.length>0&&E===0&&a,q=l.media!==f.media,Q=((v=l.media)==null?void 0:v.textTracks)!==((T=f.media)==null?void 0:T.textTracks),N=((S=l.media)==null?void 0:S.videoRenditions)!==((A=f.media)==null?void 0:A.videoRenditions),U=((b=l.media)==null?void 0:b.audioTracks)!==((D=f.media)==null?void 0:D.audioTracks),te=((I=l.media)==null?void 0:I.remote)!==((k=f.media)==null?void 0:k.remote),ge=l.documentElement!==f.documentElement,ie=!!l.media&&(q||$),de=!!((R=l.media)!=null&&R.textTracks)&&(Q||$),Be=!!((L=l.media)!=null&&L.videoRenditions)&&(N||$),Fe=!!((M=l.media)!=null&&M.audioTracks)&&(U||$),tt=!!((B=l.media)!=null&&B.remote)&&(te||$),ft=!!l.documentElement&&(ge||$),Kt=ie||de||Be||Fe||tt||ft,Si=o.length===0&&E===1&&a,us=!!f.media&&(q||Si),hs=!!((K=f.media)!=null&&K.textTracks)&&(Q||Si),vl=!!((j=f.media)!=null&&j.videoRenditions)&&(N||Si),fe=!!((V=f.media)!=null&&V.audioTracks)&&(U||Si),$e=!!((O=f.media)!=null&&O.remote)&&(te||Si),it=!!f.documentElement&&(ge||Si),Vt=us||hs||vl||fe||$e||it;if(!(Kt||Vt)){Object.entries(f).forEach(([me,mt])=>{l[me]=mt;}),u(),f=void 0;return}Object.entries(i).forEach(([me,{get:mt,mediaEvents:kn=[],textTracksEvents:fs=[],videoRenditionsEvents:Dn=[],audioTracksEvents:Ui=[],remoteEvents:Cn=[],rootEvents:Tl=[],stateOwnersUpdateHandlers:Mn=[]}])=>{h[me]||(h[me]={});let Ze=Pe=>{let gt=mt(l,Pe);c({[me]:gt});},Ie;Ie=h[me].mediaEvents,kn.forEach(Pe=>{Ie&&ie&&(l.media.removeEventListener(Pe,Ie),h[me].mediaEvents=void 0),us&&(f.media.addEventListener(Pe,Ze),h[me].mediaEvents=Ze);}),Ie=h[me].textTracksEvents,fs.forEach(Pe=>{var gt,Ct;Ie&&de&&((gt=l.media.textTracks)==null||gt.removeEventListener(Pe,Ie),h[me].textTracksEvents=void 0),hs&&((Ct=f.media.textTracks)==null||Ct.addEventListener(Pe,Ze),h[me].textTracksEvents=Ze);}),Ie=h[me].videoRenditionsEvents,Dn.forEach(Pe=>{var gt,Ct;Ie&&Be&&((gt=l.media.videoRenditions)==null||gt.removeEventListener(Pe,Ie),h[me].videoRenditionsEvents=void 0),vl&&((Ct=f.media.videoRenditions)==null||Ct.addEventListener(Pe,Ze),h[me].videoRenditionsEvents=Ze);}),Ie=h[me].audioTracksEvents,Ui.forEach(Pe=>{var gt,Ct;Ie&&Fe&&((gt=l.media.audioTracks)==null||gt.removeEventListener(Pe,Ie),h[me].audioTracksEvents=void 0),fe&&((Ct=f.media.audioTracks)==null||Ct.addEventListener(Pe,Ze),h[me].audioTracksEvents=Ze);}),Ie=h[me].remoteEvents,Cn.forEach(Pe=>{var gt,Ct;Ie&&tt&&((gt=l.media.remote)==null||gt.removeEventListener(Pe,Ie),h[me].remoteEvents=void 0),$e&&((Ct=f.media.remote)==null||Ct.addEventListener(Pe,Ze),h[me].remoteEvents=Ze);}),Ie=h[me].rootEvents,Tl.forEach(Pe=>{Ie&&ft&&(l.documentElement.removeEventListener(Pe,Ie),h[me].rootEvents=void 0),it&&(f.documentElement.addEventListener(Pe,Ze),h[me].rootEvents=Ze);});let nh=h[me].stateOwnersUpdateHandlers;Mn.forEach(Pe=>{nh&&Kt&&nh(),Vt&&(h[me].stateOwnersUpdateHandlers=Pe(Ze,f));});}),Object.entries(f).forEach(([me,mt])=>{l[me]=mt;}),u(),f=void 0;};return m({media:s,fullscreenElement:e,documentElement:t,options:n}),{dispatch(p){let{type:E,detail:v}=p;if(r[E]&&d.mediaErrorCode==null){c(r[E](i,l,p));return}E==="mediaelementchangerequest"?m({media:v}):E==="fullscreenelementchangerequest"?m({fullscreenElement:v}):E==="documentelementchangerequest"?m({documentElement:v}):E==="optionschangerequest"&&(Object.entries(v??{}).forEach(([T,S])=>{l.options[T]=S;}),u());},getState(){return d},subscribe(p){return m({},o.length+1),o.push(p),p(d),()=>{let E=o.indexOf(p);E>=0&&(m({},o.length-1),o.splice(E,1));}}}};var Nl=(s,e,t)=>{if(!e.has(s))throw TypeError("Cannot "+t)},se=(s,e,t)=>(Nl(s,e,"read from private field"),t?t.call(s):e.get(s)),mi=(s,e,t)=>{if(e.has(s))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(s):e.set(s,t);},Li=(s,e,t,i)=>(Nl(s,e,"write to private field"),e.set(s,t),t),xi=(s,e,t)=>(Nl(s,e,"access private method"),t),qi,Er,Ee,vr,Yt,ia,sa,Pl,_s,Tr,ra,wl,ef=["ArrowLeft","ArrowRight","ArrowUp","ArrowDown","Enter"," ","f","m","k","c"],zh=10,Qh=.025,F={DEFAULT_SUBTITLES:"defaultsubtitles",DEFAULT_STREAM_TYPE:"defaultstreamtype",DEFAULT_DURATION:"defaultduration",FULLSCREEN_ELEMENT:"fullscreenelement",HOTKEYS:"hotkeys",KEYS_USED:"keysused",LIVE_EDGE_OFFSET:"liveedgeoffset",SEEK_TO_LIVE_OFFSET:"seektoliveoffset",NO_AUTO_SEEK_TO_LIVE:"noautoseektolive",NO_HOTKEYS:"nohotkeys",NO_VOLUME_PREF:"novolumepref",NO_MUTED_PREF:"nomutedpref",NO_SUBTITLES_LANG_PREF:"nosubtitleslangpref",NO_DEFAULT_STORE:"nodefaultstore",KEYBOARD_FORWARD_SEEK_OFFSET:"keyboardforwardseekoffset",KEYBOARD_BACKWARD_SEEK_OFFSET:"keyboardbackwardseekoffset",KEYBOARD_UP_VOLUME_STEP:"keyboardupvolumestep",KEYBOARD_DOWN_VOLUME_STEP:"keyboarddownvolumestep",LANG:"lang"},Ol=class extends Gi{constructor(){super(),mi(this,sa),mi(this,_s),mi(this,ra),this.mediaStateReceivers=[],this.associatedElementSubscriptions=new Map,mi(this,qi,new Ii(this,F.HOTKEYS)),mi(this,Er,void 0),mi(this,Ee,void 0),mi(this,vr,void 0),mi(this,Yt,void 0),mi(this,ia,t=>{var i;(i=se(this,Ee))==null||i.dispatch(t);}),this.associateElement(this);let e={};Li(this,vr,t=>{Object.entries(t).forEach(([i,r])=>{if(i in e&&e[i]===r)return;this.propagateMediaState(i,r);let n=i.toLowerCase(),a=new chunkDITZCOYN_cjs.o.CustomEvent(chunkDITZCOYN_cjs.f[n],{composed:true,detail:r});this.dispatchEvent(a);}),e=t;}),this.hasAttribute(F.NO_HOTKEYS)?this.disableHotkeys():this.enableHotkeys();}static get observedAttributes(){return super.observedAttributes.concat(F.NO_HOTKEYS,F.HOTKEYS,F.DEFAULT_STREAM_TYPE,F.DEFAULT_SUBTITLES,F.DEFAULT_DURATION,F.NO_MUTED_PREF,F.NO_VOLUME_PREF,F.LANG)}get mediaStore(){return se(this,Ee)}set mediaStore(e){var t,i;if(se(this,Ee)&&((t=se(this,Yt))==null||t.call(this),Li(this,Yt,void 0)),Li(this,Ee,e),!se(this,Ee)&&!this.hasAttribute(F.NO_DEFAULT_STORE)){xi(this,sa,Pl).call(this);return}Li(this,Yt,(i=se(this,Ee))==null?void 0:i.subscribe(se(this,vr)));}get fullscreenElement(){var e;return (e=se(this,Er))!=null?e:this}set fullscreenElement(e){var t;this.hasAttribute(F.FULLSCREEN_ELEMENT)&&this.removeAttribute(F.FULLSCREEN_ELEMENT),Li(this,Er,e),(t=se(this,Ee))==null||t.dispatch({type:"fullscreenelementchangerequest",detail:this.fullscreenElement});}get defaultSubtitles(){return chunkDITZCOYN_cjs.F(this,F.DEFAULT_SUBTITLES)}set defaultSubtitles(e){chunkDITZCOYN_cjs.G(this,F.DEFAULT_SUBTITLES,e);}get defaultStreamType(){return chunkDITZCOYN_cjs.H(this,F.DEFAULT_STREAM_TYPE)}set defaultStreamType(e){chunkDITZCOYN_cjs.I(this,F.DEFAULT_STREAM_TYPE,e);}get defaultDuration(){return chunkDITZCOYN_cjs.D(this,F.DEFAULT_DURATION)}set defaultDuration(e){chunkDITZCOYN_cjs.E(this,F.DEFAULT_DURATION,e);}get noHotkeys(){return chunkDITZCOYN_cjs.F(this,F.NO_HOTKEYS)}set noHotkeys(e){chunkDITZCOYN_cjs.G(this,F.NO_HOTKEYS,e);}get keysUsed(){return chunkDITZCOYN_cjs.H(this,F.KEYS_USED)}set keysUsed(e){chunkDITZCOYN_cjs.I(this,F.KEYS_USED,e);}get liveEdgeOffset(){return chunkDITZCOYN_cjs.D(this,F.LIVE_EDGE_OFFSET)}set liveEdgeOffset(e){chunkDITZCOYN_cjs.E(this,F.LIVE_EDGE_OFFSET,e);}get noAutoSeekToLive(){return chunkDITZCOYN_cjs.F(this,F.NO_AUTO_SEEK_TO_LIVE)}set noAutoSeekToLive(e){chunkDITZCOYN_cjs.G(this,F.NO_AUTO_SEEK_TO_LIVE,e);}get noVolumePref(){return chunkDITZCOYN_cjs.F(this,F.NO_VOLUME_PREF)}set noVolumePref(e){chunkDITZCOYN_cjs.G(this,F.NO_VOLUME_PREF,e);}get noMutedPref(){return chunkDITZCOYN_cjs.F(this,F.NO_MUTED_PREF)}set noMutedPref(e){chunkDITZCOYN_cjs.G(this,F.NO_MUTED_PREF,e);}get noSubtitlesLangPref(){return chunkDITZCOYN_cjs.F(this,F.NO_SUBTITLES_LANG_PREF)}set noSubtitlesLangPref(e){chunkDITZCOYN_cjs.G(this,F.NO_SUBTITLES_LANG_PREF,e);}get noDefaultStore(){return chunkDITZCOYN_cjs.F(this,F.NO_DEFAULT_STORE)}set noDefaultStore(e){chunkDITZCOYN_cjs.G(this,F.NO_DEFAULT_STORE,e);}attributeChangedCallback(e,t,i){var r,n,a,o,l,d,c,u,h,f,m;if(super.attributeChangedCallback(e,t,i),e===F.NO_HOTKEYS)i!==t&&i===""?(this.hasAttribute(F.HOTKEYS)&&console.warn("Media Chrome: Both `hotkeys` and `nohotkeys` have been set. All hotkeys will be disabled."),this.disableHotkeys()):i!==t&&i===null&&this.enableHotkeys();else if(e===F.HOTKEYS)se(this,qi).value=i;else if(e===F.DEFAULT_SUBTITLES&&i!==t)(r=se(this,Ee))==null||r.dispatch({type:"optionschangerequest",detail:{defaultSubtitles:this.hasAttribute(F.DEFAULT_SUBTITLES)}});else if(e===F.DEFAULT_STREAM_TYPE)(a=se(this,Ee))==null||a.dispatch({type:"optionschangerequest",detail:{defaultStreamType:(n=this.getAttribute(F.DEFAULT_STREAM_TYPE))!=null?n:void 0}});else if(e===F.LIVE_EDGE_OFFSET)(o=se(this,Ee))==null||o.dispatch({type:"optionschangerequest",detail:{liveEdgeOffset:this.hasAttribute(F.LIVE_EDGE_OFFSET)?+this.getAttribute(F.LIVE_EDGE_OFFSET):void 0,seekToLiveOffset:this.hasAttribute(F.SEEK_TO_LIVE_OFFSET)?void 0:+this.getAttribute(F.LIVE_EDGE_OFFSET)}});else if(e===F.SEEK_TO_LIVE_OFFSET)(l=se(this,Ee))==null||l.dispatch({type:"optionschangerequest",detail:{seekToLiveOffset:this.hasAttribute(F.SEEK_TO_LIVE_OFFSET)?+this.getAttribute(F.SEEK_TO_LIVE_OFFSET):void 0}});else if(e===F.NO_AUTO_SEEK_TO_LIVE)(d=se(this,Ee))==null||d.dispatch({type:"optionschangerequest",detail:{noAutoSeekToLive:this.hasAttribute(F.NO_AUTO_SEEK_TO_LIVE)}});else if(e===F.FULLSCREEN_ELEMENT){let p=i?(c=this.getRootNode())==null?void 0:c.getElementById(i):void 0;Li(this,Er,p),(u=se(this,Ee))==null||u.dispatch({type:"fullscreenelementchangerequest",detail:this.fullscreenElement});}else e===F.LANG&&i!==t?(chunkDITZCOYN_cjs.m(i),(h=se(this,Ee))==null||h.dispatch({type:"optionschangerequest",detail:{mediaLang:i}})):e===F.NO_VOLUME_PREF&&i!==t?(f=se(this,Ee))==null||f.dispatch({type:"optionschangerequest",detail:{noVolumePref:this.hasAttribute(F.NO_VOLUME_PREF)}}):e===F.NO_MUTED_PREF&&i!==t&&((m=se(this,Ee))==null||m.dispatch({type:"optionschangerequest",detail:{noMutedPref:this.hasAttribute(F.NO_MUTED_PREF)}}));}connectedCallback(){var e,t;!se(this,Ee)&&!this.hasAttribute(F.NO_DEFAULT_STORE)&&xi(this,sa,Pl).call(this),(e=se(this,Ee))==null||e.dispatch({type:"documentelementchangerequest",detail:chunkDITZCOYN_cjs.p}),super.connectedCallback(),se(this,Ee)&&!se(this,Yt)&&Li(this,Yt,(t=se(this,Ee))==null?void 0:t.subscribe(se(this,vr))),this.hasAttribute(F.NO_HOTKEYS)?this.disableHotkeys():this.enableHotkeys();}disconnectedCallback(){var e,t,i,r;(e=super.disconnectedCallback)==null||e.call(this),se(this,Ee)&&((t=se(this,Ee))==null||t.dispatch({type:"documentelementchangerequest",detail:void 0}),(i=se(this,Ee))==null||i.dispatch({type:chunkDITZCOYN_cjs.a.MEDIA_TOGGLE_SUBTITLES_REQUEST,detail:false})),se(this,Yt)&&((r=se(this,Yt))==null||r.call(this),Li(this,Yt,void 0));}mediaSetCallback(e){var t;super.mediaSetCallback(e),(t=se(this,Ee))==null||t.dispatch({type:"mediaelementchangerequest",detail:e}),e.hasAttribute("tabindex")||(e.tabIndex=-1);}mediaUnsetCallback(e){var t;super.mediaUnsetCallback(e),(t=se(this,Ee))==null||t.dispatch({type:"mediaelementchangerequest",detail:void 0});}propagateMediaState(e,t){Jh(this.mediaStateReceivers,e,t);}associateElement(e){if(!e)return;let{associatedElementSubscriptions:t}=this;if(t.has(e))return;let i=this.registerMediaStateReceiver.bind(this),r=this.unregisterMediaStateReceiver.bind(this),n=$0(e,i,r);Object.values(chunkDITZCOYN_cjs.a).forEach(a=>{e.addEventListener(a,se(this,ia));}),t.set(e,n);}unassociateElement(e){if(!e)return;let{associatedElementSubscriptions:t}=this;if(!t.has(e))return;t.get(e)(),t.delete(e),Object.values(chunkDITZCOYN_cjs.a).forEach(r=>{e.removeEventListener(r,se(this,ia));});}registerMediaStateReceiver(e){if(!e)return;let t=this.mediaStateReceivers;t.indexOf(e)>-1||(t.push(e),se(this,Ee)&&Object.entries(se(this,Ee).getState()).forEach(([r,n])=>{Jh([e],r,n);}));}unregisterMediaStateReceiver(e){let t=this.mediaStateReceivers,i=t.indexOf(e);i<0||t.splice(i,1);}enableHotkeys(){this.addEventListener("keydown",xi(this,ra,wl));}disableHotkeys(){this.removeEventListener("keydown",xi(this,ra,wl)),this.removeEventListener("keyup",xi(this,_s,Tr));}get hotkeys(){return chunkDITZCOYN_cjs.H(this,F.HOTKEYS)}set hotkeys(e){chunkDITZCOYN_cjs.I(this,F.HOTKEYS,e);}keyboardShortcutHandler(e){var t,i,r,n,a,o,l;let d=e.target;if(((r=(i=(t=d.getAttribute(F.KEYS_USED))==null?void 0:t.split(" "))!=null?i:d?.keysUsed)!=null?r:[]).map(m=>m==="Space"?" ":m).filter(Boolean).includes(e.key))return;let u,h,f;if(!se(this,qi).contains(`no${e.key.toLowerCase()}`)&&!(e.key===" "&&se(this,qi).contains("nospace")))switch(e.key){case " ":case "k":u=se(this,Ee).getState().mediaPaused?chunkDITZCOYN_cjs.a.MEDIA_PLAY_REQUEST:chunkDITZCOYN_cjs.a.MEDIA_PAUSE_REQUEST,this.dispatchEvent(new chunkDITZCOYN_cjs.o.CustomEvent(u,{composed:true,bubbles:true}));break;case "m":u=this.mediaStore.getState().mediaVolumeLevel==="off"?chunkDITZCOYN_cjs.a.MEDIA_UNMUTE_REQUEST:chunkDITZCOYN_cjs.a.MEDIA_MUTE_REQUEST,this.dispatchEvent(new chunkDITZCOYN_cjs.o.CustomEvent(u,{composed:true,bubbles:true}));break;case "f":u=this.mediaStore.getState().mediaIsFullscreen?chunkDITZCOYN_cjs.a.MEDIA_EXIT_FULLSCREEN_REQUEST:chunkDITZCOYN_cjs.a.MEDIA_ENTER_FULLSCREEN_REQUEST,this.dispatchEvent(new chunkDITZCOYN_cjs.o.CustomEvent(u,{composed:true,bubbles:true}));break;case "c":this.dispatchEvent(new chunkDITZCOYN_cjs.o.CustomEvent(chunkDITZCOYN_cjs.a.MEDIA_TOGGLE_SUBTITLES_REQUEST,{composed:true,bubbles:true}));break;case "ArrowLeft":{let m=this.hasAttribute(F.KEYBOARD_BACKWARD_SEEK_OFFSET)?+this.getAttribute(F.KEYBOARD_BACKWARD_SEEK_OFFSET):zh;h=Math.max(((n=this.mediaStore.getState().mediaCurrentTime)!=null?n:0)-m,0),f=new chunkDITZCOYN_cjs.o.CustomEvent(chunkDITZCOYN_cjs.a.MEDIA_SEEK_REQUEST,{composed:true,bubbles:true,detail:h}),this.dispatchEvent(f);break}case "ArrowRight":{let m=this.hasAttribute(F.KEYBOARD_FORWARD_SEEK_OFFSET)?+this.getAttribute(F.KEYBOARD_FORWARD_SEEK_OFFSET):zh;h=Math.max(((a=this.mediaStore.getState().mediaCurrentTime)!=null?a:0)+m,0),f=new chunkDITZCOYN_cjs.o.CustomEvent(chunkDITZCOYN_cjs.a.MEDIA_SEEK_REQUEST,{composed:true,bubbles:true,detail:h}),this.dispatchEvent(f);break}case "ArrowUp":{let m=this.hasAttribute(F.KEYBOARD_UP_VOLUME_STEP)?+this.getAttribute(F.KEYBOARD_UP_VOLUME_STEP):Qh;h=Math.min(((o=this.mediaStore.getState().mediaVolume)!=null?o:1)+m,1),f=new chunkDITZCOYN_cjs.o.CustomEvent(chunkDITZCOYN_cjs.a.MEDIA_VOLUME_REQUEST,{composed:true,bubbles:true,detail:h}),this.dispatchEvent(f);break}case "ArrowDown":{let m=this.hasAttribute(F.KEYBOARD_DOWN_VOLUME_STEP)?+this.getAttribute(F.KEYBOARD_DOWN_VOLUME_STEP):Qh;h=Math.max(((l=this.mediaStore.getState().mediaVolume)!=null?l:1)-m,0),f=new chunkDITZCOYN_cjs.o.CustomEvent(chunkDITZCOYN_cjs.a.MEDIA_VOLUME_REQUEST,{composed:true,bubbles:true,detail:h}),this.dispatchEvent(f);break}}}};qi=new WeakMap;Er=new WeakMap;Ee=new WeakMap;vr=new WeakMap;Yt=new WeakMap;ia=new WeakMap;sa=new WeakSet;Pl=function(){var s;this.mediaStore=jh({media:this.media,fullscreenElement:this.fullscreenElement,options:{defaultSubtitles:this.hasAttribute(F.DEFAULT_SUBTITLES),defaultDuration:this.hasAttribute(F.DEFAULT_DURATION)?+this.getAttribute(F.DEFAULT_DURATION):void 0,defaultStreamType:(s=this.getAttribute(F.DEFAULT_STREAM_TYPE))!=null?s:void 0,liveEdgeOffset:this.hasAttribute(F.LIVE_EDGE_OFFSET)?+this.getAttribute(F.LIVE_EDGE_OFFSET):void 0,seekToLiveOffset:this.hasAttribute(F.SEEK_TO_LIVE_OFFSET)?+this.getAttribute(F.SEEK_TO_LIVE_OFFSET):this.hasAttribute(F.LIVE_EDGE_OFFSET)?+this.getAttribute(F.LIVE_EDGE_OFFSET):void 0,noAutoSeekToLive:this.hasAttribute(F.NO_AUTO_SEEK_TO_LIVE),noVolumePref:this.hasAttribute(F.NO_VOLUME_PREF),noMutedPref:this.hasAttribute(F.NO_MUTED_PREF),noSubtitlesLangPref:this.hasAttribute(F.NO_SUBTITLES_LANG_PREF)}});};_s=new WeakSet;Tr=function(s){let{key:e}=s;if(!ef.includes(e)){this.removeEventListener("keyup",xi(this,_s,Tr));return}this.keyboardShortcutHandler(s);};ra=new WeakSet;wl=function(s){let{metaKey:e,altKey:t,key:i}=s;if(e||t||!ef.includes(i)){this.removeEventListener("keyup",xi(this,_s,Tr));return}let r=s.target,n=r instanceof HTMLElement&&(r.tagName.toLowerCase()==="media-volume-range"||r.tagName.toLowerCase()==="media-time-range");[" ","ArrowLeft","ArrowRight","ArrowUp","ArrowDown"].includes(i)&&!(se(this,qi).contains(`no${i.toLowerCase()}`)||i===" "&&se(this,qi).contains("nospace"))&&!n&&s.preventDefault(),this.addEventListener("keyup",xi(this,_s,Tr),{once:true});};var O0=Object.values(chunkDITZCOYN_cjs.d),F0=Object.values(chunkDITZCOYN_cjs.c),tf=s=>{var e,t,i,r;let{observedAttributes:n}=s.constructor;!n&&((e=s.nodeName)!=null&&e.includes("-"))&&(chunkDITZCOYN_cjs.o.customElements.upgrade(s),{observedAttributes:n}=s.constructor);let a=(r=(i=(t=s?.getAttribute)==null?void 0:t.call(s,chunkDITZCOYN_cjs.b.MEDIA_CHROME_ATTRIBUTES))==null?void 0:i.split)==null?void 0:r.call(i,/\s+/);return Array.isArray(n||a)?(n||a).filter(o=>O0.includes(o)):[]},N0=s=>{var e,t;return (e=s.nodeName)!=null&&e.includes("-")&&chunkDITZCOYN_cjs.o.customElements.get((t=s.nodeName)==null?void 0:t.toLowerCase())&&!(s instanceof chunkDITZCOYN_cjs.o.customElements.get(s.nodeName.toLowerCase()))&&chunkDITZCOYN_cjs.o.customElements.upgrade(s),F0.some(i=>i in s)},Fl=s=>N0(s)||!!tf(s).length,Xh=s=>{var e;return (e=s?.join)==null?void 0:e.call(s,":")},Zh={[chunkDITZCOYN_cjs.d.MEDIA_SUBTITLES_LIST]:fi,[chunkDITZCOYN_cjs.d.MEDIA_SUBTITLES_SHOWING]:fi,[chunkDITZCOYN_cjs.d.MEDIA_SEEKABLE]:Xh,[chunkDITZCOYN_cjs.d.MEDIA_BUFFERED]:s=>s?.map(Xh).join(" "),[chunkDITZCOYN_cjs.d.MEDIA_PREVIEW_COORDS]:s=>s?.join(" "),[chunkDITZCOYN_cjs.d.MEDIA_RENDITION_LIST]:bh,[chunkDITZCOYN_cjs.d.MEDIA_AUDIO_TRACK_LIST]:Ih},U0=async(s,e,t)=>{var i,r;if(s.isConnected||await $n(0),typeof t=="boolean"||t==null)return chunkDITZCOYN_cjs.G(s,e,t);if(typeof t=="number")return chunkDITZCOYN_cjs.E(s,e,t);if(typeof t=="string")return chunkDITZCOYN_cjs.I(s,e,t);if(Array.isArray(t)&&!t.length)return s.removeAttribute(e);let n=(r=(i=Zh[e])==null?void 0:i.call(Zh,t))!=null?r:t;return s.setAttribute(e,n)},B0=s=>{var e;return !!((e=s.closest)!=null&&e.call(s,'*[slot="media"]'))},Yi=(s,e)=>{if(B0(s))return;let t=(r,n)=>{var a,o;Fl(r)&&n(r);let{children:l=[]}=r??{},d=(o=(a=r?.shadowRoot)==null?void 0:a.children)!=null?o:[];[...l,...d].forEach(u=>Yi(u,n));},i=s?.nodeName.toLowerCase();if(i.includes("-")&&!Fl(s)){chunkDITZCOYN_cjs.o.customElements.whenDefined(i).then(()=>{t(s,e);});return}t(s,e);},Jh=(s,e,t)=>{s.forEach(i=>{if(e in i){i[e]=t;return}let r=tf(i),n=e.toLowerCase();r.includes(n)&&U0(i,n,t);});},$0=(s,e,t)=>{Yi(s,e);let i=c=>{var u;let h=(u=c?.composedPath()[0])!=null?u:c.target;e(h);},r=c=>{var u;let h=(u=c?.composedPath()[0])!=null?u:c.target;t(h);};s.addEventListener(chunkDITZCOYN_cjs.a.REGISTER_MEDIA_STATE_RECEIVER,i),s.addEventListener(chunkDITZCOYN_cjs.a.UNREGISTER_MEDIA_STATE_RECEIVER,r);let n=c=>{c.forEach(u=>{let{addedNodes:h=[],removedNodes:f=[],type:m,target:p,attributeName:E}=u;m==="childList"?(Array.prototype.forEach.call(h,v=>Yi(v,e)),Array.prototype.forEach.call(f,v=>Yi(v,t))):m==="attributes"&&E===chunkDITZCOYN_cjs.b.MEDIA_CHROME_ATTRIBUTES&&(Fl(p)?e(p):t(p));});},a=[],o=c=>{let u=c.target;u.name!=="media"&&(a.forEach(h=>Yi(h,t)),a=[...u.assignedElements({flatten:true})],a.forEach(h=>Yi(h,e)));};s.addEventListener("slotchange",o);let l=new MutationObserver(n);return l.observe(s,{childList:true,attributes:true,subtree:true}),()=>{Yi(s,t),s.removeEventListener("slotchange",o),l.disconnect(),s.removeEventListener(chunkDITZCOYN_cjs.a.REGISTER_MEDIA_STATE_RECEIVER,i),s.removeEventListener(chunkDITZCOYN_cjs.a.UNREGISTER_MEDIA_STATE_RECEIVER,r);}};chunkDITZCOYN_cjs.o.customElements.get("media-controller")||chunkDITZCOYN_cjs.o.customElements.define("media-controller",Ol);var sf=`<svg aria-hidden="true" viewBox="0 0 26 24">
160
160
  <path d="M22.13 3H3.87a.87.87 0 0 0-.87.87v13.26a.87.87 0 0 0 .87.87h3.4L9 16H5V5h16v11h-4l1.72 2h3.4a.87.87 0 0 0 .87-.87V3.87a.87.87 0 0 0-.86-.87Zm-8.75 11.44a.5.5 0 0 0-.76 0l-4.91 5.73a.5.5 0 0 0 .38.83h9.82a.501.501 0 0 0 .38-.83l-4.91-5.73Z"/>
161
161
  </svg>
162
- `;function $0(s){return `
162
+ `;function G0(s){return `
163
163
  <style>
164
164
  :host([${chunkDITZCOYN_cjs.d.MEDIA_IS_AIRPLAYING}]) slot[name=icon] slot:not([name=exit]) {
165
165
  display: none !important;
@@ -177,17 +177,17 @@
177
177
  </style>
178
178
 
179
179
  <slot name="icon">
180
- <slot name="enter">${tf}</slot>
181
- <slot name="exit">${tf}</slot>
180
+ <slot name="enter">${sf}</slot>
181
+ <slot name="exit">${sf}</slot>
182
182
  </slot>
183
- `}function G0(){return `
183
+ `}function H0(){return `
184
184
  <slot name="tooltip-enter">${chunkDITZCOYN_cjs.n("start airplay")}</slot>
185
185
  <slot name="tooltip-exit">${chunkDITZCOYN_cjs.n("stop airplay")}</slot>
186
- `}var sf=s=>{let e=s.mediaIsAirplaying?chunkDITZCOYN_cjs.n("stop airplay"):chunkDITZCOYN_cjs.n("start airplay");s.setAttribute("aria-label",e);},yr=class extends chunkDITZCOYN_cjs.J{static get observedAttributes(){return [...super.observedAttributes,chunkDITZCOYN_cjs.d.MEDIA_IS_AIRPLAYING,chunkDITZCOYN_cjs.d.MEDIA_AIRPLAY_UNAVAILABLE]}connectedCallback(){super.connectedCallback(),sf(this);}attributeChangedCallback(e,t,i){super.attributeChangedCallback(e,t,i),e===chunkDITZCOYN_cjs.d.MEDIA_IS_AIRPLAYING&&sf(this);}get mediaIsAirplaying(){return chunkDITZCOYN_cjs.F(this,chunkDITZCOYN_cjs.d.MEDIA_IS_AIRPLAYING)}set mediaIsAirplaying(e){chunkDITZCOYN_cjs.G(this,chunkDITZCOYN_cjs.d.MEDIA_IS_AIRPLAYING,e);}get mediaAirplayUnavailable(){return chunkDITZCOYN_cjs.H(this,chunkDITZCOYN_cjs.d.MEDIA_AIRPLAY_UNAVAILABLE)}set mediaAirplayUnavailable(e){chunkDITZCOYN_cjs.I(this,chunkDITZCOYN_cjs.d.MEDIA_AIRPLAY_UNAVAILABLE,e);}handleClick(){let e=new chunkDITZCOYN_cjs.o.CustomEvent(chunkDITZCOYN_cjs.a.MEDIA_AIRPLAY_REQUEST,{composed:true,bubbles:true});this.dispatchEvent(e);}};yr.getSlotTemplateHTML=$0;yr.getTooltipContentHTML=G0;chunkDITZCOYN_cjs.o.customElements.get("media-airplay-button")||chunkDITZCOYN_cjs.o.customElements.define("media-airplay-button",yr);var H0=`<svg aria-hidden="true" viewBox="0 0 26 24">
186
+ `}var rf=s=>{let e=s.mediaIsAirplaying?chunkDITZCOYN_cjs.n("stop airplay"):chunkDITZCOYN_cjs.n("start airplay");s.setAttribute("aria-label",e);},yr=class extends chunkDITZCOYN_cjs.J{static get observedAttributes(){return [...super.observedAttributes,chunkDITZCOYN_cjs.d.MEDIA_IS_AIRPLAYING,chunkDITZCOYN_cjs.d.MEDIA_AIRPLAY_UNAVAILABLE]}connectedCallback(){super.connectedCallback(),rf(this);}attributeChangedCallback(e,t,i){super.attributeChangedCallback(e,t,i),e===chunkDITZCOYN_cjs.d.MEDIA_IS_AIRPLAYING&&rf(this);}get mediaIsAirplaying(){return chunkDITZCOYN_cjs.F(this,chunkDITZCOYN_cjs.d.MEDIA_IS_AIRPLAYING)}set mediaIsAirplaying(e){chunkDITZCOYN_cjs.G(this,chunkDITZCOYN_cjs.d.MEDIA_IS_AIRPLAYING,e);}get mediaAirplayUnavailable(){return chunkDITZCOYN_cjs.H(this,chunkDITZCOYN_cjs.d.MEDIA_AIRPLAY_UNAVAILABLE)}set mediaAirplayUnavailable(e){chunkDITZCOYN_cjs.I(this,chunkDITZCOYN_cjs.d.MEDIA_AIRPLAY_UNAVAILABLE,e);}handleClick(){let e=new chunkDITZCOYN_cjs.o.CustomEvent(chunkDITZCOYN_cjs.a.MEDIA_AIRPLAY_REQUEST,{composed:true,bubbles:true});this.dispatchEvent(e);}};yr.getSlotTemplateHTML=G0;yr.getTooltipContentHTML=H0;chunkDITZCOYN_cjs.o.customElements.get("media-airplay-button")||chunkDITZCOYN_cjs.o.customElements.define("media-airplay-button",yr);var K0=`<svg aria-hidden="true" viewBox="0 0 26 24">
187
187
  <path d="M22.83 5.68a2.58 2.58 0 0 0-2.3-2.5c-3.62-.24-11.44-.24-15.06 0a2.58 2.58 0 0 0-2.3 2.5c-.23 4.21-.23 8.43 0 12.64a2.58 2.58 0 0 0 2.3 2.5c3.62.24 11.44.24 15.06 0a2.58 2.58 0 0 0 2.3-2.5c.23-4.21.23-8.43 0-12.64Zm-11.39 9.45a3.07 3.07 0 0 1-1.91.57 3.06 3.06 0 0 1-2.34-1 3.75 3.75 0 0 1-.92-2.67 3.92 3.92 0 0 1 .92-2.77 3.18 3.18 0 0 1 2.43-1 2.94 2.94 0 0 1 2.13.78c.364.359.62.813.74 1.31l-1.43.35a1.49 1.49 0 0 0-1.51-1.17 1.61 1.61 0 0 0-1.29.58 2.79 2.79 0 0 0-.5 1.89 3 3 0 0 0 .49 1.93 1.61 1.61 0 0 0 1.27.58 1.48 1.48 0 0 0 1-.37 2.1 2.1 0 0 0 .59-1.14l1.4.44a3.23 3.23 0 0 1-1.07 1.69Zm7.22 0a3.07 3.07 0 0 1-1.91.57 3.06 3.06 0 0 1-2.34-1 3.75 3.75 0 0 1-.92-2.67 3.88 3.88 0 0 1 .93-2.77 3.14 3.14 0 0 1 2.42-1 3 3 0 0 1 2.16.82 2.8 2.8 0 0 1 .73 1.31l-1.43.35a1.49 1.49 0 0 0-1.51-1.21 1.61 1.61 0 0 0-1.29.58A2.79 2.79 0 0 0 15 12a3 3 0 0 0 .49 1.93 1.61 1.61 0 0 0 1.27.58 1.44 1.44 0 0 0 1-.37 2.1 2.1 0 0 0 .6-1.15l1.4.44a3.17 3.17 0 0 1-1.1 1.7Z"/>
188
- </svg>`,K0=`<svg aria-hidden="true" viewBox="0 0 26 24">
188
+ </svg>`,V0=`<svg aria-hidden="true" viewBox="0 0 26 24">
189
189
  <path d="M17.73 14.09a1.4 1.4 0 0 1-1 .37 1.579 1.579 0 0 1-1.27-.58A3 3 0 0 1 15 12a2.8 2.8 0 0 1 .5-1.85 1.63 1.63 0 0 1 1.29-.57 1.47 1.47 0 0 1 1.51 1.2l1.43-.34A2.89 2.89 0 0 0 19 9.07a3 3 0 0 0-2.14-.78 3.14 3.14 0 0 0-2.42 1 3.91 3.91 0 0 0-.93 2.78 3.74 3.74 0 0 0 .92 2.66 3.07 3.07 0 0 0 2.34 1 3.07 3.07 0 0 0 1.91-.57 3.17 3.17 0 0 0 1.07-1.74l-1.4-.45c-.083.43-.3.822-.62 1.12Zm-7.22 0a1.43 1.43 0 0 1-1 .37 1.58 1.58 0 0 1-1.27-.58A3 3 0 0 1 7.76 12a2.8 2.8 0 0 1 .5-1.85 1.63 1.63 0 0 1 1.29-.57 1.47 1.47 0 0 1 1.51 1.2l1.43-.34a2.81 2.81 0 0 0-.74-1.32 2.94 2.94 0 0 0-2.13-.78 3.18 3.18 0 0 0-2.43 1 4 4 0 0 0-.92 2.78 3.74 3.74 0 0 0 .92 2.66 3.07 3.07 0 0 0 2.34 1 3.07 3.07 0 0 0 1.91-.57 3.23 3.23 0 0 0 1.07-1.74l-1.4-.45a2.06 2.06 0 0 1-.6 1.07Zm12.32-8.41a2.59 2.59 0 0 0-2.3-2.51C18.72 3.05 15.86 3 13 3c-2.86 0-5.72.05-7.53.17a2.59 2.59 0 0 0-2.3 2.51c-.23 4.207-.23 8.423 0 12.63a2.57 2.57 0 0 0 2.3 2.5c1.81.13 4.67.19 7.53.19 2.86 0 5.72-.06 7.53-.19a2.57 2.57 0 0 0 2.3-2.5c.23-4.207.23-8.423 0-12.63Zm-1.49 12.53a1.11 1.11 0 0 1-.91 1.11c-1.67.11-4.45.18-7.43.18-2.98 0-5.76-.07-7.43-.18a1.11 1.11 0 0 1-.91-1.11c-.21-4.14-.21-8.29 0-12.43a1.11 1.11 0 0 1 .91-1.11C7.24 4.56 10 4.49 13 4.49s5.76.07 7.43.18a1.11 1.11 0 0 1 .91 1.11c.21 4.14.21 8.29 0 12.43Z"/>
190
- </svg>`;function V0(s){return `
190
+ </svg>`;function W0(s){return `
191
191
  <style>
192
192
  :host([aria-checked="true"]) slot[name=off] {
193
193
  display: none !important;
@@ -205,13 +205,13 @@
205
205
  </style>
206
206
 
207
207
  <slot name="icon">
208
- <slot name="on">${H0}</slot>
209
- <slot name="off">${K0}</slot>
208
+ <slot name="on">${K0}</slot>
209
+ <slot name="off">${V0}</slot>
210
210
  </slot>
211
- `}function W0(){return `
211
+ `}function Y0(){return `
212
212
  <slot name="tooltip-enable">${chunkDITZCOYN_cjs.n("Enable captions")}</slot>
213
213
  <slot name="tooltip-disable">${chunkDITZCOYN_cjs.n("Disable captions")}</slot>
214
- `}var rf=s=>{s.setAttribute("aria-checked",Xn(s).toString());},Sr=class extends chunkDITZCOYN_cjs.J{static get observedAttributes(){return [...super.observedAttributes,chunkDITZCOYN_cjs.d.MEDIA_SUBTITLES_LIST,chunkDITZCOYN_cjs.d.MEDIA_SUBTITLES_SHOWING]}connectedCallback(){super.connectedCallback(),this.setAttribute("role","switch"),this.setAttribute("aria-label",chunkDITZCOYN_cjs.n("closed captions")),rf(this);}attributeChangedCallback(e,t,i){super.attributeChangedCallback(e,t,i),e===chunkDITZCOYN_cjs.d.MEDIA_SUBTITLES_SHOWING&&rf(this);}get mediaSubtitlesList(){return nf(this,chunkDITZCOYN_cjs.d.MEDIA_SUBTITLES_LIST)}set mediaSubtitlesList(e){af(this,chunkDITZCOYN_cjs.d.MEDIA_SUBTITLES_LIST,e);}get mediaSubtitlesShowing(){return nf(this,chunkDITZCOYN_cjs.d.MEDIA_SUBTITLES_SHOWING)}set mediaSubtitlesShowing(e){af(this,chunkDITZCOYN_cjs.d.MEDIA_SUBTITLES_SHOWING,e);}handleClick(){this.dispatchEvent(new chunkDITZCOYN_cjs.o.CustomEvent(chunkDITZCOYN_cjs.a.MEDIA_TOGGLE_SUBTITLES_REQUEST,{composed:true,bubbles:true}));}};Sr.getSlotTemplateHTML=V0;Sr.getTooltipContentHTML=W0;var nf=(s,e)=>{let t=s.getAttribute(e);return t?Ki(t):[]},af=(s,e,t)=>{if(!t?.length){s.removeAttribute(e);return}let i=fi(t);s.getAttribute(e)!==i&&s.setAttribute(e,i);};chunkDITZCOYN_cjs.o.customElements.get("media-captions-button")||chunkDITZCOYN_cjs.o.customElements.define("media-captions-button",Sr);var Y0='<svg aria-hidden="true" viewBox="0 0 24 24"><g><path class="cast_caf_icon_arch0" d="M1,18 L1,21 L4,21 C4,19.3 2.66,18 1,18 L1,18 Z"/><path class="cast_caf_icon_arch1" d="M1,14 L1,16 C3.76,16 6,18.2 6,21 L8,21 C8,17.13 4.87,14 1,14 L1,14 Z"/><path class="cast_caf_icon_arch2" d="M1,10 L1,12 C5.97,12 10,16.0 10,21 L12,21 C12,14.92 7.07,10 1,10 L1,10 Z"/><path class="cast_caf_icon_box" d="M21,3 L3,3 C1.9,3 1,3.9 1,5 L1,8 L3,8 L3,5 L21,5 L21,19 L14,19 L14,21 L21,21 C22.1,21 23,20.1 23,19 L23,5 C23,3.9 22.1,3 21,3 L21,3 Z"/></g></svg>',q0='<svg aria-hidden="true" viewBox="0 0 24 24"><g><path class="cast_caf_icon_arch0" d="M1,18 L1,21 L4,21 C4,19.3 2.66,18 1,18 L1,18 Z"/><path class="cast_caf_icon_arch1" d="M1,14 L1,16 C3.76,16 6,18.2 6,21 L8,21 C8,17.13 4.87,14 1,14 L1,14 Z"/><path class="cast_caf_icon_arch2" d="M1,10 L1,12 C5.97,12 10,16.0 10,21 L12,21 C12,14.92 7.07,10 1,10 L1,10 Z"/><path class="cast_caf_icon_box" d="M21,3 L3,3 C1.9,3 1,3.9 1,5 L1,8 L3,8 L3,5 L21,5 L21,19 L14,19 L14,21 L21,21 C22.1,21 23,20.1 23,19 L23,5 C23,3.9 22.1,3 21,3 L21,3 Z"/><path class="cast_caf_icon_boxfill" d="M5,7 L5,8.63 C8,8.6 13.37,14 13.37,17 L19,17 L19,7 Z"/></g></svg>';function j0(s){return `
214
+ `}var nf=s=>{s.setAttribute("aria-checked",Xn(s).toString());},Sr=class extends chunkDITZCOYN_cjs.J{static get observedAttributes(){return [...super.observedAttributes,chunkDITZCOYN_cjs.d.MEDIA_SUBTITLES_LIST,chunkDITZCOYN_cjs.d.MEDIA_SUBTITLES_SHOWING]}connectedCallback(){super.connectedCallback(),this.setAttribute("role","switch"),this.setAttribute("aria-label",chunkDITZCOYN_cjs.n("closed captions")),nf(this);}attributeChangedCallback(e,t,i){super.attributeChangedCallback(e,t,i),e===chunkDITZCOYN_cjs.d.MEDIA_SUBTITLES_SHOWING&&nf(this);}get mediaSubtitlesList(){return af(this,chunkDITZCOYN_cjs.d.MEDIA_SUBTITLES_LIST)}set mediaSubtitlesList(e){of(this,chunkDITZCOYN_cjs.d.MEDIA_SUBTITLES_LIST,e);}get mediaSubtitlesShowing(){return af(this,chunkDITZCOYN_cjs.d.MEDIA_SUBTITLES_SHOWING)}set mediaSubtitlesShowing(e){of(this,chunkDITZCOYN_cjs.d.MEDIA_SUBTITLES_SHOWING,e);}handleClick(){this.dispatchEvent(new chunkDITZCOYN_cjs.o.CustomEvent(chunkDITZCOYN_cjs.a.MEDIA_TOGGLE_SUBTITLES_REQUEST,{composed:true,bubbles:true}));}};Sr.getSlotTemplateHTML=W0;Sr.getTooltipContentHTML=Y0;var af=(s,e)=>{let t=s.getAttribute(e);return t?Ki(t):[]},of=(s,e,t)=>{if(!t?.length){s.removeAttribute(e);return}let i=fi(t);s.getAttribute(e)!==i&&s.setAttribute(e,i);};chunkDITZCOYN_cjs.o.customElements.get("media-captions-button")||chunkDITZCOYN_cjs.o.customElements.define("media-captions-button",Sr);var q0='<svg aria-hidden="true" viewBox="0 0 24 24"><g><path class="cast_caf_icon_arch0" d="M1,18 L1,21 L4,21 C4,19.3 2.66,18 1,18 L1,18 Z"/><path class="cast_caf_icon_arch1" d="M1,14 L1,16 C3.76,16 6,18.2 6,21 L8,21 C8,17.13 4.87,14 1,14 L1,14 Z"/><path class="cast_caf_icon_arch2" d="M1,10 L1,12 C5.97,12 10,16.0 10,21 L12,21 C12,14.92 7.07,10 1,10 L1,10 Z"/><path class="cast_caf_icon_box" d="M21,3 L3,3 C1.9,3 1,3.9 1,5 L1,8 L3,8 L3,5 L21,5 L21,19 L14,19 L14,21 L21,21 C22.1,21 23,20.1 23,19 L23,5 C23,3.9 22.1,3 21,3 L21,3 Z"/></g></svg>',j0='<svg aria-hidden="true" viewBox="0 0 24 24"><g><path class="cast_caf_icon_arch0" d="M1,18 L1,21 L4,21 C4,19.3 2.66,18 1,18 L1,18 Z"/><path class="cast_caf_icon_arch1" d="M1,14 L1,16 C3.76,16 6,18.2 6,21 L8,21 C8,17.13 4.87,14 1,14 L1,14 Z"/><path class="cast_caf_icon_arch2" d="M1,10 L1,12 C5.97,12 10,16.0 10,21 L12,21 C12,14.92 7.07,10 1,10 L1,10 Z"/><path class="cast_caf_icon_box" d="M21,3 L3,3 C1.9,3 1,3.9 1,5 L1,8 L3,8 L3,5 L21,5 L21,19 L14,19 L14,21 L21,21 C22.1,21 23,20.1 23,19 L23,5 C23,3.9 22.1,3 21,3 L21,3 Z"/><path class="cast_caf_icon_boxfill" d="M5,7 L5,8.63 C8,8.6 13.37,14 13.37,17 L19,17 L19,7 Z"/></g></svg>';function z0(s){return `
215
215
  <style>
216
216
  :host([${chunkDITZCOYN_cjs.d.MEDIA_IS_CASTING}]) slot[name=icon] slot:not([name=exit]) {
217
217
  display: none !important;
@@ -229,13 +229,13 @@
229
229
  </style>
230
230
 
231
231
  <slot name="icon">
232
- <slot name="enter">${Y0}</slot>
233
- <slot name="exit">${q0}</slot>
232
+ <slot name="enter">${q0}</slot>
233
+ <slot name="exit">${j0}</slot>
234
234
  </slot>
235
- `}function z0(){return `
235
+ `}function Q0(){return `
236
236
  <slot name="tooltip-enter">${chunkDITZCOYN_cjs.n("Start casting")}</slot>
237
237
  <slot name="tooltip-exit">${chunkDITZCOYN_cjs.n("Stop casting")}</slot>
238
- `}var of=s=>{let e=s.mediaIsCasting?chunkDITZCOYN_cjs.n("stop casting"):chunkDITZCOYN_cjs.n("start casting");s.setAttribute("aria-label",e);},Ar=class extends chunkDITZCOYN_cjs.J{static get observedAttributes(){return [...super.observedAttributes,chunkDITZCOYN_cjs.d.MEDIA_IS_CASTING,chunkDITZCOYN_cjs.d.MEDIA_CAST_UNAVAILABLE]}connectedCallback(){super.connectedCallback(),of(this);}attributeChangedCallback(e,t,i){super.attributeChangedCallback(e,t,i),e===chunkDITZCOYN_cjs.d.MEDIA_IS_CASTING&&of(this);}get mediaIsCasting(){return chunkDITZCOYN_cjs.F(this,chunkDITZCOYN_cjs.d.MEDIA_IS_CASTING)}set mediaIsCasting(e){chunkDITZCOYN_cjs.G(this,chunkDITZCOYN_cjs.d.MEDIA_IS_CASTING,e);}get mediaCastUnavailable(){return chunkDITZCOYN_cjs.H(this,chunkDITZCOYN_cjs.d.MEDIA_CAST_UNAVAILABLE)}set mediaCastUnavailable(e){chunkDITZCOYN_cjs.I(this,chunkDITZCOYN_cjs.d.MEDIA_CAST_UNAVAILABLE,e);}handleClick(){let e=this.mediaIsCasting?chunkDITZCOYN_cjs.a.MEDIA_EXIT_CAST_REQUEST:chunkDITZCOYN_cjs.a.MEDIA_ENTER_CAST_REQUEST;this.dispatchEvent(new chunkDITZCOYN_cjs.o.CustomEvent(e,{composed:true,bubbles:true}));}};Ar.getSlotTemplateHTML=j0;Ar.getTooltipContentHTML=z0;chunkDITZCOYN_cjs.o.customElements.get("media-cast-button")||chunkDITZCOYN_cjs.o.customElements.define("media-cast-button",Ar);var Vl=(s,e,t)=>{if(!e.has(s))throw TypeError("Cannot "+t)},zi=(s,e,t)=>(Vl(s,e,"read from private field"),e.get(s)),gi=(s,e,t)=>{if(e.has(s))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(s):e.set(s,t);},Wl=(s,e,t,i)=>(Vl(s,e,"write to private field"),e.set(s,t),t),ji=(s,e,t)=>(Vl(s,e,"access private method"),t),aa,_r,Qi,na,Ul,Bl,lf,$l,df,Gl,cf,Hl,uf,Kl,hf;function Q0(s){return `
238
+ `}var lf=s=>{let e=s.mediaIsCasting?chunkDITZCOYN_cjs.n("stop casting"):chunkDITZCOYN_cjs.n("start casting");s.setAttribute("aria-label",e);},Ar=class extends chunkDITZCOYN_cjs.J{static get observedAttributes(){return [...super.observedAttributes,chunkDITZCOYN_cjs.d.MEDIA_IS_CASTING,chunkDITZCOYN_cjs.d.MEDIA_CAST_UNAVAILABLE]}connectedCallback(){super.connectedCallback(),lf(this);}attributeChangedCallback(e,t,i){super.attributeChangedCallback(e,t,i),e===chunkDITZCOYN_cjs.d.MEDIA_IS_CASTING&&lf(this);}get mediaIsCasting(){return chunkDITZCOYN_cjs.F(this,chunkDITZCOYN_cjs.d.MEDIA_IS_CASTING)}set mediaIsCasting(e){chunkDITZCOYN_cjs.G(this,chunkDITZCOYN_cjs.d.MEDIA_IS_CASTING,e);}get mediaCastUnavailable(){return chunkDITZCOYN_cjs.H(this,chunkDITZCOYN_cjs.d.MEDIA_CAST_UNAVAILABLE)}set mediaCastUnavailable(e){chunkDITZCOYN_cjs.I(this,chunkDITZCOYN_cjs.d.MEDIA_CAST_UNAVAILABLE,e);}handleClick(){let e=this.mediaIsCasting?chunkDITZCOYN_cjs.a.MEDIA_EXIT_CAST_REQUEST:chunkDITZCOYN_cjs.a.MEDIA_ENTER_CAST_REQUEST;this.dispatchEvent(new chunkDITZCOYN_cjs.o.CustomEvent(e,{composed:true,bubbles:true}));}};Ar.getSlotTemplateHTML=z0;Ar.getTooltipContentHTML=Q0;chunkDITZCOYN_cjs.o.customElements.get("media-cast-button")||chunkDITZCOYN_cjs.o.customElements.define("media-cast-button",Ar);var Vl=(s,e,t)=>{if(!e.has(s))throw TypeError("Cannot "+t)},zi=(s,e,t)=>(Vl(s,e,"read from private field"),e.get(s)),gi=(s,e,t)=>{if(e.has(s))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(s):e.set(s,t);},Wl=(s,e,t,i)=>(Vl(s,e,"write to private field"),e.set(s,t),t),ji=(s,e,t)=>(Vl(s,e,"access private method"),t),aa,_r,Qi,na,Ul,Bl,df,$l,cf,Gl,uf,Hl,hf,Kl,ff;function X0(s){return `
239
239
  <style>
240
240
  :host {
241
241
  font: var(--media-font,
@@ -276,9 +276,9 @@
276
276
  }
277
277
  </style>
278
278
  ${this.getSlotTemplateHTML(s)}
279
- `}function X0(s){return `
279
+ `}function Z0(s){return `
280
280
  <slot id="content"></slot>
281
- `}var br={OPEN:"open",ANCHOR:"anchor"},Ri=class extends chunkDITZCOYN_cjs.o.HTMLElement{constructor(){super(),gi(this,na),gi(this,Bl),gi(this,$l),gi(this,Gl),gi(this,Hl),gi(this,Kl),gi(this,aa,false),gi(this,_r,null),gi(this,Qi,null),this.addEventListener("invoke",this),this.addEventListener("focusout",this),this.addEventListener("keydown",this);}static get observedAttributes(){return [br.OPEN,br.ANCHOR]}get open(){return chunkDITZCOYN_cjs.F(this,br.OPEN)}set open(e){chunkDITZCOYN_cjs.G(this,br.OPEN,e);}handleEvent(e){switch(e.type){case "invoke":ji(this,Gl,cf).call(this,e);break;case "focusout":ji(this,Hl,uf).call(this,e);break;case "keydown":ji(this,Kl,hf).call(this,e);break}}connectedCallback(){ji(this,na,Ul).call(this),this.role||(this.role="dialog");}attributeChangedCallback(e,t,i){ji(this,na,Ul).call(this),e===br.OPEN&&i!==t&&(this.open?ji(this,Bl,lf).call(this):ji(this,$l,df).call(this));}focus(){Wl(this,_r,chunkDITZCOYN_cjs.y());let e=!this.dispatchEvent(new Event("focus",{composed:true,cancelable:true})),t=!this.dispatchEvent(new Event("focusin",{composed:true,bubbles:true,cancelable:true}));if(e||t)return;let i=this.querySelector('[autofocus], [tabindex]:not([tabindex="-1"]), [role="menu"]');i?.focus();}get keysUsed(){return ["Escape","Tab"]}};aa=new WeakMap;_r=new WeakMap;Qi=new WeakMap;na=new WeakSet;Ul=function(){if(!zi(this,aa)&&(Wl(this,aa,true),!this.shadowRoot)){this.attachShadow(this.constructor.shadowRootOptions);let s=chunkDITZCOYN_cjs.s(this.attributes);this.shadowRoot.innerHTML=this.constructor.getTemplateHTML(s),queueMicrotask(()=>{let{style:e}=chunkDITZCOYN_cjs.C(this.shadowRoot,":host");e.setProperty("transition","display .15s, visibility .15s, opacity .15s ease-in, transform .15s ease-in");});}};Bl=new WeakSet;lf=function(){var s;(s=zi(this,Qi))==null||s.setAttribute("aria-expanded","true"),this.dispatchEvent(new Event("open",{composed:true,bubbles:true})),this.addEventListener("transitionend",()=>this.focus(),{once:true});};$l=new WeakSet;df=function(){var s;(s=zi(this,Qi))==null||s.setAttribute("aria-expanded","false"),this.dispatchEvent(new Event("close",{composed:true,bubbles:true}));};Gl=new WeakSet;cf=function(s){Wl(this,Qi,s.relatedTarget),chunkDITZCOYN_cjs.w(this,s.relatedTarget)||(this.open=!this.open);};Hl=new WeakSet;uf=function(s){var e;chunkDITZCOYN_cjs.w(this,s.relatedTarget)||((e=zi(this,_r))==null||e.focus(),zi(this,Qi)&&zi(this,Qi)!==s.relatedTarget&&this.open&&(this.open=false));};Kl=new WeakSet;hf=function(s){var e,t,i,r,n;let{key:a,ctrlKey:o,altKey:l,metaKey:d}=s;o||l||d||this.keysUsed.includes(a)&&(s.preventDefault(),s.stopPropagation(),a==="Tab"?(s.shiftKey?(t=(e=this.previousElementSibling)==null?void 0:e.focus)==null||t.call(e):(r=(i=this.nextElementSibling)==null?void 0:i.focus)==null||r.call(i),this.blur()):a==="Escape"&&((n=zi(this,_r))==null||n.focus(),this.open=false));};Ri.shadowRootOptions={mode:"open"};Ri.getTemplateHTML=Q0;Ri.getSlotTemplateHTML=X0;chunkDITZCOYN_cjs.o.customElements.get("media-chrome-dialog")||chunkDITZCOYN_cjs.o.customElements.define("media-chrome-dialog",Ri);var Zl=(s,e,t)=>{if(!e.has(s))throw TypeError("Cannot "+t)},xe=(s,e,t)=>(Zl(s,e,"read from private field"),t?t.call(s):e.get(s)),Qe=(s,e,t)=>{if(e.has(s))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(s):e.set(s,t);},ki=(s,e,t,i)=>(Zl(s,e,"write to private field"),e.set(s,t),t),Nt=(s,e,t)=>(Zl(s,e,"access private method"),t),qt,pa,oa,la,Ut,ma,da,ca,ua,Jl,ff,ha,Yl,fa,ql,ga,ed,jl,mf,zl,gf,Ql,pf,Xl,Ef;function Z0(s){return `
281
+ `}var br={OPEN:"open",ANCHOR:"anchor"},Ri=class extends chunkDITZCOYN_cjs.o.HTMLElement{constructor(){super(),gi(this,na),gi(this,Bl),gi(this,$l),gi(this,Gl),gi(this,Hl),gi(this,Kl),gi(this,aa,false),gi(this,_r,null),gi(this,Qi,null),this.addEventListener("invoke",this),this.addEventListener("focusout",this),this.addEventListener("keydown",this);}static get observedAttributes(){return [br.OPEN,br.ANCHOR]}get open(){return chunkDITZCOYN_cjs.F(this,br.OPEN)}set open(e){chunkDITZCOYN_cjs.G(this,br.OPEN,e);}handleEvent(e){switch(e.type){case "invoke":ji(this,Gl,uf).call(this,e);break;case "focusout":ji(this,Hl,hf).call(this,e);break;case "keydown":ji(this,Kl,ff).call(this,e);break}}connectedCallback(){ji(this,na,Ul).call(this),this.role||(this.role="dialog");}attributeChangedCallback(e,t,i){ji(this,na,Ul).call(this),e===br.OPEN&&i!==t&&(this.open?ji(this,Bl,df).call(this):ji(this,$l,cf).call(this));}focus(){Wl(this,_r,chunkDITZCOYN_cjs.y());let e=!this.dispatchEvent(new Event("focus",{composed:true,cancelable:true})),t=!this.dispatchEvent(new Event("focusin",{composed:true,bubbles:true,cancelable:true}));if(e||t)return;let i=this.querySelector('[autofocus], [tabindex]:not([tabindex="-1"]), [role="menu"]');i?.focus();}get keysUsed(){return ["Escape","Tab"]}};aa=new WeakMap;_r=new WeakMap;Qi=new WeakMap;na=new WeakSet;Ul=function(){if(!zi(this,aa)&&(Wl(this,aa,true),!this.shadowRoot)){this.attachShadow(this.constructor.shadowRootOptions);let s=chunkDITZCOYN_cjs.s(this.attributes);this.shadowRoot.innerHTML=this.constructor.getTemplateHTML(s),queueMicrotask(()=>{let{style:e}=chunkDITZCOYN_cjs.C(this.shadowRoot,":host");e.setProperty("transition","display .15s, visibility .15s, opacity .15s ease-in, transform .15s ease-in");});}};Bl=new WeakSet;df=function(){var s;(s=zi(this,Qi))==null||s.setAttribute("aria-expanded","true"),this.dispatchEvent(new Event("open",{composed:true,bubbles:true})),this.addEventListener("transitionend",()=>this.focus(),{once:true});};$l=new WeakSet;cf=function(){var s;(s=zi(this,Qi))==null||s.setAttribute("aria-expanded","false"),this.dispatchEvent(new Event("close",{composed:true,bubbles:true}));};Gl=new WeakSet;uf=function(s){Wl(this,Qi,s.relatedTarget),chunkDITZCOYN_cjs.w(this,s.relatedTarget)||(this.open=!this.open);};Hl=new WeakSet;hf=function(s){var e;chunkDITZCOYN_cjs.w(this,s.relatedTarget)||((e=zi(this,_r))==null||e.focus(),zi(this,Qi)&&zi(this,Qi)!==s.relatedTarget&&this.open&&(this.open=false));};Kl=new WeakSet;ff=function(s){var e,t,i,r,n;let{key:a,ctrlKey:o,altKey:l,metaKey:d}=s;o||l||d||this.keysUsed.includes(a)&&(s.preventDefault(),s.stopPropagation(),a==="Tab"?(s.shiftKey?(t=(e=this.previousElementSibling)==null?void 0:e.focus)==null||t.call(e):(r=(i=this.nextElementSibling)==null?void 0:i.focus)==null||r.call(i),this.blur()):a==="Escape"&&((n=zi(this,_r))==null||n.focus(),this.open=false));};Ri.shadowRootOptions={mode:"open"};Ri.getTemplateHTML=X0;Ri.getSlotTemplateHTML=Z0;chunkDITZCOYN_cjs.o.customElements.get("media-chrome-dialog")||chunkDITZCOYN_cjs.o.customElements.define("media-chrome-dialog",Ri);var Zl=(s,e,t)=>{if(!e.has(s))throw TypeError("Cannot "+t)},xe=(s,e,t)=>(Zl(s,e,"read from private field"),t?t.call(s):e.get(s)),Qe=(s,e,t)=>{if(e.has(s))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(s):e.set(s,t);},ki=(s,e,t,i)=>(Zl(s,e,"write to private field"),e.set(s,t),t),Nt=(s,e,t)=>(Zl(s,e,"access private method"),t),qt,pa,oa,la,Ut,ma,da,ca,ua,Jl,mf,ha,Yl,fa,ql,ga,ed,jl,gf,zl,pf,Ql,Ef,Xl,vf;function J0(s){return `
282
282
  <style>
283
283
  :host {
284
284
  --_focus-box-shadow: var(--media-focus-box-shadow, inset 0 0 0 2px rgb(27 127 204 / .9));
@@ -506,7 +506,7 @@
506
506
  <input id="range" type="range" min="0" max="1" step="any" value="0">
507
507
  </div>
508
508
  <div id="rightgap"></div>
509
- `}var jt=class extends chunkDITZCOYN_cjs.o.HTMLElement{constructor(){if(super(),Qe(this,Jl),Qe(this,ha),Qe(this,fa),Qe(this,ga),Qe(this,jl),Qe(this,zl),Qe(this,Ql),Qe(this,Xl),Qe(this,qt,void 0),Qe(this,pa,void 0),Qe(this,oa,void 0),Qe(this,la,void 0),Qe(this,Ut,{}),Qe(this,ma,[]),Qe(this,da,()=>{if(this.range.matches(":focus-visible")){let{style:e}=chunkDITZCOYN_cjs.C(this.shadowRoot,":host");e.setProperty("--_focus-visible-box-shadow","var(--_focus-box-shadow)");}}),Qe(this,ca,()=>{let{style:e}=chunkDITZCOYN_cjs.C(this.shadowRoot,":host");e.removeProperty("--_focus-visible-box-shadow");}),Qe(this,ua,()=>{let e=this.shadowRoot.querySelector("#segments-clipping");e&&e.parentNode.append(e);}),!this.shadowRoot){this.attachShadow(this.constructor.shadowRootOptions);let e=chunkDITZCOYN_cjs.s(this.attributes),t=this.constructor.getTemplateHTML(e);this.shadowRoot.setHTMLUnsafe?this.shadowRoot.setHTMLUnsafe(t):this.shadowRoot.innerHTML=t;}this.container=this.shadowRoot.querySelector("#container"),ki(this,oa,this.shadowRoot.querySelector("#startpoint")),ki(this,la,this.shadowRoot.querySelector("#endpoint")),this.range=this.shadowRoot.querySelector("#range"),this.appearance=this.shadowRoot.querySelector("#appearance");}static get observedAttributes(){return ["disabled","aria-disabled",chunkDITZCOYN_cjs.b.MEDIA_CONTROLLER]}attributeChangedCallback(e,t,i){var r,n,a,o,l;e===chunkDITZCOYN_cjs.b.MEDIA_CONTROLLER?(t&&((n=(r=xe(this,qt))==null?void 0:r.unassociateElement)==null||n.call(r,this),ki(this,qt,null)),i&&this.isConnected&&(ki(this,qt,(a=this.getRootNode())==null?void 0:a.getElementById(i)),(l=(o=xe(this,qt))==null?void 0:o.associateElement)==null||l.call(o,this))):(e==="disabled"||e==="aria-disabled"&&t!==i)&&(i==null?(this.range.removeAttribute(e),Nt(this,ha,Yl).call(this)):(this.range.setAttribute(e,i),Nt(this,fa,ql).call(this)));}connectedCallback(){var e,t,i;let{style:r}=chunkDITZCOYN_cjs.C(this.shadowRoot,":host");r.setProperty("display",`var(--media-control-display, var(--${this.localName}-display, inline-flex))`),xe(this,Ut).pointer=chunkDITZCOYN_cjs.C(this.shadowRoot,"#pointer"),xe(this,Ut).progress=chunkDITZCOYN_cjs.C(this.shadowRoot,"#progress"),xe(this,Ut).thumb=chunkDITZCOYN_cjs.C(this.shadowRoot,'#thumb, ::slotted([slot="thumb"])'),xe(this,Ut).activeSegment=chunkDITZCOYN_cjs.C(this.shadowRoot,"#segments-clipping rect:nth-child(0)");let n=this.getAttribute(chunkDITZCOYN_cjs.b.MEDIA_CONTROLLER);n&&(ki(this,qt,(e=this.getRootNode())==null?void 0:e.getElementById(n)),(i=(t=xe(this,qt))==null?void 0:t.associateElement)==null||i.call(t,this)),this.updateBar(),this.shadowRoot.addEventListener("focusin",xe(this,da)),this.shadowRoot.addEventListener("focusout",xe(this,ca)),Nt(this,ha,Yl).call(this),chunkDITZCOYN_cjs.q(this.container,xe(this,ua));}disconnectedCallback(){var e,t;Nt(this,fa,ql).call(this),(t=(e=xe(this,qt))==null?void 0:e.unassociateElement)==null||t.call(e,this),ki(this,qt,null),this.shadowRoot.removeEventListener("focusin",xe(this,da)),this.shadowRoot.removeEventListener("focusout",xe(this,ca)),chunkDITZCOYN_cjs.r(this.container,xe(this,ua));}updatePointerBar(e){var t;(t=xe(this,Ut).pointer)==null||t.style.setProperty("width",`${this.getPointerRatio(e)*100}%`);}updateBar(){var e,t;let i=this.range.valueAsNumber*100;(e=xe(this,Ut).progress)==null||e.style.setProperty("width",`${i}%`),(t=xe(this,Ut).thumb)==null||t.style.setProperty("left",`${i}%`);}updateSegments(e){let t=this.shadowRoot.querySelector("#segments-clipping");if(t.textContent="",this.container.classList.toggle("segments",!!e?.length),!e?.length)return;let i=[...new Set([+this.range.min,...e.flatMap(n=>[n.start,n.end]),+this.range.max])];ki(this,ma,[...i]);let r=i.pop();for(let[n,a]of i.entries()){let[o,l]=[n===0,n===i.length-1],d=o?"calc(var(--segments-gap) / -1)":`${a*100}%`,u=`calc(${((l?r:i[n+1])-a)*100}%${o||l?"":" - var(--segments-gap)"})`,h=chunkDITZCOYN_cjs.p.createElementNS("http://www.w3.org/2000/svg","rect"),f=chunkDITZCOYN_cjs.C(this.shadowRoot,`#segments-clipping rect:nth-child(${n+1})`);f.style.setProperty("x",d),f.style.setProperty("width",u),t.append(h);}}getPointerRatio(e){return chunkDITZCOYN_cjs.B(e.clientX,e.clientY,xe(this,oa).getBoundingClientRect(),xe(this,la).getBoundingClientRect())}get dragging(){return this.hasAttribute("dragging")}handleEvent(e){switch(e.type){case "pointermove":Nt(this,Xl,Ef).call(this,e);break;case "input":this.updateBar();break;case "pointerenter":Nt(this,jl,mf).call(this,e);break;case "pointerdown":Nt(this,ga,ed).call(this,e);break;case "pointerup":Nt(this,zl,gf).call(this);break;case "pointerleave":Nt(this,Ql,pf).call(this);break}}get keysUsed(){return ["ArrowUp","ArrowRight","ArrowDown","ArrowLeft"]}};qt=new WeakMap;pa=new WeakMap;oa=new WeakMap;la=new WeakMap;Ut=new WeakMap;ma=new WeakMap;da=new WeakMap;ca=new WeakMap;ua=new WeakMap;Jl=new WeakSet;ff=function(s){let e=xe(this,Ut).activeSegment;if(!e)return;let t=this.getPointerRatio(s),r=`#segments-clipping rect:nth-child(${xe(this,ma).findIndex((n,a,o)=>{let l=o[a+1];return l!=null&&t>=n&&t<=l})+1})`;(e.selectorText!=r||!e.style.transform)&&(e.selectorText=r,e.style.setProperty("transform","var(--media-range-segment-hover-transform, scaleY(2))"));};ha=new WeakSet;Yl=function(){this.hasAttribute("disabled")||(this.addEventListener("input",this),this.addEventListener("pointerdown",this),this.addEventListener("pointerenter",this));};fa=new WeakSet;ql=function(){var s,e;this.removeEventListener("input",this),this.removeEventListener("pointerdown",this),this.removeEventListener("pointerenter",this),(s=chunkDITZCOYN_cjs.o.window)==null||s.removeEventListener("pointerup",this),(e=chunkDITZCOYN_cjs.o.window)==null||e.removeEventListener("pointermove",this);};ga=new WeakSet;ed=function(s){var e;ki(this,pa,s.composedPath().includes(this.range)),(e=chunkDITZCOYN_cjs.o.window)==null||e.addEventListener("pointerup",this);};jl=new WeakSet;mf=function(s){var e;s.pointerType!=="mouse"&&Nt(this,ga,ed).call(this,s),this.addEventListener("pointerleave",this),(e=chunkDITZCOYN_cjs.o.window)==null||e.addEventListener("pointermove",this);};zl=new WeakSet;gf=function(){var s;(s=chunkDITZCOYN_cjs.o.window)==null||s.removeEventListener("pointerup",this),this.toggleAttribute("dragging",false),this.range.disabled=this.hasAttribute("disabled");};Ql=new WeakSet;pf=function(){var s,e;this.removeEventListener("pointerleave",this),(s=chunkDITZCOYN_cjs.o.window)==null||s.removeEventListener("pointermove",this),this.toggleAttribute("dragging",false),this.range.disabled=this.hasAttribute("disabled"),(e=xe(this,Ut).activeSegment)==null||e.style.removeProperty("transform");};Xl=new WeakSet;Ef=function(s){s.pointerType==="pen"&&s.buttons===0||(this.toggleAttribute("dragging",s.buttons===1||s.pointerType!=="mouse"),this.updatePointerBar(s),Nt(this,Jl,ff).call(this,s),this.dragging&&(s.pointerType!=="mouse"||!xe(this,pa))&&(this.range.disabled=true,this.range.valueAsNumber=this.getPointerRatio(s),this.range.dispatchEvent(new Event("input",{bubbles:true,composed:true}))));};jt.shadowRootOptions={mode:"open"};jt.getTemplateHTML=Z0;chunkDITZCOYN_cjs.o.customElements.get("media-chrome-range")||chunkDITZCOYN_cjs.o.customElements.define("media-chrome-range",jt);var vf=(s,e,t)=>{if(!e.has(s))throw TypeError("Cannot "+t)},Ea=(s,e,t)=>(vf(s,e,"read from private field"),t?t.call(s):e.get(s)),J0=(s,e,t)=>{if(e.has(s))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(s):e.set(s,t);},va=(s,e,t,i)=>(vf(s,e,"write to private field"),e.set(s,t),t),zt;function eE(s){return `
509
+ `}var jt=class extends chunkDITZCOYN_cjs.o.HTMLElement{constructor(){if(super(),Qe(this,Jl),Qe(this,ha),Qe(this,fa),Qe(this,ga),Qe(this,jl),Qe(this,zl),Qe(this,Ql),Qe(this,Xl),Qe(this,qt,void 0),Qe(this,pa,void 0),Qe(this,oa,void 0),Qe(this,la,void 0),Qe(this,Ut,{}),Qe(this,ma,[]),Qe(this,da,()=>{if(this.range.matches(":focus-visible")){let{style:e}=chunkDITZCOYN_cjs.C(this.shadowRoot,":host");e.setProperty("--_focus-visible-box-shadow","var(--_focus-box-shadow)");}}),Qe(this,ca,()=>{let{style:e}=chunkDITZCOYN_cjs.C(this.shadowRoot,":host");e.removeProperty("--_focus-visible-box-shadow");}),Qe(this,ua,()=>{let e=this.shadowRoot.querySelector("#segments-clipping");e&&e.parentNode.append(e);}),!this.shadowRoot){this.attachShadow(this.constructor.shadowRootOptions);let e=chunkDITZCOYN_cjs.s(this.attributes),t=this.constructor.getTemplateHTML(e);this.shadowRoot.setHTMLUnsafe?this.shadowRoot.setHTMLUnsafe(t):this.shadowRoot.innerHTML=t;}this.container=this.shadowRoot.querySelector("#container"),ki(this,oa,this.shadowRoot.querySelector("#startpoint")),ki(this,la,this.shadowRoot.querySelector("#endpoint")),this.range=this.shadowRoot.querySelector("#range"),this.appearance=this.shadowRoot.querySelector("#appearance");}static get observedAttributes(){return ["disabled","aria-disabled",chunkDITZCOYN_cjs.b.MEDIA_CONTROLLER]}attributeChangedCallback(e,t,i){var r,n,a,o,l;e===chunkDITZCOYN_cjs.b.MEDIA_CONTROLLER?(t&&((n=(r=xe(this,qt))==null?void 0:r.unassociateElement)==null||n.call(r,this),ki(this,qt,null)),i&&this.isConnected&&(ki(this,qt,(a=this.getRootNode())==null?void 0:a.getElementById(i)),(l=(o=xe(this,qt))==null?void 0:o.associateElement)==null||l.call(o,this))):(e==="disabled"||e==="aria-disabled"&&t!==i)&&(i==null?(this.range.removeAttribute(e),Nt(this,ha,Yl).call(this)):(this.range.setAttribute(e,i),Nt(this,fa,ql).call(this)));}connectedCallback(){var e,t,i;let{style:r}=chunkDITZCOYN_cjs.C(this.shadowRoot,":host");r.setProperty("display",`var(--media-control-display, var(--${this.localName}-display, inline-flex))`),xe(this,Ut).pointer=chunkDITZCOYN_cjs.C(this.shadowRoot,"#pointer"),xe(this,Ut).progress=chunkDITZCOYN_cjs.C(this.shadowRoot,"#progress"),xe(this,Ut).thumb=chunkDITZCOYN_cjs.C(this.shadowRoot,'#thumb, ::slotted([slot="thumb"])'),xe(this,Ut).activeSegment=chunkDITZCOYN_cjs.C(this.shadowRoot,"#segments-clipping rect:nth-child(0)");let n=this.getAttribute(chunkDITZCOYN_cjs.b.MEDIA_CONTROLLER);n&&(ki(this,qt,(e=this.getRootNode())==null?void 0:e.getElementById(n)),(i=(t=xe(this,qt))==null?void 0:t.associateElement)==null||i.call(t,this)),this.updateBar(),this.shadowRoot.addEventListener("focusin",xe(this,da)),this.shadowRoot.addEventListener("focusout",xe(this,ca)),Nt(this,ha,Yl).call(this),chunkDITZCOYN_cjs.q(this.container,xe(this,ua));}disconnectedCallback(){var e,t;Nt(this,fa,ql).call(this),(t=(e=xe(this,qt))==null?void 0:e.unassociateElement)==null||t.call(e,this),ki(this,qt,null),this.shadowRoot.removeEventListener("focusin",xe(this,da)),this.shadowRoot.removeEventListener("focusout",xe(this,ca)),chunkDITZCOYN_cjs.r(this.container,xe(this,ua));}updatePointerBar(e){var t;(t=xe(this,Ut).pointer)==null||t.style.setProperty("width",`${this.getPointerRatio(e)*100}%`);}updateBar(){var e,t;let i=this.range.valueAsNumber*100;(e=xe(this,Ut).progress)==null||e.style.setProperty("width",`${i}%`),(t=xe(this,Ut).thumb)==null||t.style.setProperty("left",`${i}%`);}updateSegments(e){let t=this.shadowRoot.querySelector("#segments-clipping");if(t.textContent="",this.container.classList.toggle("segments",!!e?.length),!e?.length)return;let i=[...new Set([+this.range.min,...e.flatMap(n=>[n.start,n.end]),+this.range.max])];ki(this,ma,[...i]);let r=i.pop();for(let[n,a]of i.entries()){let[o,l]=[n===0,n===i.length-1],d=o?"calc(var(--segments-gap) / -1)":`${a*100}%`,u=`calc(${((l?r:i[n+1])-a)*100}%${o||l?"":" - var(--segments-gap)"})`,h=chunkDITZCOYN_cjs.p.createElementNS("http://www.w3.org/2000/svg","rect"),f=chunkDITZCOYN_cjs.C(this.shadowRoot,`#segments-clipping rect:nth-child(${n+1})`);f.style.setProperty("x",d),f.style.setProperty("width",u),t.append(h);}}getPointerRatio(e){return chunkDITZCOYN_cjs.B(e.clientX,e.clientY,xe(this,oa).getBoundingClientRect(),xe(this,la).getBoundingClientRect())}get dragging(){return this.hasAttribute("dragging")}handleEvent(e){switch(e.type){case "pointermove":Nt(this,Xl,vf).call(this,e);break;case "input":this.updateBar();break;case "pointerenter":Nt(this,jl,gf).call(this,e);break;case "pointerdown":Nt(this,ga,ed).call(this,e);break;case "pointerup":Nt(this,zl,pf).call(this);break;case "pointerleave":Nt(this,Ql,Ef).call(this);break}}get keysUsed(){return ["ArrowUp","ArrowRight","ArrowDown","ArrowLeft"]}};qt=new WeakMap;pa=new WeakMap;oa=new WeakMap;la=new WeakMap;Ut=new WeakMap;ma=new WeakMap;da=new WeakMap;ca=new WeakMap;ua=new WeakMap;Jl=new WeakSet;mf=function(s){let e=xe(this,Ut).activeSegment;if(!e)return;let t=this.getPointerRatio(s),r=`#segments-clipping rect:nth-child(${xe(this,ma).findIndex((n,a,o)=>{let l=o[a+1];return l!=null&&t>=n&&t<=l})+1})`;(e.selectorText!=r||!e.style.transform)&&(e.selectorText=r,e.style.setProperty("transform","var(--media-range-segment-hover-transform, scaleY(2))"));};ha=new WeakSet;Yl=function(){this.hasAttribute("disabled")||(this.addEventListener("input",this),this.addEventListener("pointerdown",this),this.addEventListener("pointerenter",this));};fa=new WeakSet;ql=function(){var s,e;this.removeEventListener("input",this),this.removeEventListener("pointerdown",this),this.removeEventListener("pointerenter",this),(s=chunkDITZCOYN_cjs.o.window)==null||s.removeEventListener("pointerup",this),(e=chunkDITZCOYN_cjs.o.window)==null||e.removeEventListener("pointermove",this);};ga=new WeakSet;ed=function(s){var e;ki(this,pa,s.composedPath().includes(this.range)),(e=chunkDITZCOYN_cjs.o.window)==null||e.addEventListener("pointerup",this);};jl=new WeakSet;gf=function(s){var e;s.pointerType!=="mouse"&&Nt(this,ga,ed).call(this,s),this.addEventListener("pointerleave",this),(e=chunkDITZCOYN_cjs.o.window)==null||e.addEventListener("pointermove",this);};zl=new WeakSet;pf=function(){var s;(s=chunkDITZCOYN_cjs.o.window)==null||s.removeEventListener("pointerup",this),this.toggleAttribute("dragging",false),this.range.disabled=this.hasAttribute("disabled");};Ql=new WeakSet;Ef=function(){var s,e;this.removeEventListener("pointerleave",this),(s=chunkDITZCOYN_cjs.o.window)==null||s.removeEventListener("pointermove",this),this.toggleAttribute("dragging",false),this.range.disabled=this.hasAttribute("disabled"),(e=xe(this,Ut).activeSegment)==null||e.style.removeProperty("transform");};Xl=new WeakSet;vf=function(s){s.pointerType==="pen"&&s.buttons===0||(this.toggleAttribute("dragging",s.buttons===1||s.pointerType!=="mouse"),this.updatePointerBar(s),Nt(this,Jl,mf).call(this,s),this.dragging&&(s.pointerType!=="mouse"||!xe(this,pa))&&(this.range.disabled=true,this.range.valueAsNumber=this.getPointerRatio(s),this.range.dispatchEvent(new Event("input",{bubbles:true,composed:true}))));};jt.shadowRootOptions={mode:"open"};jt.getTemplateHTML=J0;chunkDITZCOYN_cjs.o.customElements.get("media-chrome-range")||chunkDITZCOYN_cjs.o.customElements.define("media-chrome-range",jt);var Tf=(s,e,t)=>{if(!e.has(s))throw TypeError("Cannot "+t)},Ea=(s,e,t)=>(Tf(s,e,"read from private field"),t?t.call(s):e.get(s)),eE=(s,e,t)=>{if(e.has(s))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(s):e.set(s,t);},va=(s,e,t,i)=>(Tf(s,e,"write to private field"),e.set(s,t),t),zt;function tE(s){return `
510
510
  <style>
511
511
  :host {
512
512
 
@@ -532,7 +532,7 @@
532
532
  </style>
533
533
 
534
534
  <slot></slot>
535
- `}var Ir=class extends chunkDITZCOYN_cjs.o.HTMLElement{constructor(){if(super(),J0(this,zt,void 0),!this.shadowRoot){this.attachShadow(this.constructor.shadowRootOptions);let e=chunkDITZCOYN_cjs.s(this.attributes);this.shadowRoot.innerHTML=this.constructor.getTemplateHTML(e);}}static get observedAttributes(){return [chunkDITZCOYN_cjs.b.MEDIA_CONTROLLER]}attributeChangedCallback(e,t,i){var r,n,a,o,l;e===chunkDITZCOYN_cjs.b.MEDIA_CONTROLLER&&(t&&((n=(r=Ea(this,zt))==null?void 0:r.unassociateElement)==null||n.call(r,this),va(this,zt,null)),i&&this.isConnected&&(va(this,zt,(a=this.getRootNode())==null?void 0:a.getElementById(i)),(l=(o=Ea(this,zt))==null?void 0:o.associateElement)==null||l.call(o,this)));}connectedCallback(){var e,t,i;let r=this.getAttribute(chunkDITZCOYN_cjs.b.MEDIA_CONTROLLER);r&&(va(this,zt,(e=this.getRootNode())==null?void 0:e.getElementById(r)),(i=(t=Ea(this,zt))==null?void 0:t.associateElement)==null||i.call(t,this));}disconnectedCallback(){var e,t;(t=(e=Ea(this,zt))==null?void 0:e.unassociateElement)==null||t.call(e,this),va(this,zt,null);}};zt=new WeakMap;Ir.shadowRootOptions={mode:"open"};Ir.getTemplateHTML=eE;chunkDITZCOYN_cjs.o.customElements.get("media-control-bar")||chunkDITZCOYN_cjs.o.customElements.define("media-control-bar",Ir);var Tf=(s,e,t)=>{if(!e.has(s))throw TypeError("Cannot "+t)},Ta=(s,e,t)=>(Tf(s,e,"read from private field"),t?t.call(s):e.get(s)),tE=(s,e,t)=>{if(e.has(s))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(s):e.set(s,t);},ya=(s,e,t,i)=>(Tf(s,e,"write to private field"),e.set(s,t),t),Qt;function iE(s,e={}){return `
535
+ `}var Ir=class extends chunkDITZCOYN_cjs.o.HTMLElement{constructor(){if(super(),eE(this,zt,void 0),!this.shadowRoot){this.attachShadow(this.constructor.shadowRootOptions);let e=chunkDITZCOYN_cjs.s(this.attributes);this.shadowRoot.innerHTML=this.constructor.getTemplateHTML(e);}}static get observedAttributes(){return [chunkDITZCOYN_cjs.b.MEDIA_CONTROLLER]}attributeChangedCallback(e,t,i){var r,n,a,o,l;e===chunkDITZCOYN_cjs.b.MEDIA_CONTROLLER&&(t&&((n=(r=Ea(this,zt))==null?void 0:r.unassociateElement)==null||n.call(r,this),va(this,zt,null)),i&&this.isConnected&&(va(this,zt,(a=this.getRootNode())==null?void 0:a.getElementById(i)),(l=(o=Ea(this,zt))==null?void 0:o.associateElement)==null||l.call(o,this)));}connectedCallback(){var e,t,i;let r=this.getAttribute(chunkDITZCOYN_cjs.b.MEDIA_CONTROLLER);r&&(va(this,zt,(e=this.getRootNode())==null?void 0:e.getElementById(r)),(i=(t=Ea(this,zt))==null?void 0:t.associateElement)==null||i.call(t,this));}disconnectedCallback(){var e,t;(t=(e=Ea(this,zt))==null?void 0:e.unassociateElement)==null||t.call(e,this),va(this,zt,null);}};zt=new WeakMap;Ir.shadowRootOptions={mode:"open"};Ir.getTemplateHTML=tE;chunkDITZCOYN_cjs.o.customElements.get("media-control-bar")||chunkDITZCOYN_cjs.o.customElements.define("media-control-bar",Ir);var yf=(s,e,t)=>{if(!e.has(s))throw TypeError("Cannot "+t)},Ta=(s,e,t)=>(yf(s,e,"read from private field"),t?t.call(s):e.get(s)),iE=(s,e,t)=>{if(e.has(s))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(s):e.set(s,t);},ya=(s,e,t,i)=>(yf(s,e,"write to private field"),e.set(s,t),t),Qt;function sE(s,e={}){return `
536
536
  <style>
537
537
  :host {
538
538
  font: var(--media-font,
@@ -566,11 +566,11 @@
566
566
  </style>
567
567
 
568
568
  ${this.getSlotTemplateHTML(s,e)}
569
- `}function sE(s,e){return `
569
+ `}function rE(s,e){return `
570
570
  <slot></slot>
571
- `}var dt=class extends chunkDITZCOYN_cjs.o.HTMLElement{constructor(){if(super(),tE(this,Qt,void 0),!this.shadowRoot){this.attachShadow(this.constructor.shadowRootOptions);let e=chunkDITZCOYN_cjs.s(this.attributes);this.shadowRoot.innerHTML=this.constructor.getTemplateHTML(e);}}static get observedAttributes(){return [chunkDITZCOYN_cjs.b.MEDIA_CONTROLLER]}attributeChangedCallback(e,t,i){var r,n,a,o,l;e===chunkDITZCOYN_cjs.b.MEDIA_CONTROLLER&&(t&&((n=(r=Ta(this,Qt))==null?void 0:r.unassociateElement)==null||n.call(r,this),ya(this,Qt,null)),i&&this.isConnected&&(ya(this,Qt,(a=this.getRootNode())==null?void 0:a.getElementById(i)),(l=(o=Ta(this,Qt))==null?void 0:o.associateElement)==null||l.call(o,this)));}connectedCallback(){var e,t,i;let{style:r}=chunkDITZCOYN_cjs.C(this.shadowRoot,":host");r.setProperty("display",`var(--media-control-display, var(--${this.localName}-display, inline-flex))`);let n=this.getAttribute(chunkDITZCOYN_cjs.b.MEDIA_CONTROLLER);n&&(ya(this,Qt,(e=this.getRootNode())==null?void 0:e.getElementById(n)),(i=(t=Ta(this,Qt))==null?void 0:t.associateElement)==null||i.call(t,this));}disconnectedCallback(){var e,t;(t=(e=Ta(this,Qt))==null?void 0:e.unassociateElement)==null||t.call(e,this),ya(this,Qt,null);}};Qt=new WeakMap;dt.shadowRootOptions={mode:"open"};dt.getTemplateHTML=iE;dt.getSlotTemplateHTML=sE;chunkDITZCOYN_cjs.o.customElements.get("media-text-display")||chunkDITZCOYN_cjs.o.customElements.define("media-text-display",dt);var Sf=(s,e,t)=>{if(!e.has(s))throw TypeError("Cannot "+t)},yf=(s,e,t)=>(Sf(s,e,"read from private field"),t?t.call(s):e.get(s)),rE=(s,e,t)=>{if(e.has(s))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(s):e.set(s,t);},nE=(s,e,t,i)=>(Sf(s,e,"write to private field"),e.set(s,t),t),Lr;function aE(s,e){return `
571
+ `}var dt=class extends chunkDITZCOYN_cjs.o.HTMLElement{constructor(){if(super(),iE(this,Qt,void 0),!this.shadowRoot){this.attachShadow(this.constructor.shadowRootOptions);let e=chunkDITZCOYN_cjs.s(this.attributes);this.shadowRoot.innerHTML=this.constructor.getTemplateHTML(e);}}static get observedAttributes(){return [chunkDITZCOYN_cjs.b.MEDIA_CONTROLLER]}attributeChangedCallback(e,t,i){var r,n,a,o,l;e===chunkDITZCOYN_cjs.b.MEDIA_CONTROLLER&&(t&&((n=(r=Ta(this,Qt))==null?void 0:r.unassociateElement)==null||n.call(r,this),ya(this,Qt,null)),i&&this.isConnected&&(ya(this,Qt,(a=this.getRootNode())==null?void 0:a.getElementById(i)),(l=(o=Ta(this,Qt))==null?void 0:o.associateElement)==null||l.call(o,this)));}connectedCallback(){var e,t,i;let{style:r}=chunkDITZCOYN_cjs.C(this.shadowRoot,":host");r.setProperty("display",`var(--media-control-display, var(--${this.localName}-display, inline-flex))`);let n=this.getAttribute(chunkDITZCOYN_cjs.b.MEDIA_CONTROLLER);n&&(ya(this,Qt,(e=this.getRootNode())==null?void 0:e.getElementById(n)),(i=(t=Ta(this,Qt))==null?void 0:t.associateElement)==null||i.call(t,this));}disconnectedCallback(){var e,t;(t=(e=Ta(this,Qt))==null?void 0:e.unassociateElement)==null||t.call(e,this),ya(this,Qt,null);}};Qt=new WeakMap;dt.shadowRootOptions={mode:"open"};dt.getTemplateHTML=sE;dt.getSlotTemplateHTML=rE;chunkDITZCOYN_cjs.o.customElements.get("media-text-display")||chunkDITZCOYN_cjs.o.customElements.define("media-text-display",dt);var Af=(s,e,t)=>{if(!e.has(s))throw TypeError("Cannot "+t)},Sf=(s,e,t)=>(Af(s,e,"read from private field"),t?t.call(s):e.get(s)),nE=(s,e,t)=>{if(e.has(s))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(s):e.set(s,t);},aE=(s,e,t,i)=>(Af(s,e,"write to private field"),e.set(s,t),t),Lr;function oE(s,e){return `
572
572
  <slot>${Ft(e.mediaDuration)}</slot>
573
- `}var Sa=class extends dt{constructor(){var e;super(),rE(this,Lr,void 0),nE(this,Lr,this.shadowRoot.querySelector("slot")),yf(this,Lr).textContent=Ft((e=this.mediaDuration)!=null?e:0);}static get observedAttributes(){return [...super.observedAttributes,chunkDITZCOYN_cjs.d.MEDIA_DURATION]}attributeChangedCallback(e,t,i){e===chunkDITZCOYN_cjs.d.MEDIA_DURATION&&(yf(this,Lr).textContent=Ft(+i)),super.attributeChangedCallback(e,t,i);}get mediaDuration(){return chunkDITZCOYN_cjs.D(this,chunkDITZCOYN_cjs.d.MEDIA_DURATION)}set mediaDuration(e){chunkDITZCOYN_cjs.E(this,chunkDITZCOYN_cjs.d.MEDIA_DURATION,e);}};Lr=new WeakMap;Sa.getSlotTemplateHTML=aE;chunkDITZCOYN_cjs.o.customElements.get("media-duration-display")||chunkDITZCOYN_cjs.o.customElements.define("media-duration-display",Sa);var oE={2:chunkDITZCOYN_cjs.n("Network Error"),3:chunkDITZCOYN_cjs.n("Decode Error"),4:chunkDITZCOYN_cjs.n("Source Not Supported"),5:chunkDITZCOYN_cjs.n("Encryption Error")},lE={2:chunkDITZCOYN_cjs.n("A network error caused the media download to fail."),3:chunkDITZCOYN_cjs.n("A media error caused playback to be aborted. The media could be corrupt or your browser does not support this format."),4:chunkDITZCOYN_cjs.n("An unsupported error occurred. The server or network failed, or your browser does not support this format."),5:chunkDITZCOYN_cjs.n("The media is encrypted and there are no keys to decrypt it.")},td=s=>{var e,t;return s.code===1?null:{title:(e=oE[s.code])!=null?e:`Error ${s.code}`,message:(t=lE[s.code])!=null?t:s.message}};var bf=(s,e,t)=>{if(!e.has(s))throw TypeError("Cannot "+t)},dE=(s,e,t)=>(bf(s,e,"read from private field"),t?t.call(s):e.get(s)),cE=(s,e,t)=>{if(e.has(s))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(s):e.set(s,t);},uE=(s,e,t,i)=>(bf(s,e,"write to private field"),e.set(s,t),t),Aa;function hE(s){return `
573
+ `}var Sa=class extends dt{constructor(){var e;super(),nE(this,Lr,void 0),aE(this,Lr,this.shadowRoot.querySelector("slot")),Sf(this,Lr).textContent=Ft((e=this.mediaDuration)!=null?e:0);}static get observedAttributes(){return [...super.observedAttributes,chunkDITZCOYN_cjs.d.MEDIA_DURATION]}attributeChangedCallback(e,t,i){e===chunkDITZCOYN_cjs.d.MEDIA_DURATION&&(Sf(this,Lr).textContent=Ft(+i)),super.attributeChangedCallback(e,t,i);}get mediaDuration(){return chunkDITZCOYN_cjs.D(this,chunkDITZCOYN_cjs.d.MEDIA_DURATION)}set mediaDuration(e){chunkDITZCOYN_cjs.E(this,chunkDITZCOYN_cjs.d.MEDIA_DURATION,e);}};Lr=new WeakMap;Sa.getSlotTemplateHTML=oE;chunkDITZCOYN_cjs.o.customElements.get("media-duration-display")||chunkDITZCOYN_cjs.o.customElements.define("media-duration-display",Sa);var lE={2:chunkDITZCOYN_cjs.n("Network Error"),3:chunkDITZCOYN_cjs.n("Decode Error"),4:chunkDITZCOYN_cjs.n("Source Not Supported"),5:chunkDITZCOYN_cjs.n("Encryption Error")},dE={2:chunkDITZCOYN_cjs.n("A network error caused the media download to fail."),3:chunkDITZCOYN_cjs.n("A media error caused playback to be aborted. The media could be corrupt or your browser does not support this format."),4:chunkDITZCOYN_cjs.n("An unsupported error occurred. The server or network failed, or your browser does not support this format."),5:chunkDITZCOYN_cjs.n("The media is encrypted and there are no keys to decrypt it.")},td=s=>{var e,t;return s.code===1?null:{title:(e=lE[s.code])!=null?e:`Error ${s.code}`,message:(t=dE[s.code])!=null?t:s.message}};var _f=(s,e,t)=>{if(!e.has(s))throw TypeError("Cannot "+t)},cE=(s,e,t)=>(_f(s,e,"read from private field"),t?t.call(s):e.get(s)),uE=(s,e,t)=>{if(e.has(s))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(s):e.set(s,t);},hE=(s,e,t,i)=>(_f(s,e,"write to private field"),e.set(s,t),t),Aa;function fE(s){return `
574
574
  <style>
575
575
  :host {
576
576
  background: rgb(20 20 30 / .8);
@@ -587,13 +587,13 @@
587
587
  }
588
588
  </style>
589
589
  <slot name="error-${s.mediaerrorcode}" id="content">
590
- ${_f({code:+s.mediaerrorcode,message:s.mediaerrormessage})}
590
+ ${If({code:+s.mediaerrorcode,message:s.mediaerrormessage})}
591
591
  </slot>
592
- `}function fE(s){return s.code&&td(s)!==null}function _f(s){var e;let{title:t,message:i}=(e=td(s))!=null?e:{},r="";return t&&(r+=`<slot name="error-${s.code}-title"><h3>${t}</h3></slot>`),i&&(r+=`<slot name="error-${s.code}-message"><p>${i}</p></slot>`),r}var Af=[chunkDITZCOYN_cjs.d.MEDIA_ERROR_CODE,chunkDITZCOYN_cjs.d.MEDIA_ERROR_MESSAGE],xr=class extends Ri{constructor(){super(...arguments),cE(this,Aa,null);}static get observedAttributes(){return [...super.observedAttributes,...Af]}formatErrorMessage(e){return this.constructor.formatErrorMessage(e)}attributeChangedCallback(e,t,i){var r;if(super.attributeChangedCallback(e,t,i),!Af.includes(e))return;let n=(r=this.mediaError)!=null?r:{code:this.mediaErrorCode,message:this.mediaErrorMessage};this.open=fE(n),this.open&&(this.shadowRoot.querySelector("slot").name=`error-${this.mediaErrorCode}`,this.shadowRoot.querySelector("#content").innerHTML=this.formatErrorMessage(n));}get mediaError(){return dE(this,Aa)}set mediaError(e){uE(this,Aa,e);}get mediaErrorCode(){return chunkDITZCOYN_cjs.D(this,"mediaerrorcode")}set mediaErrorCode(e){chunkDITZCOYN_cjs.E(this,"mediaerrorcode",e);}get mediaErrorMessage(){return chunkDITZCOYN_cjs.H(this,"mediaerrormessage")}set mediaErrorMessage(e){chunkDITZCOYN_cjs.I(this,"mediaerrormessage",e);}};Aa=new WeakMap;xr.getSlotTemplateHTML=hE;xr.formatErrorMessage=_f;chunkDITZCOYN_cjs.o.customElements.get("media-error-dialog")||chunkDITZCOYN_cjs.o.customElements.define("media-error-dialog",xr);var Lf=(s,e,t)=>{if(!e.has(s))throw TypeError("Cannot "+t)},mE=(s,e,t)=>(Lf(s,e,"read from private field"),e.get(s)),gE=(s,e,t)=>{if(e.has(s))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(s):e.set(s,t);},pE=(s,e,t,i)=>(Lf(s,e,"write to private field"),e.set(s,t),t),ba,EE=`<svg aria-hidden="true" viewBox="0 0 26 24">
592
+ `}function mE(s){return s.code&&td(s)!==null}function If(s){var e;let{title:t,message:i}=(e=td(s))!=null?e:{},r="";return t&&(r+=`<slot name="error-${s.code}-title"><h3>${t}</h3></slot>`),i&&(r+=`<slot name="error-${s.code}-message"><p>${i}</p></slot>`),r}var bf=[chunkDITZCOYN_cjs.d.MEDIA_ERROR_CODE,chunkDITZCOYN_cjs.d.MEDIA_ERROR_MESSAGE],xr=class extends Ri{constructor(){super(...arguments),uE(this,Aa,null);}static get observedAttributes(){return [...super.observedAttributes,...bf]}formatErrorMessage(e){return this.constructor.formatErrorMessage(e)}attributeChangedCallback(e,t,i){var r;if(super.attributeChangedCallback(e,t,i),!bf.includes(e))return;let n=(r=this.mediaError)!=null?r:{code:this.mediaErrorCode,message:this.mediaErrorMessage};this.open=mE(n),this.open&&(this.shadowRoot.querySelector("slot").name=`error-${this.mediaErrorCode}`,this.shadowRoot.querySelector("#content").innerHTML=this.formatErrorMessage(n));}get mediaError(){return cE(this,Aa)}set mediaError(e){hE(this,Aa,e);}get mediaErrorCode(){return chunkDITZCOYN_cjs.D(this,"mediaerrorcode")}set mediaErrorCode(e){chunkDITZCOYN_cjs.E(this,"mediaerrorcode",e);}get mediaErrorMessage(){return chunkDITZCOYN_cjs.H(this,"mediaerrormessage")}set mediaErrorMessage(e){chunkDITZCOYN_cjs.I(this,"mediaerrormessage",e);}};Aa=new WeakMap;xr.getSlotTemplateHTML=fE;xr.formatErrorMessage=If;chunkDITZCOYN_cjs.o.customElements.get("media-error-dialog")||chunkDITZCOYN_cjs.o.customElements.define("media-error-dialog",xr);var xf=(s,e,t)=>{if(!e.has(s))throw TypeError("Cannot "+t)},gE=(s,e,t)=>(xf(s,e,"read from private field"),e.get(s)),pE=(s,e,t)=>{if(e.has(s))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(s):e.set(s,t);},EE=(s,e,t,i)=>(xf(s,e,"write to private field"),e.set(s,t),t),ba,vE=`<svg aria-hidden="true" viewBox="0 0 26 24">
593
593
  <path d="M16 3v2.5h3.5V9H22V3h-6ZM4 9h2.5V5.5H10V3H4v6Zm15.5 9.5H16V21h6v-6h-2.5v3.5ZM6.5 15H4v6h6v-2.5H6.5V15Z"/>
594
- </svg>`,vE=`<svg aria-hidden="true" viewBox="0 0 26 24">
594
+ </svg>`,TE=`<svg aria-hidden="true" viewBox="0 0 26 24">
595
595
  <path d="M18.5 6.5V3H16v6h6V6.5h-3.5ZM16 21h2.5v-3.5H22V15h-6v6ZM4 17.5h3.5V21H10v-6H4v2.5Zm3.5-11H4V9h6V3H7.5v3.5Z"/>
596
- </svg>`;function TE(s){return `
596
+ </svg>`;function yE(s){return `
597
597
  <style>
598
598
  :host([${chunkDITZCOYN_cjs.d.MEDIA_IS_FULLSCREEN}]) slot[name=icon] slot:not([name=exit]) {
599
599
  display: none !important;
@@ -611,13 +611,13 @@
611
611
  </style>
612
612
 
613
613
  <slot name="icon">
614
- <slot name="enter">${EE}</slot>
615
- <slot name="exit">${vE}</slot>
614
+ <slot name="enter">${vE}</slot>
615
+ <slot name="exit">${TE}</slot>
616
616
  </slot>
617
- `}function yE(){return `
617
+ `}function SE(){return `
618
618
  <slot name="tooltip-enter">${chunkDITZCOYN_cjs.n("Enter fullscreen mode")}</slot>
619
619
  <slot name="tooltip-exit">${chunkDITZCOYN_cjs.n("Exit fullscreen mode")}</slot>
620
- `}var If=s=>{let e=s.mediaIsFullscreen?chunkDITZCOYN_cjs.n("exit fullscreen mode"):chunkDITZCOYN_cjs.n("enter fullscreen mode");s.setAttribute("aria-label",e);},Rr=class extends chunkDITZCOYN_cjs.J{constructor(){super(...arguments),gE(this,ba,null);}static get observedAttributes(){return [...super.observedAttributes,chunkDITZCOYN_cjs.d.MEDIA_IS_FULLSCREEN,chunkDITZCOYN_cjs.d.MEDIA_FULLSCREEN_UNAVAILABLE]}connectedCallback(){super.connectedCallback(),If(this);}attributeChangedCallback(e,t,i){super.attributeChangedCallback(e,t,i),e===chunkDITZCOYN_cjs.d.MEDIA_IS_FULLSCREEN&&If(this);}get mediaFullscreenUnavailable(){return chunkDITZCOYN_cjs.H(this,chunkDITZCOYN_cjs.d.MEDIA_FULLSCREEN_UNAVAILABLE)}set mediaFullscreenUnavailable(e){chunkDITZCOYN_cjs.I(this,chunkDITZCOYN_cjs.d.MEDIA_FULLSCREEN_UNAVAILABLE,e);}get mediaIsFullscreen(){return chunkDITZCOYN_cjs.F(this,chunkDITZCOYN_cjs.d.MEDIA_IS_FULLSCREEN)}set mediaIsFullscreen(e){chunkDITZCOYN_cjs.G(this,chunkDITZCOYN_cjs.d.MEDIA_IS_FULLSCREEN,e);}handleClick(e){pE(this,ba,e);let t=mE(this,ba)instanceof PointerEvent,i=this.mediaIsFullscreen?new chunkDITZCOYN_cjs.o.CustomEvent(chunkDITZCOYN_cjs.a.MEDIA_EXIT_FULLSCREEN_REQUEST,{composed:true,bubbles:true}):new chunkDITZCOYN_cjs.o.CustomEvent(chunkDITZCOYN_cjs.a.MEDIA_ENTER_FULLSCREEN_REQUEST,{composed:true,bubbles:true,detail:t});this.dispatchEvent(i);}};ba=new WeakMap;Rr.getSlotTemplateHTML=TE;Rr.getTooltipContentHTML=yE;chunkDITZCOYN_cjs.o.customElements.get("media-fullscreen-button")||chunkDITZCOYN_cjs.o.customElements.define("media-fullscreen-button",Rr);var{MEDIA_TIME_IS_LIVE:_a,MEDIA_PAUSED:kr}=chunkDITZCOYN_cjs.d,{MEDIA_SEEK_TO_LIVE_REQUEST:SE,MEDIA_PLAY_REQUEST:AE}=chunkDITZCOYN_cjs.a,bE='<svg viewBox="0 0 6 12"><circle cx="3" cy="6" r="2"></circle></svg>';function _E(s){return `
620
+ `}var Lf=s=>{let e=s.mediaIsFullscreen?chunkDITZCOYN_cjs.n("exit fullscreen mode"):chunkDITZCOYN_cjs.n("enter fullscreen mode");s.setAttribute("aria-label",e);},Rr=class extends chunkDITZCOYN_cjs.J{constructor(){super(...arguments),pE(this,ba,null);}static get observedAttributes(){return [...super.observedAttributes,chunkDITZCOYN_cjs.d.MEDIA_IS_FULLSCREEN,chunkDITZCOYN_cjs.d.MEDIA_FULLSCREEN_UNAVAILABLE]}connectedCallback(){super.connectedCallback(),Lf(this);}attributeChangedCallback(e,t,i){super.attributeChangedCallback(e,t,i),e===chunkDITZCOYN_cjs.d.MEDIA_IS_FULLSCREEN&&Lf(this);}get mediaFullscreenUnavailable(){return chunkDITZCOYN_cjs.H(this,chunkDITZCOYN_cjs.d.MEDIA_FULLSCREEN_UNAVAILABLE)}set mediaFullscreenUnavailable(e){chunkDITZCOYN_cjs.I(this,chunkDITZCOYN_cjs.d.MEDIA_FULLSCREEN_UNAVAILABLE,e);}get mediaIsFullscreen(){return chunkDITZCOYN_cjs.F(this,chunkDITZCOYN_cjs.d.MEDIA_IS_FULLSCREEN)}set mediaIsFullscreen(e){chunkDITZCOYN_cjs.G(this,chunkDITZCOYN_cjs.d.MEDIA_IS_FULLSCREEN,e);}handleClick(e){EE(this,ba,e);let t=gE(this,ba)instanceof PointerEvent,i=this.mediaIsFullscreen?new chunkDITZCOYN_cjs.o.CustomEvent(chunkDITZCOYN_cjs.a.MEDIA_EXIT_FULLSCREEN_REQUEST,{composed:true,bubbles:true}):new chunkDITZCOYN_cjs.o.CustomEvent(chunkDITZCOYN_cjs.a.MEDIA_ENTER_FULLSCREEN_REQUEST,{composed:true,bubbles:true,detail:t});this.dispatchEvent(i);}};ba=new WeakMap;Rr.getSlotTemplateHTML=yE;Rr.getTooltipContentHTML=SE;chunkDITZCOYN_cjs.o.customElements.get("media-fullscreen-button")||chunkDITZCOYN_cjs.o.customElements.define("media-fullscreen-button",Rr);var{MEDIA_TIME_IS_LIVE:_a,MEDIA_PAUSED:kr}=chunkDITZCOYN_cjs.d,{MEDIA_SEEK_TO_LIVE_REQUEST:AE,MEDIA_PLAY_REQUEST:bE}=chunkDITZCOYN_cjs.a,_E='<svg viewBox="0 0 6 12"><circle cx="3" cy="6" r="2"></circle></svg>';function IE(s){return `
621
621
  <style>
622
622
  :host { --media-tooltip-display: none; }
623
623
 
@@ -645,10 +645,10 @@
645
645
 
646
646
  </style>
647
647
 
648
- <slot name="indicator">${bE}</slot>
648
+ <slot name="indicator">${_E}</slot>
649
649
 
650
650
  <slot name="spacer">&nbsp;</slot><slot name="text">${chunkDITZCOYN_cjs.n("live")}</slot>
651
- `}var xf=s=>{var e;let t=s.mediaPaused||!s.mediaTimeIsLive,i=t?chunkDITZCOYN_cjs.n("seek to live"):chunkDITZCOYN_cjs.n("playing live");s.setAttribute("aria-label",i);let r=(e=s.shadowRoot)==null?void 0:e.querySelector('slot[name="text"]');r&&(r.textContent=chunkDITZCOYN_cjs.n("live")),t?s.removeAttribute("aria-disabled"):s.setAttribute("aria-disabled","true");},Ia=class extends chunkDITZCOYN_cjs.J{static get observedAttributes(){return [...super.observedAttributes,_a,kr]}connectedCallback(){super.connectedCallback(),xf(this);}attributeChangedCallback(e,t,i){super.attributeChangedCallback(e,t,i),xf(this);}get mediaPaused(){return chunkDITZCOYN_cjs.F(this,chunkDITZCOYN_cjs.d.MEDIA_PAUSED)}set mediaPaused(e){chunkDITZCOYN_cjs.G(this,chunkDITZCOYN_cjs.d.MEDIA_PAUSED,e);}get mediaTimeIsLive(){return chunkDITZCOYN_cjs.F(this,chunkDITZCOYN_cjs.d.MEDIA_TIME_IS_LIVE)}set mediaTimeIsLive(e){chunkDITZCOYN_cjs.G(this,chunkDITZCOYN_cjs.d.MEDIA_TIME_IS_LIVE,e);}handleClick(){!this.mediaPaused&&this.mediaTimeIsLive||(this.dispatchEvent(new chunkDITZCOYN_cjs.o.CustomEvent(SE,{composed:true,bubbles:true})),this.hasAttribute(kr)&&this.dispatchEvent(new chunkDITZCOYN_cjs.o.CustomEvent(AE,{composed:true,bubbles:true})));}};Ia.getSlotTemplateHTML=_E;chunkDITZCOYN_cjs.o.customElements.get("media-live-button")||chunkDITZCOYN_cjs.o.customElements.define("media-live-button",Ia);var kf=(s,e,t)=>{if(!e.has(s))throw TypeError("Cannot "+t)},Dr=(s,e,t)=>(kf(s,e,"read from private field"),t?t.call(s):e.get(s)),Rf=(s,e,t)=>{if(e.has(s))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(s):e.set(s,t);},Cr=(s,e,t,i)=>(kf(s,e,"write to private field"),e.set(s,t),t),Xt,xa,La={LOADING_DELAY:"loadingdelay",NO_AUTOHIDE:"noautohide"},Df=500,IE=`
651
+ `}var Rf=s=>{var e;let t=s.mediaPaused||!s.mediaTimeIsLive,i=t?chunkDITZCOYN_cjs.n("seek to live"):chunkDITZCOYN_cjs.n("playing live");s.setAttribute("aria-label",i);let r=(e=s.shadowRoot)==null?void 0:e.querySelector('slot[name="text"]');r&&(r.textContent=chunkDITZCOYN_cjs.n("live")),t?s.removeAttribute("aria-disabled"):s.setAttribute("aria-disabled","true");},Ia=class extends chunkDITZCOYN_cjs.J{static get observedAttributes(){return [...super.observedAttributes,_a,kr]}connectedCallback(){super.connectedCallback(),Rf(this);}attributeChangedCallback(e,t,i){super.attributeChangedCallback(e,t,i),Rf(this);}get mediaPaused(){return chunkDITZCOYN_cjs.F(this,chunkDITZCOYN_cjs.d.MEDIA_PAUSED)}set mediaPaused(e){chunkDITZCOYN_cjs.G(this,chunkDITZCOYN_cjs.d.MEDIA_PAUSED,e);}get mediaTimeIsLive(){return chunkDITZCOYN_cjs.F(this,chunkDITZCOYN_cjs.d.MEDIA_TIME_IS_LIVE)}set mediaTimeIsLive(e){chunkDITZCOYN_cjs.G(this,chunkDITZCOYN_cjs.d.MEDIA_TIME_IS_LIVE,e);}handleClick(){!this.mediaPaused&&this.mediaTimeIsLive||(this.dispatchEvent(new chunkDITZCOYN_cjs.o.CustomEvent(AE,{composed:true,bubbles:true})),this.hasAttribute(kr)&&this.dispatchEvent(new chunkDITZCOYN_cjs.o.CustomEvent(bE,{composed:true,bubbles:true})));}};Ia.getSlotTemplateHTML=IE;chunkDITZCOYN_cjs.o.customElements.get("media-live-button")||chunkDITZCOYN_cjs.o.customElements.define("media-live-button",Ia);var Df=(s,e,t)=>{if(!e.has(s))throw TypeError("Cannot "+t)},Dr=(s,e,t)=>(Df(s,e,"read from private field"),t?t.call(s):e.get(s)),kf=(s,e,t)=>{if(e.has(s))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(s):e.set(s,t);},Cr=(s,e,t,i)=>(Df(s,e,"write to private field"),e.set(s,t),t),Xt,xa,La={LOADING_DELAY:"loadingdelay",NO_AUTOHIDE:"noautohide"},Cf=500,LE=`
652
652
  <svg aria-hidden="true" viewBox="0 0 100 100">
653
653
  <path d="M73,50c0-12.7-10.3-23-23-23S27,37.3,27,50 M30.9,50c0-10.5,8.5-19.1,19.1-19.1S69.1,39.5,69.1,50">
654
654
  <animateTransform
@@ -661,13 +661,13 @@
661
661
  repeatCount="indefinite" />
662
662
  </path>
663
663
  </svg>
664
- `;function LE(s){return `
664
+ `;function xE(s){return `
665
665
  <style>
666
666
  :host {
667
667
  display: var(--media-control-display, var(--media-loading-indicator-display, inline-block));
668
668
  vertical-align: middle;
669
669
  box-sizing: border-box;
670
- --_loading-indicator-delay: var(--media-loading-indicator-transition-delay, ${Df}ms);
670
+ --_loading-indicator-delay: var(--media-loading-indicator-transition-delay, ${Cf}ms);
671
671
  }
672
672
 
673
673
  #status {
@@ -706,15 +706,15 @@
706
706
  }
707
707
  </style>
708
708
 
709
- <slot name="icon">${IE}</slot>
709
+ <slot name="icon">${LE}</slot>
710
710
  <div id="status" role="status" aria-live="polite">${chunkDITZCOYN_cjs.n("media loading")}</div>
711
- `}var Mr=class extends chunkDITZCOYN_cjs.o.HTMLElement{constructor(){if(super(),Rf(this,Xt,void 0),Rf(this,xa,Df),!this.shadowRoot){this.attachShadow(this.constructor.shadowRootOptions);let e=chunkDITZCOYN_cjs.s(this.attributes);this.shadowRoot.innerHTML=this.constructor.getTemplateHTML(e);}}static get observedAttributes(){return [chunkDITZCOYN_cjs.b.MEDIA_CONTROLLER,chunkDITZCOYN_cjs.d.MEDIA_PAUSED,chunkDITZCOYN_cjs.d.MEDIA_LOADING,La.LOADING_DELAY]}attributeChangedCallback(e,t,i){var r,n,a,o,l;e===La.LOADING_DELAY&&t!==i?this.loadingDelay=Number(i):e===chunkDITZCOYN_cjs.b.MEDIA_CONTROLLER&&(t&&((n=(r=Dr(this,Xt))==null?void 0:r.unassociateElement)==null||n.call(r,this),Cr(this,Xt,null)),i&&this.isConnected&&(Cr(this,Xt,(a=this.getRootNode())==null?void 0:a.getElementById(i)),(l=(o=Dr(this,Xt))==null?void 0:o.associateElement)==null||l.call(o,this)));}connectedCallback(){var e,t,i;let r=this.getAttribute(chunkDITZCOYN_cjs.b.MEDIA_CONTROLLER);r&&(Cr(this,Xt,(e=this.getRootNode())==null?void 0:e.getElementById(r)),(i=(t=Dr(this,Xt))==null?void 0:t.associateElement)==null||i.call(t,this));}disconnectedCallback(){var e,t;(t=(e=Dr(this,Xt))==null?void 0:e.unassociateElement)==null||t.call(e,this),Cr(this,Xt,null);}get loadingDelay(){return Dr(this,xa)}set loadingDelay(e){Cr(this,xa,e);let{style:t}=chunkDITZCOYN_cjs.C(this.shadowRoot,":host");t.setProperty("--_loading-indicator-delay",`var(--media-loading-indicator-transition-delay, ${e}ms)`);}get mediaPaused(){return chunkDITZCOYN_cjs.F(this,chunkDITZCOYN_cjs.d.MEDIA_PAUSED)}set mediaPaused(e){chunkDITZCOYN_cjs.G(this,chunkDITZCOYN_cjs.d.MEDIA_PAUSED,e);}get mediaLoading(){return chunkDITZCOYN_cjs.F(this,chunkDITZCOYN_cjs.d.MEDIA_LOADING)}set mediaLoading(e){chunkDITZCOYN_cjs.G(this,chunkDITZCOYN_cjs.d.MEDIA_LOADING,e);}get mediaController(){return chunkDITZCOYN_cjs.H(this,chunkDITZCOYN_cjs.b.MEDIA_CONTROLLER)}set mediaController(e){chunkDITZCOYN_cjs.I(this,chunkDITZCOYN_cjs.b.MEDIA_CONTROLLER,e);}get noAutohide(){return chunkDITZCOYN_cjs.F(this,La.NO_AUTOHIDE)}set noAutohide(e){chunkDITZCOYN_cjs.G(this,La.NO_AUTOHIDE,e);}};Xt=new WeakMap;xa=new WeakMap;Mr.shadowRootOptions={mode:"open"};Mr.getTemplateHTML=LE;chunkDITZCOYN_cjs.o.customElements.get("media-loading-indicator")||chunkDITZCOYN_cjs.o.customElements.define("media-loading-indicator",Mr);var xE=`<svg aria-hidden="true" viewBox="0 0 24 24">
711
+ `}var Mr=class extends chunkDITZCOYN_cjs.o.HTMLElement{constructor(){if(super(),kf(this,Xt,void 0),kf(this,xa,Cf),!this.shadowRoot){this.attachShadow(this.constructor.shadowRootOptions);let e=chunkDITZCOYN_cjs.s(this.attributes);this.shadowRoot.innerHTML=this.constructor.getTemplateHTML(e);}}static get observedAttributes(){return [chunkDITZCOYN_cjs.b.MEDIA_CONTROLLER,chunkDITZCOYN_cjs.d.MEDIA_PAUSED,chunkDITZCOYN_cjs.d.MEDIA_LOADING,La.LOADING_DELAY]}attributeChangedCallback(e,t,i){var r,n,a,o,l;e===La.LOADING_DELAY&&t!==i?this.loadingDelay=Number(i):e===chunkDITZCOYN_cjs.b.MEDIA_CONTROLLER&&(t&&((n=(r=Dr(this,Xt))==null?void 0:r.unassociateElement)==null||n.call(r,this),Cr(this,Xt,null)),i&&this.isConnected&&(Cr(this,Xt,(a=this.getRootNode())==null?void 0:a.getElementById(i)),(l=(o=Dr(this,Xt))==null?void 0:o.associateElement)==null||l.call(o,this)));}connectedCallback(){var e,t,i;let r=this.getAttribute(chunkDITZCOYN_cjs.b.MEDIA_CONTROLLER);r&&(Cr(this,Xt,(e=this.getRootNode())==null?void 0:e.getElementById(r)),(i=(t=Dr(this,Xt))==null?void 0:t.associateElement)==null||i.call(t,this));}disconnectedCallback(){var e,t;(t=(e=Dr(this,Xt))==null?void 0:e.unassociateElement)==null||t.call(e,this),Cr(this,Xt,null);}get loadingDelay(){return Dr(this,xa)}set loadingDelay(e){Cr(this,xa,e);let{style:t}=chunkDITZCOYN_cjs.C(this.shadowRoot,":host");t.setProperty("--_loading-indicator-delay",`var(--media-loading-indicator-transition-delay, ${e}ms)`);}get mediaPaused(){return chunkDITZCOYN_cjs.F(this,chunkDITZCOYN_cjs.d.MEDIA_PAUSED)}set mediaPaused(e){chunkDITZCOYN_cjs.G(this,chunkDITZCOYN_cjs.d.MEDIA_PAUSED,e);}get mediaLoading(){return chunkDITZCOYN_cjs.F(this,chunkDITZCOYN_cjs.d.MEDIA_LOADING)}set mediaLoading(e){chunkDITZCOYN_cjs.G(this,chunkDITZCOYN_cjs.d.MEDIA_LOADING,e);}get mediaController(){return chunkDITZCOYN_cjs.H(this,chunkDITZCOYN_cjs.b.MEDIA_CONTROLLER)}set mediaController(e){chunkDITZCOYN_cjs.I(this,chunkDITZCOYN_cjs.b.MEDIA_CONTROLLER,e);}get noAutohide(){return chunkDITZCOYN_cjs.F(this,La.NO_AUTOHIDE)}set noAutohide(e){chunkDITZCOYN_cjs.G(this,La.NO_AUTOHIDE,e);}};Xt=new WeakMap;xa=new WeakMap;Mr.shadowRootOptions={mode:"open"};Mr.getTemplateHTML=xE;chunkDITZCOYN_cjs.o.customElements.get("media-loading-indicator")||chunkDITZCOYN_cjs.o.customElements.define("media-loading-indicator",Mr);var RE=`<svg aria-hidden="true" viewBox="0 0 24 24">
712
712
  <path d="M16.5 12A4.5 4.5 0 0 0 14 8v2.18l2.45 2.45a4.22 4.22 0 0 0 .05-.63Zm2.5 0a6.84 6.84 0 0 1-.54 2.64L20 16.15A8.8 8.8 0 0 0 21 12a9 9 0 0 0-7-8.77v2.06A7 7 0 0 1 19 12ZM4.27 3 3 4.27 7.73 9H3v6h4l5 5v-6.73l4.25 4.25A6.92 6.92 0 0 1 14 18.7v2.06A9 9 0 0 0 17.69 19l2 2.05L21 19.73l-9-9L4.27 3ZM12 4 9.91 6.09 12 8.18V4Z"/>
713
- </svg>`,Cf=`<svg aria-hidden="true" viewBox="0 0 24 24">
713
+ </svg>`,Mf=`<svg aria-hidden="true" viewBox="0 0 24 24">
714
714
  <path d="M3 9v6h4l5 5V4L7 9H3Zm13.5 3A4.5 4.5 0 0 0 14 8v8a4.47 4.47 0 0 0 2.5-4Z"/>
715
- </svg>`,RE=`<svg aria-hidden="true" viewBox="0 0 24 24">
715
+ </svg>`,kE=`<svg aria-hidden="true" viewBox="0 0 24 24">
716
716
  <path d="M3 9v6h4l5 5V4L7 9H3Zm13.5 3A4.5 4.5 0 0 0 14 8v8a4.47 4.47 0 0 0 2.5-4ZM14 3.23v2.06a7 7 0 0 1 0 13.42v2.06a9 9 0 0 0 0-17.54Z"/>
717
- </svg>`;function kE(s){return `
717
+ </svg>`;function DE(s){return `
718
718
  <style>
719
719
  :host(:not([${chunkDITZCOYN_cjs.d.MEDIA_VOLUME_LEVEL}])) slot[name=icon] slot:not([name=high]),
720
720
  :host([${chunkDITZCOYN_cjs.d.MEDIA_VOLUME_LEVEL}=high]) slot[name=icon] slot:not([name=high]) {
@@ -740,17 +740,17 @@
740
740
  </style>
741
741
 
742
742
  <slot name="icon">
743
- <slot name="off">${xE}</slot>
744
- <slot name="low">${Cf}</slot>
745
- <slot name="medium">${Cf}</slot>
746
- <slot name="high">${RE}</slot>
743
+ <slot name="off">${RE}</slot>
744
+ <slot name="low">${Mf}</slot>
745
+ <slot name="medium">${Mf}</slot>
746
+ <slot name="high">${kE}</slot>
747
747
  </slot>
748
- `}function DE(){return `
748
+ `}function CE(){return `
749
749
  <slot name="tooltip-mute">${chunkDITZCOYN_cjs.n("Mute")}</slot>
750
750
  <slot name="tooltip-unmute">${chunkDITZCOYN_cjs.n("Unmute")}</slot>
751
- `}var Mf=s=>{let t=s.mediaVolumeLevel==="off"?chunkDITZCOYN_cjs.n("unmute"):chunkDITZCOYN_cjs.n("mute");s.setAttribute("aria-label",t);},Pr=class extends chunkDITZCOYN_cjs.J{static get observedAttributes(){return [...super.observedAttributes,chunkDITZCOYN_cjs.d.MEDIA_VOLUME_LEVEL]}connectedCallback(){super.connectedCallback(),Mf(this);}attributeChangedCallback(e,t,i){super.attributeChangedCallback(e,t,i),e===chunkDITZCOYN_cjs.d.MEDIA_VOLUME_LEVEL&&Mf(this);}get mediaVolumeLevel(){return chunkDITZCOYN_cjs.H(this,chunkDITZCOYN_cjs.d.MEDIA_VOLUME_LEVEL)}set mediaVolumeLevel(e){chunkDITZCOYN_cjs.I(this,chunkDITZCOYN_cjs.d.MEDIA_VOLUME_LEVEL,e);}handleClick(){let e=this.mediaVolumeLevel==="off"?chunkDITZCOYN_cjs.a.MEDIA_UNMUTE_REQUEST:chunkDITZCOYN_cjs.a.MEDIA_MUTE_REQUEST;this.dispatchEvent(new chunkDITZCOYN_cjs.o.CustomEvent(e,{composed:true,bubbles:true}));}};Pr.getSlotTemplateHTML=kE;Pr.getTooltipContentHTML=DE;chunkDITZCOYN_cjs.o.customElements.get("media-mute-button")||chunkDITZCOYN_cjs.o.customElements.define("media-mute-button",Pr);var Pf=`<svg aria-hidden="true" viewBox="0 0 28 24">
751
+ `}var Pf=s=>{let t=s.mediaVolumeLevel==="off"?chunkDITZCOYN_cjs.n("unmute"):chunkDITZCOYN_cjs.n("mute");s.setAttribute("aria-label",t);},Pr=class extends chunkDITZCOYN_cjs.J{static get observedAttributes(){return [...super.observedAttributes,chunkDITZCOYN_cjs.d.MEDIA_VOLUME_LEVEL]}connectedCallback(){super.connectedCallback(),Pf(this);}attributeChangedCallback(e,t,i){super.attributeChangedCallback(e,t,i),e===chunkDITZCOYN_cjs.d.MEDIA_VOLUME_LEVEL&&Pf(this);}get mediaVolumeLevel(){return chunkDITZCOYN_cjs.H(this,chunkDITZCOYN_cjs.d.MEDIA_VOLUME_LEVEL)}set mediaVolumeLevel(e){chunkDITZCOYN_cjs.I(this,chunkDITZCOYN_cjs.d.MEDIA_VOLUME_LEVEL,e);}handleClick(){let e=this.mediaVolumeLevel==="off"?chunkDITZCOYN_cjs.a.MEDIA_UNMUTE_REQUEST:chunkDITZCOYN_cjs.a.MEDIA_MUTE_REQUEST;this.dispatchEvent(new chunkDITZCOYN_cjs.o.CustomEvent(e,{composed:true,bubbles:true}));}};Pr.getSlotTemplateHTML=DE;Pr.getTooltipContentHTML=CE;chunkDITZCOYN_cjs.o.customElements.get("media-mute-button")||chunkDITZCOYN_cjs.o.customElements.define("media-mute-button",Pr);var wf=`<svg aria-hidden="true" viewBox="0 0 28 24">
752
752
  <path d="M24 3H4a1 1 0 0 0-1 1v16a1 1 0 0 0 1 1h20a1 1 0 0 0 1-1V4a1 1 0 0 0-1-1Zm-1 16H5V5h18v14Zm-3-8h-7v5h7v-5Z"/>
753
- </svg>`;function CE(s){return `
753
+ </svg>`;function ME(s){return `
754
754
  <style>
755
755
  :host([${chunkDITZCOYN_cjs.d.MEDIA_IS_PIP}]) slot[name=icon] slot:not([name=exit]) {
756
756
  display: none !important;
@@ -767,13 +767,13 @@
767
767
  </style>
768
768
 
769
769
  <slot name="icon">
770
- <slot name="enter">${Pf}</slot>
771
- <slot name="exit">${Pf}</slot>
770
+ <slot name="enter">${wf}</slot>
771
+ <slot name="exit">${wf}</slot>
772
772
  </slot>
773
- `}function ME(){return `
773
+ `}function PE(){return `
774
774
  <slot name="tooltip-enter">${chunkDITZCOYN_cjs.n("Enter picture in picture mode")}</slot>
775
775
  <slot name="tooltip-exit">${chunkDITZCOYN_cjs.n("Exit picture in picture mode")}</slot>
776
- `}var wf=s=>{let e=s.mediaIsPip?chunkDITZCOYN_cjs.n("exit picture in picture mode"):chunkDITZCOYN_cjs.n("enter picture in picture mode");s.setAttribute("aria-label",e);},wr=class extends chunkDITZCOYN_cjs.J{static get observedAttributes(){return [...super.observedAttributes,chunkDITZCOYN_cjs.d.MEDIA_IS_PIP,chunkDITZCOYN_cjs.d.MEDIA_PIP_UNAVAILABLE]}connectedCallback(){super.connectedCallback(),wf(this);}attributeChangedCallback(e,t,i){super.attributeChangedCallback(e,t,i),e===chunkDITZCOYN_cjs.d.MEDIA_IS_PIP&&wf(this);}get mediaPipUnavailable(){return chunkDITZCOYN_cjs.H(this,chunkDITZCOYN_cjs.d.MEDIA_PIP_UNAVAILABLE)}set mediaPipUnavailable(e){chunkDITZCOYN_cjs.I(this,chunkDITZCOYN_cjs.d.MEDIA_PIP_UNAVAILABLE,e);}get mediaIsPip(){return chunkDITZCOYN_cjs.F(this,chunkDITZCOYN_cjs.d.MEDIA_IS_PIP)}set mediaIsPip(e){chunkDITZCOYN_cjs.G(this,chunkDITZCOYN_cjs.d.MEDIA_IS_PIP,e);}handleClick(){let e=this.mediaIsPip?chunkDITZCOYN_cjs.a.MEDIA_EXIT_PIP_REQUEST:chunkDITZCOYN_cjs.a.MEDIA_ENTER_PIP_REQUEST;this.dispatchEvent(new chunkDITZCOYN_cjs.o.CustomEvent(e,{composed:true,bubbles:true}));}};wr.getSlotTemplateHTML=CE;wr.getTooltipContentHTML=ME;chunkDITZCOYN_cjs.o.customElements.get("media-pip-button")||chunkDITZCOYN_cjs.o.customElements.define("media-pip-button",wr);var PE=(s,e,t)=>{if(!e.has(s))throw TypeError("Cannot "+t)},Is=(s,e,t)=>(PE(s,e,"read from private field"),t?t.call(s):e.get(s)),wE=(s,e,t)=>{if(e.has(s))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(s):e.set(s,t);},Di,id={RATES:"rates"},sd=[1,1.2,1.5,1.7,2],Xi=1;function OE(s){return `
776
+ `}var Of=s=>{let e=s.mediaIsPip?chunkDITZCOYN_cjs.n("exit picture in picture mode"):chunkDITZCOYN_cjs.n("enter picture in picture mode");s.setAttribute("aria-label",e);},wr=class extends chunkDITZCOYN_cjs.J{static get observedAttributes(){return [...super.observedAttributes,chunkDITZCOYN_cjs.d.MEDIA_IS_PIP,chunkDITZCOYN_cjs.d.MEDIA_PIP_UNAVAILABLE]}connectedCallback(){super.connectedCallback(),Of(this);}attributeChangedCallback(e,t,i){super.attributeChangedCallback(e,t,i),e===chunkDITZCOYN_cjs.d.MEDIA_IS_PIP&&Of(this);}get mediaPipUnavailable(){return chunkDITZCOYN_cjs.H(this,chunkDITZCOYN_cjs.d.MEDIA_PIP_UNAVAILABLE)}set mediaPipUnavailable(e){chunkDITZCOYN_cjs.I(this,chunkDITZCOYN_cjs.d.MEDIA_PIP_UNAVAILABLE,e);}get mediaIsPip(){return chunkDITZCOYN_cjs.F(this,chunkDITZCOYN_cjs.d.MEDIA_IS_PIP)}set mediaIsPip(e){chunkDITZCOYN_cjs.G(this,chunkDITZCOYN_cjs.d.MEDIA_IS_PIP,e);}handleClick(){let e=this.mediaIsPip?chunkDITZCOYN_cjs.a.MEDIA_EXIT_PIP_REQUEST:chunkDITZCOYN_cjs.a.MEDIA_ENTER_PIP_REQUEST;this.dispatchEvent(new chunkDITZCOYN_cjs.o.CustomEvent(e,{composed:true,bubbles:true}));}};wr.getSlotTemplateHTML=ME;wr.getTooltipContentHTML=PE;chunkDITZCOYN_cjs.o.customElements.get("media-pip-button")||chunkDITZCOYN_cjs.o.customElements.define("media-pip-button",wr);var wE=(s,e,t)=>{if(!e.has(s))throw TypeError("Cannot "+t)},Is=(s,e,t)=>(wE(s,e,"read from private field"),t?t.call(s):e.get(s)),OE=(s,e,t)=>{if(e.has(s))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(s):e.set(s,t);},Di,id={RATES:"rates"},sd=[1,1.2,1.5,1.7,2],Xi=1;function FE(s){return `
777
777
  <style>
778
778
  :host {
779
779
  min-width: 5ch;
@@ -781,11 +781,11 @@
781
781
  }
782
782
  </style>
783
783
  <slot name="icon">${s.mediaplaybackrate||Xi}x</slot>
784
- `}function FE(){return chunkDITZCOYN_cjs.n("Playback rate")}var Or=class extends chunkDITZCOYN_cjs.J{constructor(){var e;super(),wE(this,Di,new Ii(this,id.RATES,{defaultValue:sd})),this.container=this.shadowRoot.querySelector('slot[name="icon"]'),this.container.innerHTML=`${(e=this.mediaPlaybackRate)!=null?e:Xi}x`;}static get observedAttributes(){return [...super.observedAttributes,chunkDITZCOYN_cjs.d.MEDIA_PLAYBACK_RATE,id.RATES]}attributeChangedCallback(e,t,i){if(super.attributeChangedCallback(e,t,i),e===id.RATES&&(Is(this,Di).value=i),e===chunkDITZCOYN_cjs.d.MEDIA_PLAYBACK_RATE){let r=i?+i:Number.NaN,n=Number.isNaN(r)?Xi:r;this.container.innerHTML=`${n}x`,this.setAttribute("aria-label",chunkDITZCOYN_cjs.n("Playback rate {playbackRate}",{playbackRate:n}));}}get rates(){return Is(this,Di)}set rates(e){e?Array.isArray(e)?Is(this,Di).value=e.join(" "):typeof e=="string"&&(Is(this,Di).value=e):Is(this,Di).value="";}get mediaPlaybackRate(){return chunkDITZCOYN_cjs.D(this,chunkDITZCOYN_cjs.d.MEDIA_PLAYBACK_RATE,Xi)}set mediaPlaybackRate(e){chunkDITZCOYN_cjs.E(this,chunkDITZCOYN_cjs.d.MEDIA_PLAYBACK_RATE,e);}handleClick(){var e,t;let i=Array.from(Is(this,Di).values(),a=>+a).sort((a,o)=>a-o),r=(t=(e=i.find(a=>a>this.mediaPlaybackRate))!=null?e:i[0])!=null?t:Xi,n=new chunkDITZCOYN_cjs.o.CustomEvent(chunkDITZCOYN_cjs.a.MEDIA_PLAYBACK_RATE_REQUEST,{composed:true,bubbles:true,detail:r});this.dispatchEvent(n);}};Di=new WeakMap;Or.getSlotTemplateHTML=OE;Or.getTooltipContentHTML=FE;chunkDITZCOYN_cjs.o.customElements.get("media-playback-rate-button")||chunkDITZCOYN_cjs.o.customElements.define("media-playback-rate-button",Or);var NE=`<svg aria-hidden="true" viewBox="0 0 24 24">
784
+ `}function NE(){return chunkDITZCOYN_cjs.n("Playback rate")}var Or=class extends chunkDITZCOYN_cjs.J{constructor(){var e;super(),OE(this,Di,new Ii(this,id.RATES,{defaultValue:sd})),this.container=this.shadowRoot.querySelector('slot[name="icon"]'),this.container.innerHTML=`${(e=this.mediaPlaybackRate)!=null?e:Xi}x`;}static get observedAttributes(){return [...super.observedAttributes,chunkDITZCOYN_cjs.d.MEDIA_PLAYBACK_RATE,id.RATES]}attributeChangedCallback(e,t,i){if(super.attributeChangedCallback(e,t,i),e===id.RATES&&(Is(this,Di).value=i),e===chunkDITZCOYN_cjs.d.MEDIA_PLAYBACK_RATE){let r=i?+i:Number.NaN,n=Number.isNaN(r)?Xi:r;this.container.innerHTML=`${n}x`,this.setAttribute("aria-label",chunkDITZCOYN_cjs.n("Playback rate {playbackRate}",{playbackRate:n}));}}get rates(){return Is(this,Di)}set rates(e){e?Array.isArray(e)?Is(this,Di).value=e.join(" "):typeof e=="string"&&(Is(this,Di).value=e):Is(this,Di).value="";}get mediaPlaybackRate(){return chunkDITZCOYN_cjs.D(this,chunkDITZCOYN_cjs.d.MEDIA_PLAYBACK_RATE,Xi)}set mediaPlaybackRate(e){chunkDITZCOYN_cjs.E(this,chunkDITZCOYN_cjs.d.MEDIA_PLAYBACK_RATE,e);}handleClick(){var e,t;let i=Array.from(Is(this,Di).values(),a=>+a).sort((a,o)=>a-o),r=(t=(e=i.find(a=>a>this.mediaPlaybackRate))!=null?e:i[0])!=null?t:Xi,n=new chunkDITZCOYN_cjs.o.CustomEvent(chunkDITZCOYN_cjs.a.MEDIA_PLAYBACK_RATE_REQUEST,{composed:true,bubbles:true,detail:r});this.dispatchEvent(n);}};Di=new WeakMap;Or.getSlotTemplateHTML=FE;Or.getTooltipContentHTML=NE;chunkDITZCOYN_cjs.o.customElements.get("media-playback-rate-button")||chunkDITZCOYN_cjs.o.customElements.define("media-playback-rate-button",Or);var UE=`<svg aria-hidden="true" viewBox="0 0 24 24">
785
785
  <path d="m6 21 15-9L6 3v18Z"/>
786
- </svg>`,UE=`<svg aria-hidden="true" viewBox="0 0 24 24">
786
+ </svg>`,BE=`<svg aria-hidden="true" viewBox="0 0 24 24">
787
787
  <path d="M6 20h4V4H6v16Zm8-16v16h4V4h-4Z"/>
788
- </svg>`;function BE(s){return `
788
+ </svg>`;function $E(s){return `
789
789
  <style>
790
790
  :host([${chunkDITZCOYN_cjs.d.MEDIA_PAUSED}]) slot[name=pause],
791
791
  :host(:not([${chunkDITZCOYN_cjs.d.MEDIA_PAUSED}])) slot[name=play] {
@@ -799,13 +799,13 @@
799
799
  </style>
800
800
 
801
801
  <slot name="icon">
802
- <slot name="play">${NE}</slot>
803
- <slot name="pause">${UE}</slot>
802
+ <slot name="play">${UE}</slot>
803
+ <slot name="pause">${BE}</slot>
804
804
  </slot>
805
- `}function $E(){return `
805
+ `}function GE(){return `
806
806
  <slot name="tooltip-play">${chunkDITZCOYN_cjs.n("Play")}</slot>
807
807
  <slot name="tooltip-pause">${chunkDITZCOYN_cjs.n("Pause")}</slot>
808
- `}var Of=s=>{let e=s.mediaPaused?chunkDITZCOYN_cjs.n("play"):chunkDITZCOYN_cjs.n("pause");s.setAttribute("aria-label",e);},Fr=class extends chunkDITZCOYN_cjs.J{static get observedAttributes(){return [...super.observedAttributes,chunkDITZCOYN_cjs.d.MEDIA_PAUSED,chunkDITZCOYN_cjs.d.MEDIA_ENDED]}connectedCallback(){super.connectedCallback(),Of(this);}attributeChangedCallback(e,t,i){super.attributeChangedCallback(e,t,i),(e===chunkDITZCOYN_cjs.d.MEDIA_PAUSED||e===chunkDITZCOYN_cjs.d.MEDIA_LANG)&&Of(this);}get mediaPaused(){return chunkDITZCOYN_cjs.F(this,chunkDITZCOYN_cjs.d.MEDIA_PAUSED)}set mediaPaused(e){chunkDITZCOYN_cjs.G(this,chunkDITZCOYN_cjs.d.MEDIA_PAUSED,e);}handleClick(){let e=this.mediaPaused?chunkDITZCOYN_cjs.a.MEDIA_PLAY_REQUEST:chunkDITZCOYN_cjs.a.MEDIA_PAUSE_REQUEST;this.dispatchEvent(new chunkDITZCOYN_cjs.o.CustomEvent(e,{composed:true,bubbles:true}));}};Fr.getSlotTemplateHTML=BE;Fr.getTooltipContentHTML=$E;chunkDITZCOYN_cjs.o.customElements.get("media-play-button")||chunkDITZCOYN_cjs.o.customElements.define("media-play-button",Fr);var Zt={PLACEHOLDER_SRC:"placeholdersrc",SRC:"src"};function GE(s){return `
808
+ `}var Ff=s=>{let e=s.mediaPaused?chunkDITZCOYN_cjs.n("play"):chunkDITZCOYN_cjs.n("pause");s.setAttribute("aria-label",e);},Fr=class extends chunkDITZCOYN_cjs.J{static get observedAttributes(){return [...super.observedAttributes,chunkDITZCOYN_cjs.d.MEDIA_PAUSED,chunkDITZCOYN_cjs.d.MEDIA_ENDED]}connectedCallback(){super.connectedCallback(),Ff(this);}attributeChangedCallback(e,t,i){super.attributeChangedCallback(e,t,i),(e===chunkDITZCOYN_cjs.d.MEDIA_PAUSED||e===chunkDITZCOYN_cjs.d.MEDIA_LANG)&&Ff(this);}get mediaPaused(){return chunkDITZCOYN_cjs.F(this,chunkDITZCOYN_cjs.d.MEDIA_PAUSED)}set mediaPaused(e){chunkDITZCOYN_cjs.G(this,chunkDITZCOYN_cjs.d.MEDIA_PAUSED,e);}handleClick(){let e=this.mediaPaused?chunkDITZCOYN_cjs.a.MEDIA_PLAY_REQUEST:chunkDITZCOYN_cjs.a.MEDIA_PAUSE_REQUEST;this.dispatchEvent(new chunkDITZCOYN_cjs.o.CustomEvent(e,{composed:true,bubbles:true}));}};Fr.getSlotTemplateHTML=$E;Fr.getTooltipContentHTML=GE;chunkDITZCOYN_cjs.o.customElements.get("media-play-button")||chunkDITZCOYN_cjs.o.customElements.define("media-play-button",Fr);var Zt={PLACEHOLDER_SRC:"placeholdersrc",SRC:"src"};function HE(s){return `
809
809
  <style>
810
810
  :host {
811
811
  pointer-events: none;
@@ -827,7 +827,7 @@
827
827
  </style>
828
828
 
829
829
  <img part="poster img" aria-hidden="true" id="image"/>
830
- `}var HE=s=>{s.style.removeProperty("background-image");},KE=(s,e)=>{s.style["background-image"]=`url('${e}')`;},Nr=class extends chunkDITZCOYN_cjs.o.HTMLElement{static get observedAttributes(){return [Zt.PLACEHOLDER_SRC,Zt.SRC]}constructor(){if(super(),!this.shadowRoot){this.attachShadow(this.constructor.shadowRootOptions);let e=chunkDITZCOYN_cjs.s(this.attributes);this.shadowRoot.innerHTML=this.constructor.getTemplateHTML(e);}this.image=this.shadowRoot.querySelector("#image");}attributeChangedCallback(e,t,i){e===Zt.SRC&&(i==null?this.image.removeAttribute(Zt.SRC):this.image.setAttribute(Zt.SRC,i)),e===Zt.PLACEHOLDER_SRC&&(i==null?HE(this.image):KE(this.image,i));}get placeholderSrc(){return chunkDITZCOYN_cjs.H(this,Zt.PLACEHOLDER_SRC)}set placeholderSrc(e){chunkDITZCOYN_cjs.I(this,Zt.SRC,e);}get src(){return chunkDITZCOYN_cjs.H(this,Zt.SRC)}set src(e){chunkDITZCOYN_cjs.I(this,Zt.SRC,e);}};Nr.shadowRootOptions={mode:"open"};Nr.getTemplateHTML=GE;chunkDITZCOYN_cjs.o.customElements.get("media-poster-image")||chunkDITZCOYN_cjs.o.customElements.define("media-poster-image",Nr);var Ff=(s,e,t)=>{if(!e.has(s))throw TypeError("Cannot "+t)},VE=(s,e,t)=>(Ff(s,e,"read from private field"),t?t.call(s):e.get(s)),WE=(s,e,t)=>{if(e.has(s))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(s):e.set(s,t);},YE=(s,e,t,i)=>(Ff(s,e,"write to private field"),e.set(s,t),t),Ra,rd=class extends dt{constructor(){super(),WE(this,Ra,void 0),YE(this,Ra,this.shadowRoot.querySelector("slot"));}static get observedAttributes(){return [...super.observedAttributes,chunkDITZCOYN_cjs.d.MEDIA_PREVIEW_CHAPTER,chunkDITZCOYN_cjs.d.MEDIA_LANG]}attributeChangedCallback(e,t,i){if(super.attributeChangedCallback(e,t,i),(e===chunkDITZCOYN_cjs.d.MEDIA_PREVIEW_CHAPTER||e===chunkDITZCOYN_cjs.d.MEDIA_LANG)&&i!==t&&i!=null)if(VE(this,Ra).textContent=i,i!==""){let r=chunkDITZCOYN_cjs.n("chapter: {chapterName}",{chapterName:i});this.setAttribute("aria-valuetext",r);}else this.removeAttribute("aria-valuetext");}get mediaPreviewChapter(){return chunkDITZCOYN_cjs.H(this,chunkDITZCOYN_cjs.d.MEDIA_PREVIEW_CHAPTER)}set mediaPreviewChapter(e){chunkDITZCOYN_cjs.I(this,chunkDITZCOYN_cjs.d.MEDIA_PREVIEW_CHAPTER,e);}};Ra=new WeakMap;chunkDITZCOYN_cjs.o.customElements.get("media-preview-chapter-display")||chunkDITZCOYN_cjs.o.customElements.define("media-preview-chapter-display",rd);var Nf=(s,e,t)=>{if(!e.has(s))throw TypeError("Cannot "+t)},ka=(s,e,t)=>(Nf(s,e,"read from private field"),t?t.call(s):e.get(s)),qE=(s,e,t)=>{if(e.has(s))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(s):e.set(s,t);},Da=(s,e,t,i)=>(Nf(s,e,"write to private field"),e.set(s,t),t),Jt;function jE(s){return `
830
+ `}var KE=s=>{s.style.removeProperty("background-image");},VE=(s,e)=>{s.style["background-image"]=`url('${e}')`;},Nr=class extends chunkDITZCOYN_cjs.o.HTMLElement{static get observedAttributes(){return [Zt.PLACEHOLDER_SRC,Zt.SRC]}constructor(){if(super(),!this.shadowRoot){this.attachShadow(this.constructor.shadowRootOptions);let e=chunkDITZCOYN_cjs.s(this.attributes);this.shadowRoot.innerHTML=this.constructor.getTemplateHTML(e);}this.image=this.shadowRoot.querySelector("#image");}attributeChangedCallback(e,t,i){e===Zt.SRC&&(i==null?this.image.removeAttribute(Zt.SRC):this.image.setAttribute(Zt.SRC,i)),e===Zt.PLACEHOLDER_SRC&&(i==null?KE(this.image):VE(this.image,i));}get placeholderSrc(){return chunkDITZCOYN_cjs.H(this,Zt.PLACEHOLDER_SRC)}set placeholderSrc(e){chunkDITZCOYN_cjs.I(this,Zt.SRC,e);}get src(){return chunkDITZCOYN_cjs.H(this,Zt.SRC)}set src(e){chunkDITZCOYN_cjs.I(this,Zt.SRC,e);}};Nr.shadowRootOptions={mode:"open"};Nr.getTemplateHTML=HE;chunkDITZCOYN_cjs.o.customElements.get("media-poster-image")||chunkDITZCOYN_cjs.o.customElements.define("media-poster-image",Nr);var Nf=(s,e,t)=>{if(!e.has(s))throw TypeError("Cannot "+t)},WE=(s,e,t)=>(Nf(s,e,"read from private field"),t?t.call(s):e.get(s)),YE=(s,e,t)=>{if(e.has(s))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(s):e.set(s,t);},qE=(s,e,t,i)=>(Nf(s,e,"write to private field"),e.set(s,t),t),Ra,rd=class extends dt{constructor(){super(),YE(this,Ra,void 0),qE(this,Ra,this.shadowRoot.querySelector("slot"));}static get observedAttributes(){return [...super.observedAttributes,chunkDITZCOYN_cjs.d.MEDIA_PREVIEW_CHAPTER,chunkDITZCOYN_cjs.d.MEDIA_LANG]}attributeChangedCallback(e,t,i){if(super.attributeChangedCallback(e,t,i),(e===chunkDITZCOYN_cjs.d.MEDIA_PREVIEW_CHAPTER||e===chunkDITZCOYN_cjs.d.MEDIA_LANG)&&i!==t&&i!=null)if(WE(this,Ra).textContent=i,i!==""){let r=chunkDITZCOYN_cjs.n("chapter: {chapterName}",{chapterName:i});this.setAttribute("aria-valuetext",r);}else this.removeAttribute("aria-valuetext");}get mediaPreviewChapter(){return chunkDITZCOYN_cjs.H(this,chunkDITZCOYN_cjs.d.MEDIA_PREVIEW_CHAPTER)}set mediaPreviewChapter(e){chunkDITZCOYN_cjs.I(this,chunkDITZCOYN_cjs.d.MEDIA_PREVIEW_CHAPTER,e);}};Ra=new WeakMap;chunkDITZCOYN_cjs.o.customElements.get("media-preview-chapter-display")||chunkDITZCOYN_cjs.o.customElements.define("media-preview-chapter-display",rd);var Uf=(s,e,t)=>{if(!e.has(s))throw TypeError("Cannot "+t)},ka=(s,e,t)=>(Uf(s,e,"read from private field"),t?t.call(s):e.get(s)),jE=(s,e,t)=>{if(e.has(s))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(s):e.set(s,t);},Da=(s,e,t,i)=>(Uf(s,e,"write to private field"),e.set(s,t),t),Jt;function zE(s){return `
831
831
  <style>
832
832
  :host {
833
833
  box-sizing: border-box;
@@ -841,27 +841,27 @@
841
841
  }
842
842
  </style>
843
843
  <img crossorigin loading="eager" decoding="async">
844
- `}var Ls=class extends chunkDITZCOYN_cjs.o.HTMLElement{constructor(){if(super(),qE(this,Jt,void 0),!this.shadowRoot){this.attachShadow(this.constructor.shadowRootOptions);let e=chunkDITZCOYN_cjs.s(this.attributes);this.shadowRoot.innerHTML=this.constructor.getTemplateHTML(e);}}static get observedAttributes(){return [chunkDITZCOYN_cjs.b.MEDIA_CONTROLLER,chunkDITZCOYN_cjs.d.MEDIA_PREVIEW_IMAGE,chunkDITZCOYN_cjs.d.MEDIA_PREVIEW_COORDS]}connectedCallback(){var e,t,i;let r=this.getAttribute(chunkDITZCOYN_cjs.b.MEDIA_CONTROLLER);r&&(Da(this,Jt,(e=this.getRootNode())==null?void 0:e.getElementById(r)),(i=(t=ka(this,Jt))==null?void 0:t.associateElement)==null||i.call(t,this));}disconnectedCallback(){var e,t;(t=(e=ka(this,Jt))==null?void 0:e.unassociateElement)==null||t.call(e,this),Da(this,Jt,null);}attributeChangedCallback(e,t,i){var r,n,a,o,l;[chunkDITZCOYN_cjs.d.MEDIA_PREVIEW_IMAGE,chunkDITZCOYN_cjs.d.MEDIA_PREVIEW_COORDS].includes(e)&&this.update(),e===chunkDITZCOYN_cjs.b.MEDIA_CONTROLLER&&(t&&((n=(r=ka(this,Jt))==null?void 0:r.unassociateElement)==null||n.call(r,this),Da(this,Jt,null)),i&&this.isConnected&&(Da(this,Jt,(a=this.getRootNode())==null?void 0:a.getElementById(i)),(l=(o=ka(this,Jt))==null?void 0:o.associateElement)==null||l.call(o,this)));}get mediaPreviewImage(){return chunkDITZCOYN_cjs.H(this,chunkDITZCOYN_cjs.d.MEDIA_PREVIEW_IMAGE)}set mediaPreviewImage(e){chunkDITZCOYN_cjs.I(this,chunkDITZCOYN_cjs.d.MEDIA_PREVIEW_IMAGE,e);}get mediaPreviewCoords(){let e=this.getAttribute(chunkDITZCOYN_cjs.d.MEDIA_PREVIEW_COORDS);if(e)return e.split(/\s+/).map(t=>+t)}set mediaPreviewCoords(e){if(!e){this.removeAttribute(chunkDITZCOYN_cjs.d.MEDIA_PREVIEW_COORDS);return}this.setAttribute(chunkDITZCOYN_cjs.d.MEDIA_PREVIEW_COORDS,e.join(" "));}update(){let e=this.mediaPreviewCoords,t=this.mediaPreviewImage;if(!(e&&t))return;let[i,r,n,a]=e,o=t.split("#")[0],l=getComputedStyle(this),{maxWidth:d,maxHeight:c,minWidth:u,minHeight:h}=l,f=Math.min(parseInt(d)/n,parseInt(c)/a),m=Math.max(parseInt(u)/n,parseInt(h)/a),p=f<1,E=p?f:m>1?m:1,{style:v}=chunkDITZCOYN_cjs.C(this.shadowRoot,":host"),T=chunkDITZCOYN_cjs.C(this.shadowRoot,"img").style,S=this.shadowRoot.querySelector("img"),A=p?"min":"max";v.setProperty(`${A}-width`,"initial","important"),v.setProperty(`${A}-height`,"initial","important"),v.width=`${n*E}px`,v.height=`${a*E}px`;let b=()=>{T.width=`${this.imgWidth*E}px`,T.height=`${this.imgHeight*E}px`,T.display="block";};S.src!==o&&(S.onload=()=>{this.imgWidth=S.naturalWidth,this.imgHeight=S.naturalHeight,b();},S.src=o,b()),b(),T.transform=`translate(-${i*E}px, -${r*E}px)`;}};Jt=new WeakMap;Ls.shadowRootOptions={mode:"open"};Ls.getTemplateHTML=jE;chunkDITZCOYN_cjs.o.customElements.get("media-preview-thumbnail")||chunkDITZCOYN_cjs.o.customElements.define("media-preview-thumbnail",Ls);var Ca=Ls;var Bf=(s,e,t)=>{if(!e.has(s))throw TypeError("Cannot "+t)},Uf=(s,e,t)=>(Bf(s,e,"read from private field"),t?t.call(s):e.get(s)),zE=(s,e,t)=>{if(e.has(s))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(s):e.set(s,t);},QE=(s,e,t,i)=>(Bf(s,e,"write to private field"),e.set(s,t),t),Ur,nd=class extends dt{constructor(){super(),zE(this,Ur,void 0),QE(this,Ur,this.shadowRoot.querySelector("slot")),Uf(this,Ur).textContent=Ft(0);}static get observedAttributes(){return [...super.observedAttributes,chunkDITZCOYN_cjs.d.MEDIA_PREVIEW_TIME]}attributeChangedCallback(e,t,i){super.attributeChangedCallback(e,t,i),e===chunkDITZCOYN_cjs.d.MEDIA_PREVIEW_TIME&&i!=null&&(Uf(this,Ur).textContent=Ft(parseFloat(i)));}get mediaPreviewTime(){return chunkDITZCOYN_cjs.D(this,chunkDITZCOYN_cjs.d.MEDIA_PREVIEW_TIME)}set mediaPreviewTime(e){chunkDITZCOYN_cjs.E(this,chunkDITZCOYN_cjs.d.MEDIA_PREVIEW_TIME,e);}};Ur=new WeakMap;chunkDITZCOYN_cjs.o.customElements.get("media-preview-time-display")||chunkDITZCOYN_cjs.o.customElements.define("media-preview-time-display",nd);var xs={SEEK_OFFSET:"seekoffset"},ad=30,XE=s=>`
844
+ `}var Ls=class extends chunkDITZCOYN_cjs.o.HTMLElement{constructor(){if(super(),jE(this,Jt,void 0),!this.shadowRoot){this.attachShadow(this.constructor.shadowRootOptions);let e=chunkDITZCOYN_cjs.s(this.attributes);this.shadowRoot.innerHTML=this.constructor.getTemplateHTML(e);}}static get observedAttributes(){return [chunkDITZCOYN_cjs.b.MEDIA_CONTROLLER,chunkDITZCOYN_cjs.d.MEDIA_PREVIEW_IMAGE,chunkDITZCOYN_cjs.d.MEDIA_PREVIEW_COORDS]}connectedCallback(){var e,t,i;let r=this.getAttribute(chunkDITZCOYN_cjs.b.MEDIA_CONTROLLER);r&&(Da(this,Jt,(e=this.getRootNode())==null?void 0:e.getElementById(r)),(i=(t=ka(this,Jt))==null?void 0:t.associateElement)==null||i.call(t,this));}disconnectedCallback(){var e,t;(t=(e=ka(this,Jt))==null?void 0:e.unassociateElement)==null||t.call(e,this),Da(this,Jt,null);}attributeChangedCallback(e,t,i){var r,n,a,o,l;[chunkDITZCOYN_cjs.d.MEDIA_PREVIEW_IMAGE,chunkDITZCOYN_cjs.d.MEDIA_PREVIEW_COORDS].includes(e)&&this.update(),e===chunkDITZCOYN_cjs.b.MEDIA_CONTROLLER&&(t&&((n=(r=ka(this,Jt))==null?void 0:r.unassociateElement)==null||n.call(r,this),Da(this,Jt,null)),i&&this.isConnected&&(Da(this,Jt,(a=this.getRootNode())==null?void 0:a.getElementById(i)),(l=(o=ka(this,Jt))==null?void 0:o.associateElement)==null||l.call(o,this)));}get mediaPreviewImage(){return chunkDITZCOYN_cjs.H(this,chunkDITZCOYN_cjs.d.MEDIA_PREVIEW_IMAGE)}set mediaPreviewImage(e){chunkDITZCOYN_cjs.I(this,chunkDITZCOYN_cjs.d.MEDIA_PREVIEW_IMAGE,e);}get mediaPreviewCoords(){let e=this.getAttribute(chunkDITZCOYN_cjs.d.MEDIA_PREVIEW_COORDS);if(e)return e.split(/\s+/).map(t=>+t)}set mediaPreviewCoords(e){if(!e){this.removeAttribute(chunkDITZCOYN_cjs.d.MEDIA_PREVIEW_COORDS);return}this.setAttribute(chunkDITZCOYN_cjs.d.MEDIA_PREVIEW_COORDS,e.join(" "));}update(){let e=this.mediaPreviewCoords,t=this.mediaPreviewImage;if(!(e&&t))return;let[i,r,n,a]=e,o=t.split("#")[0],l=getComputedStyle(this),{maxWidth:d,maxHeight:c,minWidth:u,minHeight:h}=l,f=Math.min(parseInt(d)/n,parseInt(c)/a),m=Math.max(parseInt(u)/n,parseInt(h)/a),p=f<1,E=p?f:m>1?m:1,{style:v}=chunkDITZCOYN_cjs.C(this.shadowRoot,":host"),T=chunkDITZCOYN_cjs.C(this.shadowRoot,"img").style,S=this.shadowRoot.querySelector("img"),A=p?"min":"max";v.setProperty(`${A}-width`,"initial","important"),v.setProperty(`${A}-height`,"initial","important"),v.width=`${n*E}px`,v.height=`${a*E}px`;let b=()=>{T.width=`${this.imgWidth*E}px`,T.height=`${this.imgHeight*E}px`,T.display="block";};S.src!==o&&(S.onload=()=>{this.imgWidth=S.naturalWidth,this.imgHeight=S.naturalHeight,b();},S.src=o,b()),b(),T.transform=`translate(-${i*E}px, -${r*E}px)`;}};Jt=new WeakMap;Ls.shadowRootOptions={mode:"open"};Ls.getTemplateHTML=zE;chunkDITZCOYN_cjs.o.customElements.get("media-preview-thumbnail")||chunkDITZCOYN_cjs.o.customElements.define("media-preview-thumbnail",Ls);var Ca=Ls;var $f=(s,e,t)=>{if(!e.has(s))throw TypeError("Cannot "+t)},Bf=(s,e,t)=>($f(s,e,"read from private field"),t?t.call(s):e.get(s)),QE=(s,e,t)=>{if(e.has(s))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(s):e.set(s,t);},XE=(s,e,t,i)=>($f(s,e,"write to private field"),e.set(s,t),t),Ur,nd=class extends dt{constructor(){super(),QE(this,Ur,void 0),XE(this,Ur,this.shadowRoot.querySelector("slot")),Bf(this,Ur).textContent=Ft(0);}static get observedAttributes(){return [...super.observedAttributes,chunkDITZCOYN_cjs.d.MEDIA_PREVIEW_TIME]}attributeChangedCallback(e,t,i){super.attributeChangedCallback(e,t,i),e===chunkDITZCOYN_cjs.d.MEDIA_PREVIEW_TIME&&i!=null&&(Bf(this,Ur).textContent=Ft(parseFloat(i)));}get mediaPreviewTime(){return chunkDITZCOYN_cjs.D(this,chunkDITZCOYN_cjs.d.MEDIA_PREVIEW_TIME)}set mediaPreviewTime(e){chunkDITZCOYN_cjs.E(this,chunkDITZCOYN_cjs.d.MEDIA_PREVIEW_TIME,e);}};Ur=new WeakMap;chunkDITZCOYN_cjs.o.customElements.get("media-preview-time-display")||chunkDITZCOYN_cjs.o.customElements.define("media-preview-time-display",nd);var xs={SEEK_OFFSET:"seekoffset"},ad=30,ZE=s=>`
845
845
  <svg aria-hidden="true" viewBox="0 0 20 24">
846
846
  <defs>
847
847
  <style>.text{font-size:8px;font-family:Arial-BoldMT, Arial;font-weight:700;}</style>
848
848
  </defs>
849
849
  <text class="text value" transform="translate(2.18 19.87)">${s}</text>
850
850
  <path d="M10 6V3L4.37 7 10 10.94V8a5.54 5.54 0 0 1 1.9 10.48v2.12A7.5 7.5 0 0 0 10 6Z"/>
851
- </svg>`;function ZE(s,e){return `
852
- <slot name="icon">${XE(e.seekOffset)}</slot>
853
- `}function JE(){return chunkDITZCOYN_cjs.n("Seek backward")}var ev=0,Br=class extends chunkDITZCOYN_cjs.J{static get observedAttributes(){return [...super.observedAttributes,chunkDITZCOYN_cjs.d.MEDIA_CURRENT_TIME,xs.SEEK_OFFSET]}connectedCallback(){super.connectedCallback(),this.seekOffset=chunkDITZCOYN_cjs.D(this,xs.SEEK_OFFSET,ad);}attributeChangedCallback(e,t,i){super.attributeChangedCallback(e,t,i),e===xs.SEEK_OFFSET&&(this.seekOffset=chunkDITZCOYN_cjs.D(this,xs.SEEK_OFFSET,ad));}get seekOffset(){return chunkDITZCOYN_cjs.D(this,xs.SEEK_OFFSET,ad)}set seekOffset(e){chunkDITZCOYN_cjs.E(this,xs.SEEK_OFFSET,e),this.setAttribute("aria-label",chunkDITZCOYN_cjs.n("seek back {seekOffset} seconds",{seekOffset:this.seekOffset})),chunkDITZCOYN_cjs.u(chunkDITZCOYN_cjs.v(this,"icon"),this.seekOffset);}get mediaCurrentTime(){return chunkDITZCOYN_cjs.D(this,chunkDITZCOYN_cjs.d.MEDIA_CURRENT_TIME,ev)}set mediaCurrentTime(e){chunkDITZCOYN_cjs.E(this,chunkDITZCOYN_cjs.d.MEDIA_CURRENT_TIME,e);}handleClick(){let e=Math.max(this.mediaCurrentTime-this.seekOffset,0),t=new chunkDITZCOYN_cjs.o.CustomEvent(chunkDITZCOYN_cjs.a.MEDIA_SEEK_REQUEST,{composed:true,bubbles:true,detail:e});this.dispatchEvent(t);}};Br.getSlotTemplateHTML=ZE;Br.getTooltipContentHTML=JE;chunkDITZCOYN_cjs.o.customElements.get("media-seek-backward-button")||chunkDITZCOYN_cjs.o.customElements.define("media-seek-backward-button",Br);var Rs={SEEK_OFFSET:"seekoffset"},od=30,tv=s=>`
851
+ </svg>`;function JE(s,e){return `
852
+ <slot name="icon">${ZE(e.seekOffset)}</slot>
853
+ `}function ev(){return chunkDITZCOYN_cjs.n("Seek backward")}var tv=0,Br=class extends chunkDITZCOYN_cjs.J{static get observedAttributes(){return [...super.observedAttributes,chunkDITZCOYN_cjs.d.MEDIA_CURRENT_TIME,xs.SEEK_OFFSET]}connectedCallback(){super.connectedCallback(),this.seekOffset=chunkDITZCOYN_cjs.D(this,xs.SEEK_OFFSET,ad);}attributeChangedCallback(e,t,i){super.attributeChangedCallback(e,t,i),e===xs.SEEK_OFFSET&&(this.seekOffset=chunkDITZCOYN_cjs.D(this,xs.SEEK_OFFSET,ad));}get seekOffset(){return chunkDITZCOYN_cjs.D(this,xs.SEEK_OFFSET,ad)}set seekOffset(e){chunkDITZCOYN_cjs.E(this,xs.SEEK_OFFSET,e),this.setAttribute("aria-label",chunkDITZCOYN_cjs.n("seek back {seekOffset} seconds",{seekOffset:this.seekOffset})),chunkDITZCOYN_cjs.u(chunkDITZCOYN_cjs.v(this,"icon"),this.seekOffset);}get mediaCurrentTime(){return chunkDITZCOYN_cjs.D(this,chunkDITZCOYN_cjs.d.MEDIA_CURRENT_TIME,tv)}set mediaCurrentTime(e){chunkDITZCOYN_cjs.E(this,chunkDITZCOYN_cjs.d.MEDIA_CURRENT_TIME,e);}handleClick(){let e=Math.max(this.mediaCurrentTime-this.seekOffset,0),t=new chunkDITZCOYN_cjs.o.CustomEvent(chunkDITZCOYN_cjs.a.MEDIA_SEEK_REQUEST,{composed:true,bubbles:true,detail:e});this.dispatchEvent(t);}};Br.getSlotTemplateHTML=JE;Br.getTooltipContentHTML=ev;chunkDITZCOYN_cjs.o.customElements.get("media-seek-backward-button")||chunkDITZCOYN_cjs.o.customElements.define("media-seek-backward-button",Br);var Rs={SEEK_OFFSET:"seekoffset"},od=30,iv=s=>`
854
854
  <svg aria-hidden="true" viewBox="0 0 20 24">
855
855
  <defs>
856
856
  <style>.text{font-size:8px;font-family:Arial-BoldMT, Arial;font-weight:700;}</style>
857
857
  </defs>
858
858
  <text class="text value" transform="translate(8.9 19.87)">${s}</text>
859
859
  <path d="M10 6V3l5.61 4L10 10.94V8a5.54 5.54 0 0 0-1.9 10.48v2.12A7.5 7.5 0 0 1 10 6Z"/>
860
- </svg>`;function iv(s,e){return `
861
- <slot name="icon">${tv(e.seekOffset)}</slot>
862
- `}function sv(){return chunkDITZCOYN_cjs.n("Seek forward")}var rv=0,$r=class extends chunkDITZCOYN_cjs.J{static get observedAttributes(){return [...super.observedAttributes,chunkDITZCOYN_cjs.d.MEDIA_CURRENT_TIME,Rs.SEEK_OFFSET]}connectedCallback(){super.connectedCallback(),this.seekOffset=chunkDITZCOYN_cjs.D(this,Rs.SEEK_OFFSET,od);}attributeChangedCallback(e,t,i){super.attributeChangedCallback(e,t,i),e===Rs.SEEK_OFFSET&&(this.seekOffset=chunkDITZCOYN_cjs.D(this,Rs.SEEK_OFFSET,od));}get seekOffset(){return chunkDITZCOYN_cjs.D(this,Rs.SEEK_OFFSET,od)}set seekOffset(e){chunkDITZCOYN_cjs.E(this,Rs.SEEK_OFFSET,e),this.setAttribute("aria-label",chunkDITZCOYN_cjs.n("seek forward {seekOffset} seconds",{seekOffset:this.seekOffset})),chunkDITZCOYN_cjs.u(chunkDITZCOYN_cjs.v(this,"icon"),this.seekOffset);}get mediaCurrentTime(){return chunkDITZCOYN_cjs.D(this,chunkDITZCOYN_cjs.d.MEDIA_CURRENT_TIME,rv)}set mediaCurrentTime(e){chunkDITZCOYN_cjs.E(this,chunkDITZCOYN_cjs.d.MEDIA_CURRENT_TIME,e);}handleClick(){let e=this.mediaCurrentTime+this.seekOffset,t=new chunkDITZCOYN_cjs.o.CustomEvent(chunkDITZCOYN_cjs.a.MEDIA_SEEK_REQUEST,{composed:true,bubbles:true,detail:e});this.dispatchEvent(t);}};$r.getSlotTemplateHTML=iv;$r.getTooltipContentHTML=sv;chunkDITZCOYN_cjs.o.customElements.get("media-seek-forward-button")||chunkDITZCOYN_cjs.o.customElements.define("media-seek-forward-button",$r);var Hf=(s,e,t)=>{if(!e.has(s))throw TypeError("Cannot "+t)},ld=(s,e,t)=>(Hf(s,e,"read from private field"),t?t.call(s):e.get(s)),nv=(s,e,t)=>{if(e.has(s))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(s):e.set(s,t);},av=(s,e,t,i)=>(Hf(s,e,"write to private field"),e.set(s,t),t),ks,Zi={REMAINING:"remaining",SHOW_DURATION:"showduration",NO_TOGGLE:"notoggle"},$f=[...Object.values(Zi),chunkDITZCOYN_cjs.d.MEDIA_CURRENT_TIME,chunkDITZCOYN_cjs.d.MEDIA_DURATION,chunkDITZCOYN_cjs.d.MEDIA_SEEKABLE],Gf=["Enter"," "],ov="&nbsp;/&nbsp;",dd=(s,{timesSep:e=ov}={})=>{var t,i;let r=(t=s.mediaCurrentTime)!=null?t:0,[,n]=(i=s.mediaSeekable)!=null?i:[],a=0;Number.isFinite(s.mediaDuration)?a=s.mediaDuration:Number.isFinite(n)&&(a=n);let o=s.remaining?Ft(0-(a-r)):Ft(r);return s.showDuration?`${o}${e}${Ft(a)}`:o},lv="video not loaded, unknown time.",dv=s=>{var e;let t=s.mediaCurrentTime,[,i]=(e=s.mediaSeekable)!=null?e:[],r=null;if(Number.isFinite(s.mediaDuration)?r=s.mediaDuration:Number.isFinite(i)&&(r=i),t==null||r===null){s.setAttribute("aria-valuetext",lv);return}let n=s.remaining?Bi(0-(r-t)):Bi(t);if(!s.showDuration){s.setAttribute("aria-valuetext",n);return}let a=Bi(r),o=`${n} of ${a}`;s.setAttribute("aria-valuetext",o);};function cv(s,e){return `
860
+ </svg>`;function sv(s,e){return `
861
+ <slot name="icon">${iv(e.seekOffset)}</slot>
862
+ `}function rv(){return chunkDITZCOYN_cjs.n("Seek forward")}var nv=0,$r=class extends chunkDITZCOYN_cjs.J{static get observedAttributes(){return [...super.observedAttributes,chunkDITZCOYN_cjs.d.MEDIA_CURRENT_TIME,Rs.SEEK_OFFSET]}connectedCallback(){super.connectedCallback(),this.seekOffset=chunkDITZCOYN_cjs.D(this,Rs.SEEK_OFFSET,od);}attributeChangedCallback(e,t,i){super.attributeChangedCallback(e,t,i),e===Rs.SEEK_OFFSET&&(this.seekOffset=chunkDITZCOYN_cjs.D(this,Rs.SEEK_OFFSET,od));}get seekOffset(){return chunkDITZCOYN_cjs.D(this,Rs.SEEK_OFFSET,od)}set seekOffset(e){chunkDITZCOYN_cjs.E(this,Rs.SEEK_OFFSET,e),this.setAttribute("aria-label",chunkDITZCOYN_cjs.n("seek forward {seekOffset} seconds",{seekOffset:this.seekOffset})),chunkDITZCOYN_cjs.u(chunkDITZCOYN_cjs.v(this,"icon"),this.seekOffset);}get mediaCurrentTime(){return chunkDITZCOYN_cjs.D(this,chunkDITZCOYN_cjs.d.MEDIA_CURRENT_TIME,nv)}set mediaCurrentTime(e){chunkDITZCOYN_cjs.E(this,chunkDITZCOYN_cjs.d.MEDIA_CURRENT_TIME,e);}handleClick(){let e=this.mediaCurrentTime+this.seekOffset,t=new chunkDITZCOYN_cjs.o.CustomEvent(chunkDITZCOYN_cjs.a.MEDIA_SEEK_REQUEST,{composed:true,bubbles:true,detail:e});this.dispatchEvent(t);}};$r.getSlotTemplateHTML=sv;$r.getTooltipContentHTML=rv;chunkDITZCOYN_cjs.o.customElements.get("media-seek-forward-button")||chunkDITZCOYN_cjs.o.customElements.define("media-seek-forward-button",$r);var Kf=(s,e,t)=>{if(!e.has(s))throw TypeError("Cannot "+t)},ld=(s,e,t)=>(Kf(s,e,"read from private field"),t?t.call(s):e.get(s)),av=(s,e,t)=>{if(e.has(s))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(s):e.set(s,t);},ov=(s,e,t,i)=>(Kf(s,e,"write to private field"),e.set(s,t),t),ks,Zi={REMAINING:"remaining",SHOW_DURATION:"showduration",NO_TOGGLE:"notoggle"},Gf=[...Object.values(Zi),chunkDITZCOYN_cjs.d.MEDIA_CURRENT_TIME,chunkDITZCOYN_cjs.d.MEDIA_DURATION,chunkDITZCOYN_cjs.d.MEDIA_SEEKABLE],Hf=["Enter"," "],lv="&nbsp;/&nbsp;",dd=(s,{timesSep:e=lv}={})=>{var t,i;let r=(t=s.mediaCurrentTime)!=null?t:0,[,n]=(i=s.mediaSeekable)!=null?i:[],a=0;Number.isFinite(s.mediaDuration)?a=s.mediaDuration:Number.isFinite(n)&&(a=n);let o=s.remaining?Ft(0-(a-r)):Ft(r);return s.showDuration?`${o}${e}${Ft(a)}`:o},dv="video not loaded, unknown time.",cv=s=>{var e;let t=s.mediaCurrentTime,[,i]=(e=s.mediaSeekable)!=null?e:[],r=null;if(Number.isFinite(s.mediaDuration)?r=s.mediaDuration:Number.isFinite(i)&&(r=i),t==null||r===null){s.setAttribute("aria-valuetext",dv);return}let n=s.remaining?Bi(0-(r-t)):Bi(t);if(!s.showDuration){s.setAttribute("aria-valuetext",n);return}let a=Bi(r),o=`${n} of ${a}`;s.setAttribute("aria-valuetext",o);};function uv(s,e){return `
863
863
  <slot>${dd(e)}</slot>
864
- `}var Ma=class extends dt{constructor(){super(),nv(this,ks,void 0),av(this,ks,this.shadowRoot.querySelector("slot")),ld(this,ks).innerHTML=`${dd(this)}`;}static get observedAttributes(){return [...super.observedAttributes,...$f,"disabled"]}connectedCallback(){let{style:e}=chunkDITZCOYN_cjs.C(this.shadowRoot,":host(:hover:not([notoggle]))");e.setProperty("cursor","var(--media-cursor, pointer)"),e.setProperty("background","var(--media-control-hover-background, rgba(50 50 70 / .7))"),this.hasAttribute("disabled")||this.enable(),this.setAttribute("role","progressbar"),this.setAttribute("aria-label",chunkDITZCOYN_cjs.n("playback time"));let t=i=>{let{key:r}=i;if(!Gf.includes(r)){this.removeEventListener("keyup",t);return}this.toggleTimeDisplay();};this.addEventListener("keydown",i=>{let{metaKey:r,altKey:n,key:a}=i;if(r||n||!Gf.includes(a)){this.removeEventListener("keyup",t);return}this.addEventListener("keyup",t);}),this.addEventListener("click",this.toggleTimeDisplay),super.connectedCallback();}toggleTimeDisplay(){this.noToggle||(this.hasAttribute("remaining")?this.removeAttribute("remaining"):this.setAttribute("remaining",""));}disconnectedCallback(){this.disable(),super.disconnectedCallback();}attributeChangedCallback(e,t,i){$f.includes(e)?this.update():e==="disabled"&&i!==t&&(i==null?this.enable():this.disable()),super.attributeChangedCallback(e,t,i);}enable(){this.tabIndex=0;}disable(){this.tabIndex=-1;}get remaining(){return chunkDITZCOYN_cjs.F(this,Zi.REMAINING)}set remaining(e){chunkDITZCOYN_cjs.G(this,Zi.REMAINING,e);}get showDuration(){return chunkDITZCOYN_cjs.F(this,Zi.SHOW_DURATION)}set showDuration(e){chunkDITZCOYN_cjs.G(this,Zi.SHOW_DURATION,e);}get noToggle(){return chunkDITZCOYN_cjs.F(this,Zi.NO_TOGGLE)}set noToggle(e){chunkDITZCOYN_cjs.G(this,Zi.NO_TOGGLE,e);}get mediaDuration(){return chunkDITZCOYN_cjs.D(this,chunkDITZCOYN_cjs.d.MEDIA_DURATION)}set mediaDuration(e){chunkDITZCOYN_cjs.E(this,chunkDITZCOYN_cjs.d.MEDIA_DURATION,e);}get mediaCurrentTime(){return chunkDITZCOYN_cjs.D(this,chunkDITZCOYN_cjs.d.MEDIA_CURRENT_TIME)}set mediaCurrentTime(e){chunkDITZCOYN_cjs.E(this,chunkDITZCOYN_cjs.d.MEDIA_CURRENT_TIME,e);}get mediaSeekable(){let e=this.getAttribute(chunkDITZCOYN_cjs.d.MEDIA_SEEKABLE);if(e)return e.split(":").map(t=>+t)}set mediaSeekable(e){if(e==null){this.removeAttribute(chunkDITZCOYN_cjs.d.MEDIA_SEEKABLE);return}this.setAttribute(chunkDITZCOYN_cjs.d.MEDIA_SEEKABLE,e.join(":"));}update(){let e=dd(this);dv(this),e!==ld(this,ks).innerHTML&&(ld(this,ks).innerHTML=e);}};ks=new WeakMap;Ma.getSlotTemplateHTML=cv;chunkDITZCOYN_cjs.o.customElements.get("media-time-display")||chunkDITZCOYN_cjs.o.customElements.define("media-time-display",Ma);var Kf=(s,e,t)=>{if(!e.has(s))throw TypeError("Cannot "+t)},qe=(s,e,t)=>(Kf(s,e,"read from private field"),e.get(s)),ei=(s,e,t)=>{if(e.has(s))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(s):e.set(s,t);},vt=(s,e,t,i)=>(Kf(s,e,"write to private field"),e.set(s,t),t),uv=(s,e,t,i)=>({set _(r){vt(s,e,r);},get _(){return qe(s,e)}}),Ds,Pa,Cs,Gr,wa,Oa,Fa,Ms,Ji,Na,Ua=class{constructor(e,t,i){ei(this,Ds,void 0),ei(this,Pa,void 0),ei(this,Cs,void 0),ei(this,Gr,void 0),ei(this,wa,void 0),ei(this,Oa,void 0),ei(this,Fa,void 0),ei(this,Ms,void 0),ei(this,Ji,0),ei(this,Na,(r=performance.now())=>{vt(this,Ji,requestAnimationFrame(qe(this,Na))),vt(this,Gr,performance.now()-qe(this,Cs));let n=1e3/this.fps;if(qe(this,Gr)>n){vt(this,Cs,r-qe(this,Gr)%n);let a=1e3/((r-qe(this,Pa))/++uv(this,wa)._),o=(r-qe(this,Oa))/1e3/this.duration,l=qe(this,Fa)+o*this.playbackRate;l-qe(this,Ds).valueAsNumber>0?vt(this,Ms,this.playbackRate/this.duration/a):(vt(this,Ms,.995*qe(this,Ms)),l=qe(this,Ds).valueAsNumber+qe(this,Ms)),this.callback(l);}}),vt(this,Ds,e),this.callback=t,this.fps=i;}start(){qe(this,Ji)===0&&(vt(this,Cs,performance.now()),vt(this,Pa,qe(this,Cs)),vt(this,wa,0),qe(this,Na).call(this));}stop(){qe(this,Ji)!==0&&(cancelAnimationFrame(qe(this,Ji)),vt(this,Ji,0));}update({start:e,duration:t,playbackRate:i}){let r=e-qe(this,Ds).valueAsNumber,n=Math.abs(t-this.duration);(r>0||r<-0.03||n>=.5)&&this.callback(e),vt(this,Fa,e),vt(this,Oa,performance.now()),this.duration=t,this.playbackRate=i;}};Ds=new WeakMap;Pa=new WeakMap;Cs=new WeakMap;Gr=new WeakMap;wa=new WeakMap;Oa=new WeakMap;Fa=new WeakMap;Ms=new WeakMap;Ji=new WeakMap;Na=new WeakMap;var fd=(s,e,t)=>{if(!e.has(s))throw TypeError("Cannot "+t)},Oe=(s,e,t)=>(fd(s,e,"read from private field"),t?t.call(s):e.get(s)),Ge=(s,e,t)=>{if(e.has(s))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(s):e.set(s,t);},xt=(s,e,t,i)=>(fd(s,e,"write to private field"),e.set(s,t),t),et=(s,e,t)=>(fd(s,e,"access private method"),t),Ps,es,Ga,Kr,Ha,$a,Vr,Wr,ws,Os,Fs,Hr,md,Vf,cd,Ka,gd,Va,pd,Wa,Ed,ud,Wf,Yr,Ya,hd,Yf,hv="video not loaded, unknown time.",fv=s=>{let e=s.range,t=Bi(+qf(s)),i=Bi(+s.mediaSeekableEnd),r=t&&i?`${t} of ${i}`:hv;e.setAttribute("aria-valuetext",r);};function mv(s){return `
864
+ `}var Ma=class extends dt{constructor(){super(),av(this,ks,void 0),ov(this,ks,this.shadowRoot.querySelector("slot")),ld(this,ks).innerHTML=`${dd(this)}`;}static get observedAttributes(){return [...super.observedAttributes,...Gf,"disabled"]}connectedCallback(){let{style:e}=chunkDITZCOYN_cjs.C(this.shadowRoot,":host(:hover:not([notoggle]))");e.setProperty("cursor","var(--media-cursor, pointer)"),e.setProperty("background","var(--media-control-hover-background, rgba(50 50 70 / .7))"),this.hasAttribute("disabled")||this.enable(),this.setAttribute("role","progressbar"),this.setAttribute("aria-label",chunkDITZCOYN_cjs.n("playback time"));let t=i=>{let{key:r}=i;if(!Hf.includes(r)){this.removeEventListener("keyup",t);return}this.toggleTimeDisplay();};this.addEventListener("keydown",i=>{let{metaKey:r,altKey:n,key:a}=i;if(r||n||!Hf.includes(a)){this.removeEventListener("keyup",t);return}this.addEventListener("keyup",t);}),this.addEventListener("click",this.toggleTimeDisplay),super.connectedCallback();}toggleTimeDisplay(){this.noToggle||(this.hasAttribute("remaining")?this.removeAttribute("remaining"):this.setAttribute("remaining",""));}disconnectedCallback(){this.disable(),super.disconnectedCallback();}attributeChangedCallback(e,t,i){Gf.includes(e)?this.update():e==="disabled"&&i!==t&&(i==null?this.enable():this.disable()),super.attributeChangedCallback(e,t,i);}enable(){this.tabIndex=0;}disable(){this.tabIndex=-1;}get remaining(){return chunkDITZCOYN_cjs.F(this,Zi.REMAINING)}set remaining(e){chunkDITZCOYN_cjs.G(this,Zi.REMAINING,e);}get showDuration(){return chunkDITZCOYN_cjs.F(this,Zi.SHOW_DURATION)}set showDuration(e){chunkDITZCOYN_cjs.G(this,Zi.SHOW_DURATION,e);}get noToggle(){return chunkDITZCOYN_cjs.F(this,Zi.NO_TOGGLE)}set noToggle(e){chunkDITZCOYN_cjs.G(this,Zi.NO_TOGGLE,e);}get mediaDuration(){return chunkDITZCOYN_cjs.D(this,chunkDITZCOYN_cjs.d.MEDIA_DURATION)}set mediaDuration(e){chunkDITZCOYN_cjs.E(this,chunkDITZCOYN_cjs.d.MEDIA_DURATION,e);}get mediaCurrentTime(){return chunkDITZCOYN_cjs.D(this,chunkDITZCOYN_cjs.d.MEDIA_CURRENT_TIME)}set mediaCurrentTime(e){chunkDITZCOYN_cjs.E(this,chunkDITZCOYN_cjs.d.MEDIA_CURRENT_TIME,e);}get mediaSeekable(){let e=this.getAttribute(chunkDITZCOYN_cjs.d.MEDIA_SEEKABLE);if(e)return e.split(":").map(t=>+t)}set mediaSeekable(e){if(e==null){this.removeAttribute(chunkDITZCOYN_cjs.d.MEDIA_SEEKABLE);return}this.setAttribute(chunkDITZCOYN_cjs.d.MEDIA_SEEKABLE,e.join(":"));}update(){let e=dd(this);cv(this),e!==ld(this,ks).innerHTML&&(ld(this,ks).innerHTML=e);}};ks=new WeakMap;Ma.getSlotTemplateHTML=uv;chunkDITZCOYN_cjs.o.customElements.get("media-time-display")||chunkDITZCOYN_cjs.o.customElements.define("media-time-display",Ma);var Vf=(s,e,t)=>{if(!e.has(s))throw TypeError("Cannot "+t)},qe=(s,e,t)=>(Vf(s,e,"read from private field"),e.get(s)),ei=(s,e,t)=>{if(e.has(s))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(s):e.set(s,t);},vt=(s,e,t,i)=>(Vf(s,e,"write to private field"),e.set(s,t),t),hv=(s,e,t,i)=>({set _(r){vt(s,e,r);},get _(){return qe(s,e)}}),Ds,Pa,Cs,Gr,wa,Oa,Fa,Ms,Ji,Na,Ua=class{constructor(e,t,i){ei(this,Ds,void 0),ei(this,Pa,void 0),ei(this,Cs,void 0),ei(this,Gr,void 0),ei(this,wa,void 0),ei(this,Oa,void 0),ei(this,Fa,void 0),ei(this,Ms,void 0),ei(this,Ji,0),ei(this,Na,(r=performance.now())=>{vt(this,Ji,requestAnimationFrame(qe(this,Na))),vt(this,Gr,performance.now()-qe(this,Cs));let n=1e3/this.fps;if(qe(this,Gr)>n){vt(this,Cs,r-qe(this,Gr)%n);let a=1e3/((r-qe(this,Pa))/++hv(this,wa)._),o=(r-qe(this,Oa))/1e3/this.duration,l=qe(this,Fa)+o*this.playbackRate;l-qe(this,Ds).valueAsNumber>0?vt(this,Ms,this.playbackRate/this.duration/a):(vt(this,Ms,.995*qe(this,Ms)),l=qe(this,Ds).valueAsNumber+qe(this,Ms)),this.callback(l);}}),vt(this,Ds,e),this.callback=t,this.fps=i;}start(){qe(this,Ji)===0&&(vt(this,Cs,performance.now()),vt(this,Pa,qe(this,Cs)),vt(this,wa,0),qe(this,Na).call(this));}stop(){qe(this,Ji)!==0&&(cancelAnimationFrame(qe(this,Ji)),vt(this,Ji,0));}update({start:e,duration:t,playbackRate:i}){let r=e-qe(this,Ds).valueAsNumber,n=Math.abs(t-this.duration);(r>0||r<-0.03||n>=.5)&&this.callback(e),vt(this,Fa,e),vt(this,Oa,performance.now()),this.duration=t,this.playbackRate=i;}};Ds=new WeakMap;Pa=new WeakMap;Cs=new WeakMap;Gr=new WeakMap;wa=new WeakMap;Oa=new WeakMap;Fa=new WeakMap;Ms=new WeakMap;Ji=new WeakMap;Na=new WeakMap;var fd=(s,e,t)=>{if(!e.has(s))throw TypeError("Cannot "+t)},Oe=(s,e,t)=>(fd(s,e,"read from private field"),t?t.call(s):e.get(s)),Ge=(s,e,t)=>{if(e.has(s))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(s):e.set(s,t);},xt=(s,e,t,i)=>(fd(s,e,"write to private field"),e.set(s,t),t),et=(s,e,t)=>(fd(s,e,"access private method"),t),Ps,es,Ga,Kr,Ha,$a,Vr,Wr,ws,Os,Fs,Hr,md,Wf,cd,Ka,gd,Va,pd,Wa,Ed,ud,Yf,Yr,Ya,hd,qf,fv="video not loaded, unknown time.",mv=s=>{let e=s.range,t=Bi(+jf(s)),i=Bi(+s.mediaSeekableEnd),r=t&&i?`${t} of ${i}`:fv;e.setAttribute("aria-valuetext",r);};function gv(s){return `
865
865
  ${jt.getTemplateHTML(s)}
866
866
  <style>
867
867
  :host {
@@ -1079,7 +1079,7 @@
1079
1079
 
1080
1080
  </slot>
1081
1081
  </div>
1082
- `}var Ba=(s,e=s.mediaCurrentTime)=>{let t=Number.isFinite(s.mediaSeekableStart)?s.mediaSeekableStart:0,i=Number.isFinite(s.mediaDuration)?s.mediaDuration:s.mediaSeekableEnd;if(Number.isNaN(i))return 0;let r=(e-t)/(i-t);return Math.max(0,Math.min(r,1))},qf=(s,e=s.range.valueAsNumber)=>{let t=Number.isFinite(s.mediaSeekableStart)?s.mediaSeekableStart:0,i=Number.isFinite(s.mediaDuration)?s.mediaDuration:s.mediaSeekableEnd;return Number.isNaN(i)?0:e*(i-t)+t},qr=class extends jt{constructor(){super(),Ge(this,Fs),Ge(this,md),Ge(this,Ka),Ge(this,Va),Ge(this,Wa),Ge(this,ud),Ge(this,Yr),Ge(this,hd),Ge(this,Ps,void 0),Ge(this,es,void 0),Ge(this,Ga,void 0),Ge(this,Kr,void 0),Ge(this,Ha,void 0),Ge(this,$a,void 0),Ge(this,Vr,void 0),Ge(this,Wr,void 0),Ge(this,ws,void 0),Ge(this,Os,void 0),Ge(this,cd,i=>{this.dragging||(gs(i)&&(this.range.valueAsNumber=i),Oe(this,Os)||this.updateBar());}),this.shadowRoot.querySelector("#track").insertAdjacentHTML("afterbegin",'<div id="buffered" part="buffered"></div>'),xt(this,Ga,this.shadowRoot.querySelectorAll('[part~="box"]')),xt(this,Ha,this.shadowRoot.querySelector('[part~="preview-box"]')),xt(this,$a,this.shadowRoot.querySelector('[part~="current-box"]'));let t=getComputedStyle(this);xt(this,Vr,parseInt(t.getPropertyValue("--media-box-padding-left"))),xt(this,Wr,parseInt(t.getPropertyValue("--media-box-padding-right"))),xt(this,es,new Ua(this.range,Oe(this,cd),60));}static get observedAttributes(){return [...super.observedAttributes,chunkDITZCOYN_cjs.d.MEDIA_PAUSED,chunkDITZCOYN_cjs.d.MEDIA_DURATION,chunkDITZCOYN_cjs.d.MEDIA_SEEKABLE,chunkDITZCOYN_cjs.d.MEDIA_CURRENT_TIME,chunkDITZCOYN_cjs.d.MEDIA_PREVIEW_IMAGE,chunkDITZCOYN_cjs.d.MEDIA_PREVIEW_TIME,chunkDITZCOYN_cjs.d.MEDIA_PREVIEW_CHAPTER,chunkDITZCOYN_cjs.d.MEDIA_BUFFERED,chunkDITZCOYN_cjs.d.MEDIA_PLAYBACK_RATE,chunkDITZCOYN_cjs.d.MEDIA_LOADING,chunkDITZCOYN_cjs.d.MEDIA_ENDED]}connectedCallback(){var e;super.connectedCallback(),this.range.setAttribute("aria-label",chunkDITZCOYN_cjs.n("seek")),et(this,Fs,Hr).call(this),xt(this,Ps,this.getRootNode()),(e=Oe(this,Ps))==null||e.addEventListener("transitionstart",this);}disconnectedCallback(){var e;super.disconnectedCallback(),et(this,Fs,Hr).call(this),(e=Oe(this,Ps))==null||e.removeEventListener("transitionstart",this),xt(this,Ps,null);}attributeChangedCallback(e,t,i){super.attributeChangedCallback(e,t,i),t!=i&&(e===chunkDITZCOYN_cjs.d.MEDIA_CURRENT_TIME||e===chunkDITZCOYN_cjs.d.MEDIA_PAUSED||e===chunkDITZCOYN_cjs.d.MEDIA_ENDED||e===chunkDITZCOYN_cjs.d.MEDIA_LOADING||e===chunkDITZCOYN_cjs.d.MEDIA_DURATION||e===chunkDITZCOYN_cjs.d.MEDIA_SEEKABLE?(Oe(this,es).update({start:Ba(this),duration:this.mediaSeekableEnd-this.mediaSeekableStart,playbackRate:this.mediaPlaybackRate}),et(this,Fs,Hr).call(this),fv(this)):e===chunkDITZCOYN_cjs.d.MEDIA_BUFFERED&&this.updateBufferedBar(),(e===chunkDITZCOYN_cjs.d.MEDIA_DURATION||e===chunkDITZCOYN_cjs.d.MEDIA_SEEKABLE)&&(this.mediaChaptersCues=Oe(this,ws),this.updateBar()));}get mediaChaptersCues(){return Oe(this,ws)}set mediaChaptersCues(e){var t;xt(this,ws,e),this.updateSegments((t=Oe(this,ws))==null?void 0:t.map(i=>({start:Ba(this,i.startTime),end:Ba(this,i.endTime)})));}get mediaPaused(){return chunkDITZCOYN_cjs.F(this,chunkDITZCOYN_cjs.d.MEDIA_PAUSED)}set mediaPaused(e){chunkDITZCOYN_cjs.G(this,chunkDITZCOYN_cjs.d.MEDIA_PAUSED,e);}get mediaLoading(){return chunkDITZCOYN_cjs.F(this,chunkDITZCOYN_cjs.d.MEDIA_LOADING)}set mediaLoading(e){chunkDITZCOYN_cjs.G(this,chunkDITZCOYN_cjs.d.MEDIA_LOADING,e);}get mediaDuration(){return chunkDITZCOYN_cjs.D(this,chunkDITZCOYN_cjs.d.MEDIA_DURATION)}set mediaDuration(e){chunkDITZCOYN_cjs.E(this,chunkDITZCOYN_cjs.d.MEDIA_DURATION,e);}get mediaCurrentTime(){return chunkDITZCOYN_cjs.D(this,chunkDITZCOYN_cjs.d.MEDIA_CURRENT_TIME)}set mediaCurrentTime(e){chunkDITZCOYN_cjs.E(this,chunkDITZCOYN_cjs.d.MEDIA_CURRENT_TIME,e);}get mediaPlaybackRate(){return chunkDITZCOYN_cjs.D(this,chunkDITZCOYN_cjs.d.MEDIA_PLAYBACK_RATE,1)}set mediaPlaybackRate(e){chunkDITZCOYN_cjs.E(this,chunkDITZCOYN_cjs.d.MEDIA_PLAYBACK_RATE,e);}get mediaBuffered(){let e=this.getAttribute(chunkDITZCOYN_cjs.d.MEDIA_BUFFERED);return e?e.split(" ").map(t=>t.split(":").map(i=>+i)):[]}set mediaBuffered(e){if(!e){this.removeAttribute(chunkDITZCOYN_cjs.d.MEDIA_BUFFERED);return}let t=e.map(i=>i.join(":")).join(" ");this.setAttribute(chunkDITZCOYN_cjs.d.MEDIA_BUFFERED,t);}get mediaSeekable(){let e=this.getAttribute(chunkDITZCOYN_cjs.d.MEDIA_SEEKABLE);if(e)return e.split(":").map(t=>+t)}set mediaSeekable(e){if(e==null){this.removeAttribute(chunkDITZCOYN_cjs.d.MEDIA_SEEKABLE);return}this.setAttribute(chunkDITZCOYN_cjs.d.MEDIA_SEEKABLE,e.join(":"));}get mediaSeekableEnd(){var e;let[,t=this.mediaDuration]=(e=this.mediaSeekable)!=null?e:[];return t}get mediaSeekableStart(){var e;let[t=0]=(e=this.mediaSeekable)!=null?e:[];return t}get mediaPreviewImage(){return chunkDITZCOYN_cjs.H(this,chunkDITZCOYN_cjs.d.MEDIA_PREVIEW_IMAGE)}set mediaPreviewImage(e){chunkDITZCOYN_cjs.I(this,chunkDITZCOYN_cjs.d.MEDIA_PREVIEW_IMAGE,e);}get mediaPreviewTime(){return chunkDITZCOYN_cjs.D(this,chunkDITZCOYN_cjs.d.MEDIA_PREVIEW_TIME)}set mediaPreviewTime(e){chunkDITZCOYN_cjs.E(this,chunkDITZCOYN_cjs.d.MEDIA_PREVIEW_TIME,e);}get mediaEnded(){return chunkDITZCOYN_cjs.F(this,chunkDITZCOYN_cjs.d.MEDIA_ENDED)}set mediaEnded(e){chunkDITZCOYN_cjs.G(this,chunkDITZCOYN_cjs.d.MEDIA_ENDED,e);}updateBar(){super.updateBar(),this.updateBufferedBar(),this.updateCurrentBox();}updateBufferedBar(){var e;let t=this.mediaBuffered;if(!t.length)return;let i;if(this.mediaEnded)i=1;else {let n=this.mediaCurrentTime,[,a=this.mediaSeekableStart]=(e=t.find(([o,l])=>o<=n&&n<=l))!=null?e:[];i=Ba(this,a);}let{style:r}=chunkDITZCOYN_cjs.C(this.shadowRoot,"#buffered");r.setProperty("width",`${i*100}%`);}updateCurrentBox(){if(!this.shadowRoot.querySelector('slot[name="current"]').assignedElements().length)return;let t=chunkDITZCOYN_cjs.C(this.shadowRoot,"#current-rail"),i=chunkDITZCOYN_cjs.C(this.shadowRoot,'[part~="current-box"]'),r=et(this,Ka,gd).call(this,Oe(this,$a)),n=et(this,Va,pd).call(this,r,this.range.valueAsNumber),a=et(this,Wa,Ed).call(this,r,this.range.valueAsNumber);t.style.transform=`translateX(${n})`,t.style.setProperty("--_range-width",`${r.range.width}`),i.style.setProperty("--_box-shift",`${a}`),i.style.setProperty("--_box-width",`${r.box.width}px`),i.style.setProperty("visibility","initial");}handleEvent(e){switch(super.handleEvent(e),e.type){case "input":et(this,hd,Yf).call(this);break;case "pointermove":et(this,ud,Wf).call(this,e);break;case "pointerup":Oe(this,Os)&&xt(this,Os,false);break;case "pointerdown":xt(this,Os,true);break;case "pointerleave":et(this,Yr,Ya).call(this,null);break;case "transitionstart":chunkDITZCOYN_cjs.w(e.target,this)&&setTimeout(()=>et(this,Fs,Hr).call(this),0);break}}};Ps=new WeakMap;es=new WeakMap;Ga=new WeakMap;Kr=new WeakMap;Ha=new WeakMap;$a=new WeakMap;Vr=new WeakMap;Wr=new WeakMap;ws=new WeakMap;Os=new WeakMap;Fs=new WeakSet;Hr=function(){et(this,md,Vf).call(this)?Oe(this,es).start():Oe(this,es).stop();};md=new WeakSet;Vf=function(){return this.isConnected&&!this.mediaPaused&&!this.mediaLoading&&!this.mediaEnded&&this.mediaSeekableEnd>0&&chunkDITZCOYN_cjs.A(this)};cd=new WeakMap;Ka=new WeakSet;gd=function(s){var e;let i=((e=this.getAttribute("bounds")?chunkDITZCOYN_cjs.x(this,`#${this.getAttribute("bounds")}`):this.parentElement)!=null?e:this).getBoundingClientRect(),r=this.range.getBoundingClientRect(),n=s.offsetWidth,a=-(r.left-i.left-n/2),o=i.right-r.left-n/2;return {box:{width:n,min:a,max:o},bounds:i,range:r}};Va=new WeakSet;pd=function(s,e){let t=`${e*100}%`,{width:i,min:r,max:n}=s.box;if(!i)return t;if(Number.isNaN(r)||(t=`max(${`calc(1 / var(--_range-width) * 100 * ${r}% + var(--media-box-padding-left))`}, ${t})`),!Number.isNaN(n)){let o=`calc(1 / var(--_range-width) * 100 * ${n}% - var(--media-box-padding-right))`;t=`min(${t}, ${o})`;}return t};Wa=new WeakSet;Ed=function(s,e){let{width:t,min:i,max:r}=s.box,n=e*s.range.width;if(n<i+Oe(this,Vr)){let a=s.range.left-s.bounds.left-Oe(this,Vr);return `${n-t/2+a}px`}if(n>r-Oe(this,Wr)){let a=s.bounds.right-s.range.right-Oe(this,Wr);return `${n+t/2-a-s.range.width}px`}return 0};ud=new WeakSet;Wf=function(s){let e=[...Oe(this,Ga)].some(c=>s.composedPath().includes(c));if(!this.dragging&&(e||!s.composedPath().includes(this))){et(this,Yr,Ya).call(this,null);return}let t=this.mediaSeekableEnd;if(!t)return;let i=chunkDITZCOYN_cjs.C(this.shadowRoot,"#preview-rail"),r=chunkDITZCOYN_cjs.C(this.shadowRoot,'[part~="preview-box"]'),n=et(this,Ka,gd).call(this,Oe(this,Ha)),a=(s.clientX-n.range.left)/n.range.width;a=Math.max(0,Math.min(1,a));let o=et(this,Va,pd).call(this,n,a),l=et(this,Wa,Ed).call(this,n,a);i.style.transform=`translateX(${o})`,i.style.setProperty("--_range-width",`${n.range.width}`),r.style.setProperty("--_box-shift",`${l}`),r.style.setProperty("--_box-width",`${n.box.width}px`);let d=Math.round(Oe(this,Kr))-Math.round(a*t);Math.abs(d)<1&&a>.01&&a<.99||(xt(this,Kr,a*t),et(this,Yr,Ya).call(this,Oe(this,Kr)));};Yr=new WeakSet;Ya=function(s){this.dispatchEvent(new chunkDITZCOYN_cjs.o.CustomEvent(chunkDITZCOYN_cjs.a.MEDIA_PREVIEW_REQUEST,{composed:true,bubbles:true,detail:s}));};hd=new WeakSet;Yf=function(){Oe(this,es).stop();let s=qf(this);this.dispatchEvent(new chunkDITZCOYN_cjs.o.CustomEvent(chunkDITZCOYN_cjs.a.MEDIA_SEEK_REQUEST,{composed:true,bubbles:true,detail:s}));};qr.shadowRootOptions={mode:"open"};qr.getTemplateHTML=mv;chunkDITZCOYN_cjs.o.customElements.get("media-time-range")||chunkDITZCOYN_cjs.o.customElements.define("media-time-range",qr);var gv=1,pv=s=>s.mediaMuted?0:s.mediaVolume,Ev=s=>`${Math.round(s*100)}%`,vd=class extends jt{static get observedAttributes(){return [...super.observedAttributes,chunkDITZCOYN_cjs.d.MEDIA_VOLUME,chunkDITZCOYN_cjs.d.MEDIA_MUTED,chunkDITZCOYN_cjs.d.MEDIA_VOLUME_UNAVAILABLE]}constructor(){super(),this.range.addEventListener("input",()=>{let e=this.range.value,t=new chunkDITZCOYN_cjs.o.CustomEvent(chunkDITZCOYN_cjs.a.MEDIA_VOLUME_REQUEST,{composed:true,bubbles:true,detail:e});this.dispatchEvent(t);});}connectedCallback(){super.connectedCallback(),this.range.setAttribute("aria-label",chunkDITZCOYN_cjs.n("volume"));}attributeChangedCallback(e,t,i){super.attributeChangedCallback(e,t,i),(e===chunkDITZCOYN_cjs.d.MEDIA_VOLUME||e===chunkDITZCOYN_cjs.d.MEDIA_MUTED)&&(this.range.valueAsNumber=pv(this),this.range.setAttribute("aria-valuetext",Ev(this.range.valueAsNumber)),this.updateBar());}get mediaVolume(){return chunkDITZCOYN_cjs.D(this,chunkDITZCOYN_cjs.d.MEDIA_VOLUME,gv)}set mediaVolume(e){chunkDITZCOYN_cjs.E(this,chunkDITZCOYN_cjs.d.MEDIA_VOLUME,e);}get mediaMuted(){return chunkDITZCOYN_cjs.F(this,chunkDITZCOYN_cjs.d.MEDIA_MUTED)}set mediaMuted(e){chunkDITZCOYN_cjs.G(this,chunkDITZCOYN_cjs.d.MEDIA_MUTED,e);}get mediaVolumeUnavailable(){return chunkDITZCOYN_cjs.H(this,chunkDITZCOYN_cjs.d.MEDIA_VOLUME_UNAVAILABLE)}set mediaVolumeUnavailable(e){chunkDITZCOYN_cjs.I(this,chunkDITZCOYN_cjs.d.MEDIA_VOLUME_UNAVAILABLE,e);}};chunkDITZCOYN_cjs.o.customElements.get("media-volume-range")||chunkDITZCOYN_cjs.o.customElements.define("media-volume-range",vd);var _d=(s,e,t)=>{if(!e.has(s))throw TypeError("Cannot "+t)},ti=(s,e,t)=>(_d(s,e,"read from private field"),t?t.call(s):e.get(s)),pi=(s,e,t)=>{if(e.has(s))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(s):e.set(s,t);},Td=(s,e,t,i)=>(_d(s,e,"write to private field"),e.set(s,t),t),Bt=(s,e,t)=>(_d(s,e,"access private method"),t),qa,zr,yd,jf,za,Id,Ld,zf,ii,Ns,Qr,Sd,Qf,ja,Ad;function vv(s){return `
1082
+ `}var Ba=(s,e=s.mediaCurrentTime)=>{let t=Number.isFinite(s.mediaSeekableStart)?s.mediaSeekableStart:0,i=Number.isFinite(s.mediaDuration)?s.mediaDuration:s.mediaSeekableEnd;if(Number.isNaN(i))return 0;let r=(e-t)/(i-t);return Math.max(0,Math.min(r,1))},jf=(s,e=s.range.valueAsNumber)=>{let t=Number.isFinite(s.mediaSeekableStart)?s.mediaSeekableStart:0,i=Number.isFinite(s.mediaDuration)?s.mediaDuration:s.mediaSeekableEnd;return Number.isNaN(i)?0:e*(i-t)+t},qr=class extends jt{constructor(){super(),Ge(this,Fs),Ge(this,md),Ge(this,Ka),Ge(this,Va),Ge(this,Wa),Ge(this,ud),Ge(this,Yr),Ge(this,hd),Ge(this,Ps,void 0),Ge(this,es,void 0),Ge(this,Ga,void 0),Ge(this,Kr,void 0),Ge(this,Ha,void 0),Ge(this,$a,void 0),Ge(this,Vr,void 0),Ge(this,Wr,void 0),Ge(this,ws,void 0),Ge(this,Os,void 0),Ge(this,cd,i=>{this.dragging||(gs(i)&&(this.range.valueAsNumber=i),Oe(this,Os)||this.updateBar());}),this.shadowRoot.querySelector("#track").insertAdjacentHTML("afterbegin",'<div id="buffered" part="buffered"></div>'),xt(this,Ga,this.shadowRoot.querySelectorAll('[part~="box"]')),xt(this,Ha,this.shadowRoot.querySelector('[part~="preview-box"]')),xt(this,$a,this.shadowRoot.querySelector('[part~="current-box"]'));let t=getComputedStyle(this);xt(this,Vr,parseInt(t.getPropertyValue("--media-box-padding-left"))),xt(this,Wr,parseInt(t.getPropertyValue("--media-box-padding-right"))),xt(this,es,new Ua(this.range,Oe(this,cd),60));}static get observedAttributes(){return [...super.observedAttributes,chunkDITZCOYN_cjs.d.MEDIA_PAUSED,chunkDITZCOYN_cjs.d.MEDIA_DURATION,chunkDITZCOYN_cjs.d.MEDIA_SEEKABLE,chunkDITZCOYN_cjs.d.MEDIA_CURRENT_TIME,chunkDITZCOYN_cjs.d.MEDIA_PREVIEW_IMAGE,chunkDITZCOYN_cjs.d.MEDIA_PREVIEW_TIME,chunkDITZCOYN_cjs.d.MEDIA_PREVIEW_CHAPTER,chunkDITZCOYN_cjs.d.MEDIA_BUFFERED,chunkDITZCOYN_cjs.d.MEDIA_PLAYBACK_RATE,chunkDITZCOYN_cjs.d.MEDIA_LOADING,chunkDITZCOYN_cjs.d.MEDIA_ENDED]}connectedCallback(){var e;super.connectedCallback(),this.range.setAttribute("aria-label",chunkDITZCOYN_cjs.n("seek")),et(this,Fs,Hr).call(this),xt(this,Ps,this.getRootNode()),(e=Oe(this,Ps))==null||e.addEventListener("transitionstart",this);}disconnectedCallback(){var e;super.disconnectedCallback(),et(this,Fs,Hr).call(this),(e=Oe(this,Ps))==null||e.removeEventListener("transitionstart",this),xt(this,Ps,null);}attributeChangedCallback(e,t,i){super.attributeChangedCallback(e,t,i),t!=i&&(e===chunkDITZCOYN_cjs.d.MEDIA_CURRENT_TIME||e===chunkDITZCOYN_cjs.d.MEDIA_PAUSED||e===chunkDITZCOYN_cjs.d.MEDIA_ENDED||e===chunkDITZCOYN_cjs.d.MEDIA_LOADING||e===chunkDITZCOYN_cjs.d.MEDIA_DURATION||e===chunkDITZCOYN_cjs.d.MEDIA_SEEKABLE?(Oe(this,es).update({start:Ba(this),duration:this.mediaSeekableEnd-this.mediaSeekableStart,playbackRate:this.mediaPlaybackRate}),et(this,Fs,Hr).call(this),mv(this)):e===chunkDITZCOYN_cjs.d.MEDIA_BUFFERED&&this.updateBufferedBar(),(e===chunkDITZCOYN_cjs.d.MEDIA_DURATION||e===chunkDITZCOYN_cjs.d.MEDIA_SEEKABLE)&&(this.mediaChaptersCues=Oe(this,ws),this.updateBar()));}get mediaChaptersCues(){return Oe(this,ws)}set mediaChaptersCues(e){var t;xt(this,ws,e),this.updateSegments((t=Oe(this,ws))==null?void 0:t.map(i=>({start:Ba(this,i.startTime),end:Ba(this,i.endTime)})));}get mediaPaused(){return chunkDITZCOYN_cjs.F(this,chunkDITZCOYN_cjs.d.MEDIA_PAUSED)}set mediaPaused(e){chunkDITZCOYN_cjs.G(this,chunkDITZCOYN_cjs.d.MEDIA_PAUSED,e);}get mediaLoading(){return chunkDITZCOYN_cjs.F(this,chunkDITZCOYN_cjs.d.MEDIA_LOADING)}set mediaLoading(e){chunkDITZCOYN_cjs.G(this,chunkDITZCOYN_cjs.d.MEDIA_LOADING,e);}get mediaDuration(){return chunkDITZCOYN_cjs.D(this,chunkDITZCOYN_cjs.d.MEDIA_DURATION)}set mediaDuration(e){chunkDITZCOYN_cjs.E(this,chunkDITZCOYN_cjs.d.MEDIA_DURATION,e);}get mediaCurrentTime(){return chunkDITZCOYN_cjs.D(this,chunkDITZCOYN_cjs.d.MEDIA_CURRENT_TIME)}set mediaCurrentTime(e){chunkDITZCOYN_cjs.E(this,chunkDITZCOYN_cjs.d.MEDIA_CURRENT_TIME,e);}get mediaPlaybackRate(){return chunkDITZCOYN_cjs.D(this,chunkDITZCOYN_cjs.d.MEDIA_PLAYBACK_RATE,1)}set mediaPlaybackRate(e){chunkDITZCOYN_cjs.E(this,chunkDITZCOYN_cjs.d.MEDIA_PLAYBACK_RATE,e);}get mediaBuffered(){let e=this.getAttribute(chunkDITZCOYN_cjs.d.MEDIA_BUFFERED);return e?e.split(" ").map(t=>t.split(":").map(i=>+i)):[]}set mediaBuffered(e){if(!e){this.removeAttribute(chunkDITZCOYN_cjs.d.MEDIA_BUFFERED);return}let t=e.map(i=>i.join(":")).join(" ");this.setAttribute(chunkDITZCOYN_cjs.d.MEDIA_BUFFERED,t);}get mediaSeekable(){let e=this.getAttribute(chunkDITZCOYN_cjs.d.MEDIA_SEEKABLE);if(e)return e.split(":").map(t=>+t)}set mediaSeekable(e){if(e==null){this.removeAttribute(chunkDITZCOYN_cjs.d.MEDIA_SEEKABLE);return}this.setAttribute(chunkDITZCOYN_cjs.d.MEDIA_SEEKABLE,e.join(":"));}get mediaSeekableEnd(){var e;let[,t=this.mediaDuration]=(e=this.mediaSeekable)!=null?e:[];return t}get mediaSeekableStart(){var e;let[t=0]=(e=this.mediaSeekable)!=null?e:[];return t}get mediaPreviewImage(){return chunkDITZCOYN_cjs.H(this,chunkDITZCOYN_cjs.d.MEDIA_PREVIEW_IMAGE)}set mediaPreviewImage(e){chunkDITZCOYN_cjs.I(this,chunkDITZCOYN_cjs.d.MEDIA_PREVIEW_IMAGE,e);}get mediaPreviewTime(){return chunkDITZCOYN_cjs.D(this,chunkDITZCOYN_cjs.d.MEDIA_PREVIEW_TIME)}set mediaPreviewTime(e){chunkDITZCOYN_cjs.E(this,chunkDITZCOYN_cjs.d.MEDIA_PREVIEW_TIME,e);}get mediaEnded(){return chunkDITZCOYN_cjs.F(this,chunkDITZCOYN_cjs.d.MEDIA_ENDED)}set mediaEnded(e){chunkDITZCOYN_cjs.G(this,chunkDITZCOYN_cjs.d.MEDIA_ENDED,e);}updateBar(){super.updateBar(),this.updateBufferedBar(),this.updateCurrentBox();}updateBufferedBar(){var e;let t=this.mediaBuffered;if(!t.length)return;let i;if(this.mediaEnded)i=1;else {let n=this.mediaCurrentTime,[,a=this.mediaSeekableStart]=(e=t.find(([o,l])=>o<=n&&n<=l))!=null?e:[];i=Ba(this,a);}let{style:r}=chunkDITZCOYN_cjs.C(this.shadowRoot,"#buffered");r.setProperty("width",`${i*100}%`);}updateCurrentBox(){if(!this.shadowRoot.querySelector('slot[name="current"]').assignedElements().length)return;let t=chunkDITZCOYN_cjs.C(this.shadowRoot,"#current-rail"),i=chunkDITZCOYN_cjs.C(this.shadowRoot,'[part~="current-box"]'),r=et(this,Ka,gd).call(this,Oe(this,$a)),n=et(this,Va,pd).call(this,r,this.range.valueAsNumber),a=et(this,Wa,Ed).call(this,r,this.range.valueAsNumber);t.style.transform=`translateX(${n})`,t.style.setProperty("--_range-width",`${r.range.width}`),i.style.setProperty("--_box-shift",`${a}`),i.style.setProperty("--_box-width",`${r.box.width}px`),i.style.setProperty("visibility","initial");}handleEvent(e){switch(super.handleEvent(e),e.type){case "input":et(this,hd,qf).call(this);break;case "pointermove":et(this,ud,Yf).call(this,e);break;case "pointerup":Oe(this,Os)&&xt(this,Os,false);break;case "pointerdown":xt(this,Os,true);break;case "pointerleave":et(this,Yr,Ya).call(this,null);break;case "transitionstart":chunkDITZCOYN_cjs.w(e.target,this)&&setTimeout(()=>et(this,Fs,Hr).call(this),0);break}}};Ps=new WeakMap;es=new WeakMap;Ga=new WeakMap;Kr=new WeakMap;Ha=new WeakMap;$a=new WeakMap;Vr=new WeakMap;Wr=new WeakMap;ws=new WeakMap;Os=new WeakMap;Fs=new WeakSet;Hr=function(){et(this,md,Wf).call(this)?Oe(this,es).start():Oe(this,es).stop();};md=new WeakSet;Wf=function(){return this.isConnected&&!this.mediaPaused&&!this.mediaLoading&&!this.mediaEnded&&this.mediaSeekableEnd>0&&chunkDITZCOYN_cjs.A(this)};cd=new WeakMap;Ka=new WeakSet;gd=function(s){var e;let i=((e=this.getAttribute("bounds")?chunkDITZCOYN_cjs.x(this,`#${this.getAttribute("bounds")}`):this.parentElement)!=null?e:this).getBoundingClientRect(),r=this.range.getBoundingClientRect(),n=s.offsetWidth,a=-(r.left-i.left-n/2),o=i.right-r.left-n/2;return {box:{width:n,min:a,max:o},bounds:i,range:r}};Va=new WeakSet;pd=function(s,e){let t=`${e*100}%`,{width:i,min:r,max:n}=s.box;if(!i)return t;if(Number.isNaN(r)||(t=`max(${`calc(1 / var(--_range-width) * 100 * ${r}% + var(--media-box-padding-left))`}, ${t})`),!Number.isNaN(n)){let o=`calc(1 / var(--_range-width) * 100 * ${n}% - var(--media-box-padding-right))`;t=`min(${t}, ${o})`;}return t};Wa=new WeakSet;Ed=function(s,e){let{width:t,min:i,max:r}=s.box,n=e*s.range.width;if(n<i+Oe(this,Vr)){let a=s.range.left-s.bounds.left-Oe(this,Vr);return `${n-t/2+a}px`}if(n>r-Oe(this,Wr)){let a=s.bounds.right-s.range.right-Oe(this,Wr);return `${n+t/2-a-s.range.width}px`}return 0};ud=new WeakSet;Yf=function(s){let e=[...Oe(this,Ga)].some(c=>s.composedPath().includes(c));if(!this.dragging&&(e||!s.composedPath().includes(this))){et(this,Yr,Ya).call(this,null);return}let t=this.mediaSeekableEnd;if(!t)return;let i=chunkDITZCOYN_cjs.C(this.shadowRoot,"#preview-rail"),r=chunkDITZCOYN_cjs.C(this.shadowRoot,'[part~="preview-box"]'),n=et(this,Ka,gd).call(this,Oe(this,Ha)),a=(s.clientX-n.range.left)/n.range.width;a=Math.max(0,Math.min(1,a));let o=et(this,Va,pd).call(this,n,a),l=et(this,Wa,Ed).call(this,n,a);i.style.transform=`translateX(${o})`,i.style.setProperty("--_range-width",`${n.range.width}`),r.style.setProperty("--_box-shift",`${l}`),r.style.setProperty("--_box-width",`${n.box.width}px`);let d=Math.round(Oe(this,Kr))-Math.round(a*t);Math.abs(d)<1&&a>.01&&a<.99||(xt(this,Kr,a*t),et(this,Yr,Ya).call(this,Oe(this,Kr)));};Yr=new WeakSet;Ya=function(s){this.dispatchEvent(new chunkDITZCOYN_cjs.o.CustomEvent(chunkDITZCOYN_cjs.a.MEDIA_PREVIEW_REQUEST,{composed:true,bubbles:true,detail:s}));};hd=new WeakSet;qf=function(){Oe(this,es).stop();let s=jf(this);this.dispatchEvent(new chunkDITZCOYN_cjs.o.CustomEvent(chunkDITZCOYN_cjs.a.MEDIA_SEEK_REQUEST,{composed:true,bubbles:true,detail:s}));};qr.shadowRootOptions={mode:"open"};qr.getTemplateHTML=gv;chunkDITZCOYN_cjs.o.customElements.get("media-time-range")||chunkDITZCOYN_cjs.o.customElements.define("media-time-range",qr);var pv=1,Ev=s=>s.mediaMuted?0:s.mediaVolume,vv=s=>`${Math.round(s*100)}%`,vd=class extends jt{static get observedAttributes(){return [...super.observedAttributes,chunkDITZCOYN_cjs.d.MEDIA_VOLUME,chunkDITZCOYN_cjs.d.MEDIA_MUTED,chunkDITZCOYN_cjs.d.MEDIA_VOLUME_UNAVAILABLE]}constructor(){super(),this.range.addEventListener("input",()=>{let e=this.range.value,t=new chunkDITZCOYN_cjs.o.CustomEvent(chunkDITZCOYN_cjs.a.MEDIA_VOLUME_REQUEST,{composed:true,bubbles:true,detail:e});this.dispatchEvent(t);});}connectedCallback(){super.connectedCallback(),this.range.setAttribute("aria-label",chunkDITZCOYN_cjs.n("volume"));}attributeChangedCallback(e,t,i){super.attributeChangedCallback(e,t,i),(e===chunkDITZCOYN_cjs.d.MEDIA_VOLUME||e===chunkDITZCOYN_cjs.d.MEDIA_MUTED)&&(this.range.valueAsNumber=Ev(this),this.range.setAttribute("aria-valuetext",vv(this.range.valueAsNumber)),this.updateBar());}get mediaVolume(){return chunkDITZCOYN_cjs.D(this,chunkDITZCOYN_cjs.d.MEDIA_VOLUME,pv)}set mediaVolume(e){chunkDITZCOYN_cjs.E(this,chunkDITZCOYN_cjs.d.MEDIA_VOLUME,e);}get mediaMuted(){return chunkDITZCOYN_cjs.F(this,chunkDITZCOYN_cjs.d.MEDIA_MUTED)}set mediaMuted(e){chunkDITZCOYN_cjs.G(this,chunkDITZCOYN_cjs.d.MEDIA_MUTED,e);}get mediaVolumeUnavailable(){return chunkDITZCOYN_cjs.H(this,chunkDITZCOYN_cjs.d.MEDIA_VOLUME_UNAVAILABLE)}set mediaVolumeUnavailable(e){chunkDITZCOYN_cjs.I(this,chunkDITZCOYN_cjs.d.MEDIA_VOLUME_UNAVAILABLE,e);}};chunkDITZCOYN_cjs.o.customElements.get("media-volume-range")||chunkDITZCOYN_cjs.o.customElements.define("media-volume-range",vd);var _d=(s,e,t)=>{if(!e.has(s))throw TypeError("Cannot "+t)},ti=(s,e,t)=>(_d(s,e,"read from private field"),t?t.call(s):e.get(s)),pi=(s,e,t)=>{if(e.has(s))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(s):e.set(s,t);},Td=(s,e,t,i)=>(_d(s,e,"write to private field"),e.set(s,t),t),Bt=(s,e,t)=>(_d(s,e,"access private method"),t),qa,zr,yd,zf,za,Id,Ld,Qf,ii,Ns,Qr,Sd,Xf,ja,Ad;function Tv(s){return `
1083
1083
  <style>
1084
1084
  :host {
1085
1085
  transition: var(--media-menu-item-transition,
@@ -1197,7 +1197,7 @@
1197
1197
  ${this.getSuffixSlotInnerHTML(s)}
1198
1198
  </slot>
1199
1199
  <slot name="submenu"></slot>
1200
- `}function Tv(s){return ""}var Rt={TYPE:"type",VALUE:"value",CHECKED:"checked",DISABLED:"disabled"},Tt=class extends chunkDITZCOYN_cjs.o.HTMLElement{constructor(){if(super(),pi(this,yd),pi(this,za),pi(this,Ld),pi(this,Ns),pi(this,Sd),pi(this,ja),pi(this,qa,false),pi(this,zr,void 0),pi(this,ii,()=>{var e,t;this.submenuElement.items&&this.setAttribute("submenusize",`${this.submenuElement.items.length}`);let i=this.shadowRoot.querySelector('slot[name="description"]'),r=(e=this.submenuElement.checkedItems)==null?void 0:e[0],n=(t=r?.dataset.description)!=null?t:r?.text,a=chunkDITZCOYN_cjs.p.createElement("span");a.textContent=n??"",i.replaceChildren(a);}),!this.shadowRoot){this.attachShadow(this.constructor.shadowRootOptions);let e=chunkDITZCOYN_cjs.s(this.attributes);this.shadowRoot.innerHTML=this.constructor.getTemplateHTML(e);}this.shadowRoot.addEventListener("slotchange",this);}static get observedAttributes(){return [Rt.TYPE,Rt.DISABLED,Rt.CHECKED,Rt.VALUE]}enable(){this.hasAttribute("tabindex")||this.setAttribute("tabindex","-1"),jr(this)&&!this.hasAttribute("aria-checked")&&this.setAttribute("aria-checked","false"),this.addEventListener("click",this),this.addEventListener("keydown",this);}disable(){this.removeAttribute("tabindex"),this.removeEventListener("click",this),this.removeEventListener("keydown",this),this.removeEventListener("keyup",this);}handleEvent(e){switch(e.type){case "slotchange":Bt(this,yd,jf).call(this,e);break;case "click":this.handleClick(e);break;case "keydown":Bt(this,Sd,Qf).call(this,e);break;case "keyup":Bt(this,Ns,Qr).call(this,e);break}}attributeChangedCallback(e,t,i){e===Rt.CHECKED&&jr(this)&&!ti(this,qa)?this.setAttribute("aria-checked",i!=null?"true":"false"):e===Rt.TYPE&&i!==t?this.role="menuitem"+i:e===Rt.DISABLED&&i!==t&&(i==null?this.enable():this.disable());}connectedCallback(){this.hasAttribute(Rt.DISABLED)||this.enable(),this.role="menuitem"+this.type,Td(this,zr,bd(this,this.parentNode)),Bt(this,ja,Ad).call(this),this.submenuElement&&Bt(this,za,Id).call(this);}disconnectedCallback(){this.disable(),Bt(this,ja,Ad).call(this),Td(this,zr,null);}get invokeTarget(){return this.getAttribute("invoketarget")}set invokeTarget(e){this.setAttribute("invoketarget",`${e}`);}get invokeTargetElement(){var e;return this.invokeTarget?(e=chunkDITZCOYN_cjs.z(this))==null?void 0:e.querySelector(`#${this.invokeTarget}`):this.submenuElement}get submenuElement(){return this.shadowRoot.querySelector('slot[name="submenu"]').assignedElements({flatten:true})[0]}get type(){var e;return (e=this.getAttribute(Rt.TYPE))!=null?e:""}set type(e){this.setAttribute(Rt.TYPE,`${e}`);}get value(){var e;return (e=this.getAttribute(Rt.VALUE))!=null?e:this.text}set value(e){this.setAttribute(Rt.VALUE,e);}get text(){var e;return ((e=this.textContent)!=null?e:"").trim()}get checked(){if(jr(this))return this.getAttribute("aria-checked")==="true"}set checked(e){jr(this)&&(Td(this,qa,true),this.setAttribute("aria-checked",e?"true":"false"),e?this.part.add("checked"):this.part.remove("checked"));}handleClick(e){jr(this)||this.invokeTargetElement&&chunkDITZCOYN_cjs.w(this,e.target)&&this.invokeTargetElement.dispatchEvent(new chunkDITZCOYN_cjs.K({relatedTarget:this}));}get keysUsed(){return ["Enter"," "]}};qa=new WeakMap;zr=new WeakMap;yd=new WeakSet;jf=function(s){let e=s.target;if(!e?.name)for(let i of e.assignedNodes({flatten:true}))i instanceof Text&&i.textContent.trim()===""&&i.remove();e.name==="submenu"&&(this.submenuElement?Bt(this,za,Id).call(this):Bt(this,Ld,zf).call(this));};za=new WeakSet;Id=async function(){this.setAttribute("aria-haspopup","menu"),this.setAttribute("aria-expanded",`${!this.submenuElement.hidden}`),this.submenuElement.addEventListener("change",ti(this,ii)),this.submenuElement.addEventListener("addmenuitem",ti(this,ii)),this.submenuElement.addEventListener("removemenuitem",ti(this,ii)),ti(this,ii).call(this);};Ld=new WeakSet;zf=function(){this.removeAttribute("aria-haspopup"),this.removeAttribute("aria-expanded"),this.submenuElement.removeEventListener("change",ti(this,ii)),this.submenuElement.removeEventListener("addmenuitem",ti(this,ii)),this.submenuElement.removeEventListener("removemenuitem",ti(this,ii)),ti(this,ii).call(this);};ii=new WeakMap;Ns=new WeakSet;Qr=function(s){let{key:e}=s;if(!this.keysUsed.includes(e)){this.removeEventListener("keyup",Bt(this,Ns,Qr));return}this.handleClick(s);};Sd=new WeakSet;Qf=function(s){let{metaKey:e,altKey:t,key:i}=s;if(e||t||!this.keysUsed.includes(i)){this.removeEventListener("keyup",Bt(this,Ns,Qr));return}this.addEventListener("keyup",Bt(this,Ns,Qr),{once:true});};ja=new WeakSet;Ad=function(){var s;let e=(s=ti(this,zr))==null?void 0:s.radioGroupItems;if(!e)return;let t=e.filter(i=>i.getAttribute("aria-checked")==="true").pop();t||(t=e[0]);for(let i of e)i.setAttribute("aria-checked","false");t?.setAttribute("aria-checked","true");};Tt.shadowRootOptions={mode:"open"};Tt.getTemplateHTML=vv;Tt.getSuffixSlotInnerHTML=Tv;function jr(s){return s.type==="radio"||s.type==="checkbox"}function bd(s,e){if(!s)return null;let{host:t}=s.getRootNode();return !e&&t?bd(s,t):e?.items?e:bd(e,e?.parentNode)}chunkDITZCOYN_cjs.o.customElements.get("media-chrome-menu-item")||chunkDITZCOYN_cjs.o.customElements.define("media-chrome-menu-item",Tt);function yv(s){return `
1200
+ `}function yv(s){return ""}var Rt={TYPE:"type",VALUE:"value",CHECKED:"checked",DISABLED:"disabled"},Tt=class extends chunkDITZCOYN_cjs.o.HTMLElement{constructor(){if(super(),pi(this,yd),pi(this,za),pi(this,Ld),pi(this,Ns),pi(this,Sd),pi(this,ja),pi(this,qa,false),pi(this,zr,void 0),pi(this,ii,()=>{var e,t;this.submenuElement.items&&this.setAttribute("submenusize",`${this.submenuElement.items.length}`);let i=this.shadowRoot.querySelector('slot[name="description"]'),r=(e=this.submenuElement.checkedItems)==null?void 0:e[0],n=(t=r?.dataset.description)!=null?t:r?.text,a=chunkDITZCOYN_cjs.p.createElement("span");a.textContent=n??"",i.replaceChildren(a);}),!this.shadowRoot){this.attachShadow(this.constructor.shadowRootOptions);let e=chunkDITZCOYN_cjs.s(this.attributes);this.shadowRoot.innerHTML=this.constructor.getTemplateHTML(e);}this.shadowRoot.addEventListener("slotchange",this);}static get observedAttributes(){return [Rt.TYPE,Rt.DISABLED,Rt.CHECKED,Rt.VALUE]}enable(){this.hasAttribute("tabindex")||this.setAttribute("tabindex","-1"),jr(this)&&!this.hasAttribute("aria-checked")&&this.setAttribute("aria-checked","false"),this.addEventListener("click",this),this.addEventListener("keydown",this);}disable(){this.removeAttribute("tabindex"),this.removeEventListener("click",this),this.removeEventListener("keydown",this),this.removeEventListener("keyup",this);}handleEvent(e){switch(e.type){case "slotchange":Bt(this,yd,zf).call(this,e);break;case "click":this.handleClick(e);break;case "keydown":Bt(this,Sd,Xf).call(this,e);break;case "keyup":Bt(this,Ns,Qr).call(this,e);break}}attributeChangedCallback(e,t,i){e===Rt.CHECKED&&jr(this)&&!ti(this,qa)?this.setAttribute("aria-checked",i!=null?"true":"false"):e===Rt.TYPE&&i!==t?this.role="menuitem"+i:e===Rt.DISABLED&&i!==t&&(i==null?this.enable():this.disable());}connectedCallback(){this.hasAttribute(Rt.DISABLED)||this.enable(),this.role="menuitem"+this.type,Td(this,zr,bd(this,this.parentNode)),Bt(this,ja,Ad).call(this),this.submenuElement&&Bt(this,za,Id).call(this);}disconnectedCallback(){this.disable(),Bt(this,ja,Ad).call(this),Td(this,zr,null);}get invokeTarget(){return this.getAttribute("invoketarget")}set invokeTarget(e){this.setAttribute("invoketarget",`${e}`);}get invokeTargetElement(){var e;return this.invokeTarget?(e=chunkDITZCOYN_cjs.z(this))==null?void 0:e.querySelector(`#${this.invokeTarget}`):this.submenuElement}get submenuElement(){return this.shadowRoot.querySelector('slot[name="submenu"]').assignedElements({flatten:true})[0]}get type(){var e;return (e=this.getAttribute(Rt.TYPE))!=null?e:""}set type(e){this.setAttribute(Rt.TYPE,`${e}`);}get value(){var e;return (e=this.getAttribute(Rt.VALUE))!=null?e:this.text}set value(e){this.setAttribute(Rt.VALUE,e);}get text(){var e;return ((e=this.textContent)!=null?e:"").trim()}get checked(){if(jr(this))return this.getAttribute("aria-checked")==="true"}set checked(e){jr(this)&&(Td(this,qa,true),this.setAttribute("aria-checked",e?"true":"false"),e?this.part.add("checked"):this.part.remove("checked"));}handleClick(e){jr(this)||this.invokeTargetElement&&chunkDITZCOYN_cjs.w(this,e.target)&&this.invokeTargetElement.dispatchEvent(new chunkDITZCOYN_cjs.K({relatedTarget:this}));}get keysUsed(){return ["Enter"," "]}};qa=new WeakMap;zr=new WeakMap;yd=new WeakSet;zf=function(s){let e=s.target;if(!e?.name)for(let i of e.assignedNodes({flatten:true}))i instanceof Text&&i.textContent.trim()===""&&i.remove();e.name==="submenu"&&(this.submenuElement?Bt(this,za,Id).call(this):Bt(this,Ld,Qf).call(this));};za=new WeakSet;Id=async function(){this.setAttribute("aria-haspopup","menu"),this.setAttribute("aria-expanded",`${!this.submenuElement.hidden}`),this.submenuElement.addEventListener("change",ti(this,ii)),this.submenuElement.addEventListener("addmenuitem",ti(this,ii)),this.submenuElement.addEventListener("removemenuitem",ti(this,ii)),ti(this,ii).call(this);};Ld=new WeakSet;Qf=function(){this.removeAttribute("aria-haspopup"),this.removeAttribute("aria-expanded"),this.submenuElement.removeEventListener("change",ti(this,ii)),this.submenuElement.removeEventListener("addmenuitem",ti(this,ii)),this.submenuElement.removeEventListener("removemenuitem",ti(this,ii)),ti(this,ii).call(this);};ii=new WeakMap;Ns=new WeakSet;Qr=function(s){let{key:e}=s;if(!this.keysUsed.includes(e)){this.removeEventListener("keyup",Bt(this,Ns,Qr));return}this.handleClick(s);};Sd=new WeakSet;Xf=function(s){let{metaKey:e,altKey:t,key:i}=s;if(e||t||!this.keysUsed.includes(i)){this.removeEventListener("keyup",Bt(this,Ns,Qr));return}this.addEventListener("keyup",Bt(this,Ns,Qr),{once:true});};ja=new WeakSet;Ad=function(){var s;let e=(s=ti(this,zr))==null?void 0:s.radioGroupItems;if(!e)return;let t=e.filter(i=>i.getAttribute("aria-checked")==="true").pop();t||(t=e[0]);for(let i of e)i.setAttribute("aria-checked","false");t?.setAttribute("aria-checked","true");};Tt.shadowRootOptions={mode:"open"};Tt.getTemplateHTML=Tv;Tt.getSuffixSlotInnerHTML=yv;function jr(s){return s.type==="radio"||s.type==="checkbox"}function bd(s,e){if(!s)return null;let{host:t}=s.getRootNode();return !e&&t?bd(s,t):e?.items?e:bd(e,e?.parentNode)}chunkDITZCOYN_cjs.o.customElements.get("media-chrome-menu-item")||chunkDITZCOYN_cjs.o.customElements.define("media-chrome-menu-item",Tt);function Sv(s){return `
1201
1201
  ${chunkDITZCOYN_cjs.N.getTemplateHTML(s)}
1202
1202
  <style>
1203
1203
  :host {
@@ -1232,7 +1232,7 @@
1232
1232
  --media-settings-menu-item-opacity: 0;
1233
1233
  }
1234
1234
  </style>
1235
- `}var Xr=class extends chunkDITZCOYN_cjs.N{get anchorElement(){return this.anchor!=="auto"?super.anchorElement:chunkDITZCOYN_cjs.t(this).querySelector("media-settings-menu-button")}};Xr.getTemplateHTML=yv;chunkDITZCOYN_cjs.o.customElements.get("media-settings-menu")||chunkDITZCOYN_cjs.o.customElements.define("media-settings-menu",Xr);function Sv(s){return `
1235
+ `}var Xr=class extends chunkDITZCOYN_cjs.N{get anchorElement(){return this.anchor!=="auto"?super.anchorElement:chunkDITZCOYN_cjs.t(this).querySelector("media-settings-menu-button")}};Xr.getTemplateHTML=Sv;chunkDITZCOYN_cjs.o.customElements.get("media-settings-menu")||chunkDITZCOYN_cjs.o.customElements.define("media-settings-menu",Xr);function Av(s){return `
1236
1236
  ${Tt.getTemplateHTML.call(this,s)}
1237
1237
  <style>
1238
1238
  slot:not([name="submenu"]) {
@@ -1243,11 +1243,11 @@
1243
1243
  background: transparent;
1244
1244
  }
1245
1245
  </style>
1246
- `}function Av(s){return `
1246
+ `}function bv(s){return `
1247
1247
  <svg aria-hidden="true" viewBox="0 0 20 24">
1248
1248
  <path d="m8.12 17.585-.742-.669 4.2-4.665-4.2-4.666.743-.669 4.803 5.335-4.803 5.334Z"/>
1249
1249
  </svg>
1250
- `}var ts=class extends Tt{};ts.shadowRootOptions={mode:"open"};ts.getTemplateHTML=Sv;ts.getSuffixSlotInnerHTML=Av;chunkDITZCOYN_cjs.o.customElements.get("media-settings-menu-item")||chunkDITZCOYN_cjs.o.customElements.define("media-settings-menu-item",ts);function bv(){return `
1250
+ `}var ts=class extends Tt{};ts.shadowRootOptions={mode:"open"};ts.getTemplateHTML=Av;ts.getSuffixSlotInnerHTML=bv;chunkDITZCOYN_cjs.o.customElements.get("media-settings-menu-item")||chunkDITZCOYN_cjs.o.customElements.define("media-settings-menu-item",ts);function _v(){return `
1251
1251
  <style>
1252
1252
  :host([aria-expanded="true"]) slot[name=tooltip] {
1253
1253
  display: none;
@@ -1258,27 +1258,27 @@
1258
1258
  <path d="M4.5 14.5a2.5 2.5 0 1 0 0-5 2.5 2.5 0 0 0 0 5Zm7.5 0a2.5 2.5 0 1 0 0-5 2.5 2.5 0 0 0 0 5Zm7.5 0a2.5 2.5 0 1 0 0-5 2.5 2.5 0 0 0 0 5Z"/>
1259
1259
  </svg>
1260
1260
  </slot>
1261
- `}function _v(){return chunkDITZCOYN_cjs.n("Settings")}var Us=class extends chunkDITZCOYN_cjs.O{static get observedAttributes(){return [...super.observedAttributes,"target"]}connectedCallback(){super.connectedCallback(),this.setAttribute("aria-label",chunkDITZCOYN_cjs.n("settings"));}get invokeTargetElement(){return this.invokeTarget!=null?super.invokeTargetElement:chunkDITZCOYN_cjs.t(this).querySelector("media-settings-menu")}};Us.getSlotTemplateHTML=bv;Us.getTooltipContentHTML=_v;chunkDITZCOYN_cjs.o.customElements.get("media-settings-menu-button")||chunkDITZCOYN_cjs.o.customElements.define("media-settings-menu-button",Us);var Dd=(s,e,t)=>{if(!e.has(s))throw TypeError("Cannot "+t)},Xf=(s,e,t)=>(Dd(s,e,"read from private field"),t?t.call(s):e.get(s)),Qa=(s,e,t)=>{if(e.has(s))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(s):e.set(s,t);},xd=(s,e,t,i)=>(Dd(s,e,"write to private field"),e.set(s,t),t),Xa=(s,e,t)=>(Dd(s,e,"access private method"),t),Zr,eo,Za,Rd,Ja,kd,to=class extends chunkDITZCOYN_cjs.N{constructor(){super(...arguments),Qa(this,Za),Qa(this,Ja),Qa(this,Zr,[]),Qa(this,eo,void 0);}static get observedAttributes(){return [...super.observedAttributes,chunkDITZCOYN_cjs.d.MEDIA_AUDIO_TRACK_LIST,chunkDITZCOYN_cjs.d.MEDIA_AUDIO_TRACK_ENABLED,chunkDITZCOYN_cjs.d.MEDIA_AUDIO_TRACK_UNAVAILABLE]}attributeChangedCallback(e,t,i){super.attributeChangedCallback(e,t,i),e===chunkDITZCOYN_cjs.d.MEDIA_AUDIO_TRACK_ENABLED&&t!==i?this.value=i:e===chunkDITZCOYN_cjs.d.MEDIA_AUDIO_TRACK_LIST&&t!==i&&(xd(this,Zr,Ih(i??"")),Xa(this,Za,Rd).call(this));}connectedCallback(){super.connectedCallback(),this.addEventListener("change",Xa(this,Ja,kd));}disconnectedCallback(){super.disconnectedCallback(),this.removeEventListener("change",Xa(this,Ja,kd));}get anchorElement(){var e;return this.anchor!=="auto"?super.anchorElement:(e=chunkDITZCOYN_cjs.t(this))==null?void 0:e.querySelector("media-audio-track-menu-button")}get mediaAudioTrackList(){return Xf(this,Zr)}set mediaAudioTrackList(e){xd(this,Zr,e),Xa(this,Za,Rd).call(this);}get mediaAudioTrackEnabled(){var e;return (e=chunkDITZCOYN_cjs.H(this,chunkDITZCOYN_cjs.d.MEDIA_AUDIO_TRACK_ENABLED))!=null?e:""}set mediaAudioTrackEnabled(e){chunkDITZCOYN_cjs.I(this,chunkDITZCOYN_cjs.d.MEDIA_AUDIO_TRACK_ENABLED,e);}};Zr=new WeakMap;eo=new WeakMap;Za=new WeakSet;Rd=function(){if(Xf(this,eo)===JSON.stringify(this.mediaAudioTrackList))return;xd(this,eo,JSON.stringify(this.mediaAudioTrackList));let s=this.mediaAudioTrackList;this.defaultSlot.textContent="",s.sort((e,t)=>e.id.localeCompare(t.id,void 0,{numeric:true}));for(let e of s){let t=this.formatMenuItemText(e.label,e),i=chunkDITZCOYN_cjs.L({type:"radio",text:t,value:`${e.id}`,checked:e.enabled});i.prepend(chunkDITZCOYN_cjs.M(this,"checked-indicator")),this.defaultSlot.append(i);}};Ja=new WeakSet;kd=function(){if(this.value==null)return;let s=new chunkDITZCOYN_cjs.o.CustomEvent(chunkDITZCOYN_cjs.a.MEDIA_AUDIO_TRACK_REQUEST,{composed:true,bubbles:true,detail:this.value});this.dispatchEvent(s);};chunkDITZCOYN_cjs.o.customElements.get("media-audio-track-menu")||chunkDITZCOYN_cjs.o.customElements.define("media-audio-track-menu",to);var Iv=`<svg aria-hidden="true" viewBox="0 0 24 24">
1261
+ `}function Iv(){return chunkDITZCOYN_cjs.n("Settings")}var Us=class extends chunkDITZCOYN_cjs.O{static get observedAttributes(){return [...super.observedAttributes,"target"]}connectedCallback(){super.connectedCallback(),this.setAttribute("aria-label",chunkDITZCOYN_cjs.n("settings"));}get invokeTargetElement(){return this.invokeTarget!=null?super.invokeTargetElement:chunkDITZCOYN_cjs.t(this).querySelector("media-settings-menu")}};Us.getSlotTemplateHTML=_v;Us.getTooltipContentHTML=Iv;chunkDITZCOYN_cjs.o.customElements.get("media-settings-menu-button")||chunkDITZCOYN_cjs.o.customElements.define("media-settings-menu-button",Us);var Dd=(s,e,t)=>{if(!e.has(s))throw TypeError("Cannot "+t)},Zf=(s,e,t)=>(Dd(s,e,"read from private field"),t?t.call(s):e.get(s)),Qa=(s,e,t)=>{if(e.has(s))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(s):e.set(s,t);},xd=(s,e,t,i)=>(Dd(s,e,"write to private field"),e.set(s,t),t),Xa=(s,e,t)=>(Dd(s,e,"access private method"),t),Zr,eo,Za,Rd,Ja,kd,to=class extends chunkDITZCOYN_cjs.N{constructor(){super(...arguments),Qa(this,Za),Qa(this,Ja),Qa(this,Zr,[]),Qa(this,eo,void 0);}static get observedAttributes(){return [...super.observedAttributes,chunkDITZCOYN_cjs.d.MEDIA_AUDIO_TRACK_LIST,chunkDITZCOYN_cjs.d.MEDIA_AUDIO_TRACK_ENABLED,chunkDITZCOYN_cjs.d.MEDIA_AUDIO_TRACK_UNAVAILABLE]}attributeChangedCallback(e,t,i){super.attributeChangedCallback(e,t,i),e===chunkDITZCOYN_cjs.d.MEDIA_AUDIO_TRACK_ENABLED&&t!==i?this.value=i:e===chunkDITZCOYN_cjs.d.MEDIA_AUDIO_TRACK_LIST&&t!==i&&(xd(this,Zr,Lh(i??"")),Xa(this,Za,Rd).call(this));}connectedCallback(){super.connectedCallback(),this.addEventListener("change",Xa(this,Ja,kd));}disconnectedCallback(){super.disconnectedCallback(),this.removeEventListener("change",Xa(this,Ja,kd));}get anchorElement(){var e;return this.anchor!=="auto"?super.anchorElement:(e=chunkDITZCOYN_cjs.t(this))==null?void 0:e.querySelector("media-audio-track-menu-button")}get mediaAudioTrackList(){return Zf(this,Zr)}set mediaAudioTrackList(e){xd(this,Zr,e),Xa(this,Za,Rd).call(this);}get mediaAudioTrackEnabled(){var e;return (e=chunkDITZCOYN_cjs.H(this,chunkDITZCOYN_cjs.d.MEDIA_AUDIO_TRACK_ENABLED))!=null?e:""}set mediaAudioTrackEnabled(e){chunkDITZCOYN_cjs.I(this,chunkDITZCOYN_cjs.d.MEDIA_AUDIO_TRACK_ENABLED,e);}};Zr=new WeakMap;eo=new WeakMap;Za=new WeakSet;Rd=function(){if(Zf(this,eo)===JSON.stringify(this.mediaAudioTrackList))return;xd(this,eo,JSON.stringify(this.mediaAudioTrackList));let s=this.mediaAudioTrackList;this.defaultSlot.textContent="",s.sort((e,t)=>e.id.localeCompare(t.id,void 0,{numeric:true}));for(let e of s){let t=this.formatMenuItemText(e.label,e),i=chunkDITZCOYN_cjs.L({type:"radio",text:t,value:`${e.id}`,checked:e.enabled});i.prepend(chunkDITZCOYN_cjs.M(this,"checked-indicator")),this.defaultSlot.append(i);}};Ja=new WeakSet;kd=function(){if(this.value==null)return;let s=new chunkDITZCOYN_cjs.o.CustomEvent(chunkDITZCOYN_cjs.a.MEDIA_AUDIO_TRACK_REQUEST,{composed:true,bubbles:true,detail:this.value});this.dispatchEvent(s);};chunkDITZCOYN_cjs.o.customElements.get("media-audio-track-menu")||chunkDITZCOYN_cjs.o.customElements.define("media-audio-track-menu",to);var Lv=`<svg aria-hidden="true" viewBox="0 0 24 24">
1262
1262
  <path d="M11 17H9.5V7H11v10Zm-3-3H6.5v-4H8v4Zm6-5h-1.5v6H14V9Zm3 7h-1.5V8H17v8Z"/>
1263
1263
  <path d="M22 12c0 5.523-4.477 10-10 10S2 17.523 2 12 6.477 2 12 2s10 4.477 10 10Zm-2 0a8 8 0 1 0-16 0 8 8 0 0 0 16 0Z"/>
1264
- </svg>`;function Lv(){return `
1264
+ </svg>`;function xv(){return `
1265
1265
  <style>
1266
1266
  :host([aria-expanded="true"]) slot[name=tooltip] {
1267
1267
  display: none;
1268
1268
  }
1269
1269
  </style>
1270
- <slot name="icon">${Iv}</slot>
1271
- `}function xv(){return chunkDITZCOYN_cjs.n("Audio")}var Zf=s=>{let e=chunkDITZCOYN_cjs.n("Audio");s.setAttribute("aria-label",e);},Bs=class extends chunkDITZCOYN_cjs.O{static get observedAttributes(){return [...super.observedAttributes,chunkDITZCOYN_cjs.d.MEDIA_AUDIO_TRACK_ENABLED,chunkDITZCOYN_cjs.d.MEDIA_AUDIO_TRACK_UNAVAILABLE]}connectedCallback(){super.connectedCallback(),Zf(this);}attributeChangedCallback(e,t,i){super.attributeChangedCallback(e,t,i),e===chunkDITZCOYN_cjs.d.MEDIA_LANG&&Zf(this);}get invokeTargetElement(){var e;return this.invokeTarget!=null?super.invokeTargetElement:(e=chunkDITZCOYN_cjs.t(this))==null?void 0:e.querySelector("media-audio-track-menu")}get mediaAudioTrackEnabled(){var e;return (e=chunkDITZCOYN_cjs.H(this,chunkDITZCOYN_cjs.d.MEDIA_AUDIO_TRACK_ENABLED))!=null?e:""}set mediaAudioTrackEnabled(e){chunkDITZCOYN_cjs.I(this,chunkDITZCOYN_cjs.d.MEDIA_AUDIO_TRACK_ENABLED,e);}};Bs.getSlotTemplateHTML=Lv;Bs.getTooltipContentHTML=xv;chunkDITZCOYN_cjs.o.customElements.get("media-audio-track-menu-button")||chunkDITZCOYN_cjs.o.customElements.define("media-audio-track-menu-button",Bs);var Od=(s,e,t)=>{if(!e.has(s))throw TypeError("Cannot "+t)},Rv=(s,e,t)=>(Od(s,e,"read from private field"),e.get(s)),Cd=(s,e,t)=>{if(e.has(s))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(s):e.set(s,t);},kv=(s,e,t,i)=>(Od(s,e,"write to private field"),e.set(s,t),t),Md=(s,e,t)=>(Od(s,e,"access private method"),t),so,Pd,tm,io,wd,Dv=`
1270
+ <slot name="icon">${Lv}</slot>
1271
+ `}function Rv(){return chunkDITZCOYN_cjs.n("Audio")}var Jf=s=>{let e=chunkDITZCOYN_cjs.n("Audio");s.setAttribute("aria-label",e);},Bs=class extends chunkDITZCOYN_cjs.O{static get observedAttributes(){return [...super.observedAttributes,chunkDITZCOYN_cjs.d.MEDIA_AUDIO_TRACK_ENABLED,chunkDITZCOYN_cjs.d.MEDIA_AUDIO_TRACK_UNAVAILABLE]}connectedCallback(){super.connectedCallback(),Jf(this);}attributeChangedCallback(e,t,i){super.attributeChangedCallback(e,t,i),e===chunkDITZCOYN_cjs.d.MEDIA_LANG&&Jf(this);}get invokeTargetElement(){var e;return this.invokeTarget!=null?super.invokeTargetElement:(e=chunkDITZCOYN_cjs.t(this))==null?void 0:e.querySelector("media-audio-track-menu")}get mediaAudioTrackEnabled(){var e;return (e=chunkDITZCOYN_cjs.H(this,chunkDITZCOYN_cjs.d.MEDIA_AUDIO_TRACK_ENABLED))!=null?e:""}set mediaAudioTrackEnabled(e){chunkDITZCOYN_cjs.I(this,chunkDITZCOYN_cjs.d.MEDIA_AUDIO_TRACK_ENABLED,e);}};Bs.getSlotTemplateHTML=xv;Bs.getTooltipContentHTML=Rv;chunkDITZCOYN_cjs.o.customElements.get("media-audio-track-menu-button")||chunkDITZCOYN_cjs.o.customElements.define("media-audio-track-menu-button",Bs);var Od=(s,e,t)=>{if(!e.has(s))throw TypeError("Cannot "+t)},kv=(s,e,t)=>(Od(s,e,"read from private field"),e.get(s)),Cd=(s,e,t)=>{if(e.has(s))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(s):e.set(s,t);},Dv=(s,e,t,i)=>(Od(s,e,"write to private field"),e.set(s,t),t),Md=(s,e,t)=>(Od(s,e,"access private method"),t),so,Pd,im,io,wd,Cv=`
1272
1272
  <svg aria-hidden="true" viewBox="0 0 26 24" part="captions-indicator indicator">
1273
1273
  <path d="M22.83 5.68a2.58 2.58 0 0 0-2.3-2.5c-3.62-.24-11.44-.24-15.06 0a2.58 2.58 0 0 0-2.3 2.5c-.23 4.21-.23 8.43 0 12.64a2.58 2.58 0 0 0 2.3 2.5c3.62.24 11.44.24 15.06 0a2.58 2.58 0 0 0 2.3-2.5c.23-4.21.23-8.43 0-12.64Zm-11.39 9.45a3.07 3.07 0 0 1-1.91.57 3.06 3.06 0 0 1-2.34-1 3.75 3.75 0 0 1-.92-2.67 3.92 3.92 0 0 1 .92-2.77 3.18 3.18 0 0 1 2.43-1 2.94 2.94 0 0 1 2.13.78c.364.359.62.813.74 1.31l-1.43.35a1.49 1.49 0 0 0-1.51-1.17 1.61 1.61 0 0 0-1.29.58 2.79 2.79 0 0 0-.5 1.89 3 3 0 0 0 .49 1.93 1.61 1.61 0 0 0 1.27.58 1.48 1.48 0 0 0 1-.37 2.1 2.1 0 0 0 .59-1.14l1.4.44a3.23 3.23 0 0 1-1.07 1.69Zm7.22 0a3.07 3.07 0 0 1-1.91.57 3.06 3.06 0 0 1-2.34-1 3.75 3.75 0 0 1-.92-2.67 3.88 3.88 0 0 1 .93-2.77 3.14 3.14 0 0 1 2.42-1 3 3 0 0 1 2.16.82 2.8 2.8 0 0 1 .73 1.31l-1.43.35a1.49 1.49 0 0 0-1.51-1.21 1.61 1.61 0 0 0-1.29.58A2.79 2.79 0 0 0 15 12a3 3 0 0 0 .49 1.93 1.61 1.61 0 0 0 1.27.58 1.44 1.44 0 0 0 1-.37 2.1 2.1 0 0 0 .6-1.15l1.4.44a3.17 3.17 0 0 1-1.1 1.7Z"/>
1274
- </svg>`;function Cv(s){return `
1274
+ </svg>`;function Mv(s){return `
1275
1275
  ${chunkDITZCOYN_cjs.N.getTemplateHTML(s)}
1276
- <slot name="captions-indicator" hidden>${Dv}</slot>
1277
- `}var Jr=class extends chunkDITZCOYN_cjs.N{constructor(){super(...arguments),Cd(this,Pd),Cd(this,io),Cd(this,so,void 0);}static get observedAttributes(){return [...super.observedAttributes,chunkDITZCOYN_cjs.d.MEDIA_SUBTITLES_LIST,chunkDITZCOYN_cjs.d.MEDIA_SUBTITLES_SHOWING]}attributeChangedCallback(e,t,i){super.attributeChangedCallback(e,t,i),e===chunkDITZCOYN_cjs.d.MEDIA_SUBTITLES_LIST&&t!==i?Md(this,Pd,tm).call(this):e===chunkDITZCOYN_cjs.d.MEDIA_SUBTITLES_SHOWING&&t!==i&&(this.value=i);}connectedCallback(){super.connectedCallback(),this.addEventListener("change",Md(this,io,wd));}disconnectedCallback(){super.disconnectedCallback(),this.removeEventListener("change",Md(this,io,wd));}get anchorElement(){return this.anchor!=="auto"?super.anchorElement:chunkDITZCOYN_cjs.t(this).querySelector("media-captions-menu-button")}get mediaSubtitlesList(){return Jf(this,chunkDITZCOYN_cjs.d.MEDIA_SUBTITLES_LIST)}set mediaSubtitlesList(e){em(this,chunkDITZCOYN_cjs.d.MEDIA_SUBTITLES_LIST,e);}get mediaSubtitlesShowing(){return Jf(this,chunkDITZCOYN_cjs.d.MEDIA_SUBTITLES_SHOWING)}set mediaSubtitlesShowing(e){em(this,chunkDITZCOYN_cjs.d.MEDIA_SUBTITLES_SHOWING,e);}};so=new WeakMap;Pd=new WeakSet;tm=function(){var s;if(Rv(this,so)===JSON.stringify(this.mediaSubtitlesList))return;kv(this,so,JSON.stringify(this.mediaSubtitlesList)),this.defaultSlot.textContent="";let e=!this.value,t=chunkDITZCOYN_cjs.L({type:"radio",text:this.formatMenuItemText(chunkDITZCOYN_cjs.n("Off")),value:"off",checked:e});t.prepend(chunkDITZCOYN_cjs.M(this,"checked-indicator")),this.defaultSlot.append(t);let i=this.mediaSubtitlesList;for(let r of i){let n=chunkDITZCOYN_cjs.L({type:"radio",text:this.formatMenuItemText(r.label,r),value:Qn(r),checked:this.value==Qn(r)});n.prepend(chunkDITZCOYN_cjs.M(this,"checked-indicator")),((s=r.kind)!=null?s:"subs")==="captions"&&n.append(chunkDITZCOYN_cjs.M(this,"captions-indicator")),this.defaultSlot.append(n);}};io=new WeakSet;wd=function(){let s=this.mediaSubtitlesShowing,e=this.getAttribute(chunkDITZCOYN_cjs.d.MEDIA_SUBTITLES_SHOWING),t=this.value!==e;if(s?.length&&t&&this.dispatchEvent(new chunkDITZCOYN_cjs.o.CustomEvent(chunkDITZCOYN_cjs.a.MEDIA_DISABLE_SUBTITLES_REQUEST,{composed:true,bubbles:true,detail:s})),!this.value||!t)return;let i=new chunkDITZCOYN_cjs.o.CustomEvent(chunkDITZCOYN_cjs.a.MEDIA_SHOW_SUBTITLES_REQUEST,{composed:true,bubbles:true,detail:this.value});this.dispatchEvent(i);};Jr.getTemplateHTML=Cv;var Jf=(s,e)=>{let t=s.getAttribute(e);return t?Ki(t):[]},em=(s,e,t)=>{if(!t?.length){s.removeAttribute(e);return}let i=fi(t);s.getAttribute(e)!==i&&s.setAttribute(e,i);};chunkDITZCOYN_cjs.o.customElements.get("media-captions-menu")||chunkDITZCOYN_cjs.o.customElements.define("media-captions-menu",Jr);var Mv=`<svg aria-hidden="true" viewBox="0 0 26 24">
1276
+ <slot name="captions-indicator" hidden>${Cv}</slot>
1277
+ `}var Jr=class extends chunkDITZCOYN_cjs.N{constructor(){super(...arguments),Cd(this,Pd),Cd(this,io),Cd(this,so,void 0);}static get observedAttributes(){return [...super.observedAttributes,chunkDITZCOYN_cjs.d.MEDIA_SUBTITLES_LIST,chunkDITZCOYN_cjs.d.MEDIA_SUBTITLES_SHOWING]}attributeChangedCallback(e,t,i){super.attributeChangedCallback(e,t,i),e===chunkDITZCOYN_cjs.d.MEDIA_SUBTITLES_LIST&&t!==i?Md(this,Pd,im).call(this):e===chunkDITZCOYN_cjs.d.MEDIA_SUBTITLES_SHOWING&&t!==i&&(this.value=i);}connectedCallback(){super.connectedCallback(),this.addEventListener("change",Md(this,io,wd));}disconnectedCallback(){super.disconnectedCallback(),this.removeEventListener("change",Md(this,io,wd));}get anchorElement(){return this.anchor!=="auto"?super.anchorElement:chunkDITZCOYN_cjs.t(this).querySelector("media-captions-menu-button")}get mediaSubtitlesList(){return em(this,chunkDITZCOYN_cjs.d.MEDIA_SUBTITLES_LIST)}set mediaSubtitlesList(e){tm(this,chunkDITZCOYN_cjs.d.MEDIA_SUBTITLES_LIST,e);}get mediaSubtitlesShowing(){return em(this,chunkDITZCOYN_cjs.d.MEDIA_SUBTITLES_SHOWING)}set mediaSubtitlesShowing(e){tm(this,chunkDITZCOYN_cjs.d.MEDIA_SUBTITLES_SHOWING,e);}};so=new WeakMap;Pd=new WeakSet;im=function(){var s;if(kv(this,so)===JSON.stringify(this.mediaSubtitlesList))return;Dv(this,so,JSON.stringify(this.mediaSubtitlesList)),this.defaultSlot.textContent="";let e=!this.value,t=chunkDITZCOYN_cjs.L({type:"radio",text:this.formatMenuItemText(chunkDITZCOYN_cjs.n("Off")),value:"off",checked:e});t.prepend(chunkDITZCOYN_cjs.M(this,"checked-indicator")),this.defaultSlot.append(t);let i=this.mediaSubtitlesList;for(let r of i){let n=chunkDITZCOYN_cjs.L({type:"radio",text:this.formatMenuItemText(r.label,r),value:Qn(r),checked:this.value==Qn(r)});n.prepend(chunkDITZCOYN_cjs.M(this,"checked-indicator")),((s=r.kind)!=null?s:"subs")==="captions"&&n.append(chunkDITZCOYN_cjs.M(this,"captions-indicator")),this.defaultSlot.append(n);}};io=new WeakSet;wd=function(){let s=this.mediaSubtitlesShowing,e=this.getAttribute(chunkDITZCOYN_cjs.d.MEDIA_SUBTITLES_SHOWING),t=this.value!==e;if(s?.length&&t&&this.dispatchEvent(new chunkDITZCOYN_cjs.o.CustomEvent(chunkDITZCOYN_cjs.a.MEDIA_DISABLE_SUBTITLES_REQUEST,{composed:true,bubbles:true,detail:s})),!this.value||!t)return;let i=new chunkDITZCOYN_cjs.o.CustomEvent(chunkDITZCOYN_cjs.a.MEDIA_SHOW_SUBTITLES_REQUEST,{composed:true,bubbles:true,detail:this.value});this.dispatchEvent(i);};Jr.getTemplateHTML=Mv;var em=(s,e)=>{let t=s.getAttribute(e);return t?Ki(t):[]},tm=(s,e,t)=>{if(!t?.length){s.removeAttribute(e);return}let i=fi(t);s.getAttribute(e)!==i&&s.setAttribute(e,i);};chunkDITZCOYN_cjs.o.customElements.get("media-captions-menu")||chunkDITZCOYN_cjs.o.customElements.define("media-captions-menu",Jr);var Pv=`<svg aria-hidden="true" viewBox="0 0 26 24">
1278
1278
  <path d="M22.83 5.68a2.58 2.58 0 0 0-2.3-2.5c-3.62-.24-11.44-.24-15.06 0a2.58 2.58 0 0 0-2.3 2.5c-.23 4.21-.23 8.43 0 12.64a2.58 2.58 0 0 0 2.3 2.5c3.62.24 11.44.24 15.06 0a2.58 2.58 0 0 0 2.3-2.5c.23-4.21.23-8.43 0-12.64Zm-11.39 9.45a3.07 3.07 0 0 1-1.91.57 3.06 3.06 0 0 1-2.34-1 3.75 3.75 0 0 1-.92-2.67 3.92 3.92 0 0 1 .92-2.77 3.18 3.18 0 0 1 2.43-1 2.94 2.94 0 0 1 2.13.78c.364.359.62.813.74 1.31l-1.43.35a1.49 1.49 0 0 0-1.51-1.17 1.61 1.61 0 0 0-1.29.58 2.79 2.79 0 0 0-.5 1.89 3 3 0 0 0 .49 1.93 1.61 1.61 0 0 0 1.27.58 1.48 1.48 0 0 0 1-.37 2.1 2.1 0 0 0 .59-1.14l1.4.44a3.23 3.23 0 0 1-1.07 1.69Zm7.22 0a3.07 3.07 0 0 1-1.91.57 3.06 3.06 0 0 1-2.34-1 3.75 3.75 0 0 1-.92-2.67 3.88 3.88 0 0 1 .93-2.77 3.14 3.14 0 0 1 2.42-1 3 3 0 0 1 2.16.82 2.8 2.8 0 0 1 .73 1.31l-1.43.35a1.49 1.49 0 0 0-1.51-1.21 1.61 1.61 0 0 0-1.29.58A2.79 2.79 0 0 0 15 12a3 3 0 0 0 .49 1.93 1.61 1.61 0 0 0 1.27.58 1.44 1.44 0 0 0 1-.37 2.1 2.1 0 0 0 .6-1.15l1.4.44a3.17 3.17 0 0 1-1.1 1.7Z"/>
1279
- </svg>`,Pv=`<svg aria-hidden="true" viewBox="0 0 26 24">
1279
+ </svg>`,wv=`<svg aria-hidden="true" viewBox="0 0 26 24">
1280
1280
  <path d="M17.73 14.09a1.4 1.4 0 0 1-1 .37 1.579 1.579 0 0 1-1.27-.58A3 3 0 0 1 15 12a2.8 2.8 0 0 1 .5-1.85 1.63 1.63 0 0 1 1.29-.57 1.47 1.47 0 0 1 1.51 1.2l1.43-.34A2.89 2.89 0 0 0 19 9.07a3 3 0 0 0-2.14-.78 3.14 3.14 0 0 0-2.42 1 3.91 3.91 0 0 0-.93 2.78 3.74 3.74 0 0 0 .92 2.66 3.07 3.07 0 0 0 2.34 1 3.07 3.07 0 0 0 1.91-.57 3.17 3.17 0 0 0 1.07-1.74l-1.4-.45c-.083.43-.3.822-.62 1.12Zm-7.22 0a1.43 1.43 0 0 1-1 .37 1.58 1.58 0 0 1-1.27-.58A3 3 0 0 1 7.76 12a2.8 2.8 0 0 1 .5-1.85 1.63 1.63 0 0 1 1.29-.57 1.47 1.47 0 0 1 1.51 1.2l1.43-.34a2.81 2.81 0 0 0-.74-1.32 2.94 2.94 0 0 0-2.13-.78 3.18 3.18 0 0 0-2.43 1 4 4 0 0 0-.92 2.78 3.74 3.74 0 0 0 .92 2.66 3.07 3.07 0 0 0 2.34 1 3.07 3.07 0 0 0 1.91-.57 3.23 3.23 0 0 0 1.07-1.74l-1.4-.45a2.06 2.06 0 0 1-.6 1.07Zm12.32-8.41a2.59 2.59 0 0 0-2.3-2.51C18.72 3.05 15.86 3 13 3c-2.86 0-5.72.05-7.53.17a2.59 2.59 0 0 0-2.3 2.51c-.23 4.207-.23 8.423 0 12.63a2.57 2.57 0 0 0 2.3 2.5c1.81.13 4.67.19 7.53.19 2.86 0 5.72-.06 7.53-.19a2.57 2.57 0 0 0 2.3-2.5c.23-4.207.23-8.423 0-12.63Zm-1.49 12.53a1.11 1.11 0 0 1-.91 1.11c-1.67.11-4.45.18-7.43.18-2.98 0-5.76-.07-7.43-.18a1.11 1.11 0 0 1-.91-1.11c-.21-4.14-.21-8.29 0-12.43a1.11 1.11 0 0 1 .91-1.11C7.24 4.56 10 4.49 13 4.49s5.76.07 7.43.18a1.11 1.11 0 0 1 .91 1.11c.21 4.14.21 8.29 0 12.43Z"/>
1281
- </svg>`;function wv(){return `
1281
+ </svg>`;function Ov(){return `
1282
1282
  <style>
1283
1283
  :host([data-captions-enabled="true"]) slot[name=off] {
1284
1284
  display: none !important;
@@ -1295,10 +1295,10 @@
1295
1295
  </style>
1296
1296
 
1297
1297
  <slot name="icon">
1298
- <slot name="on">${Mv}</slot>
1299
- <slot name="off">${Pv}</slot>
1298
+ <slot name="on">${Pv}</slot>
1299
+ <slot name="off">${wv}</slot>
1300
1300
  </slot>
1301
- `}function Ov(){return chunkDITZCOYN_cjs.n("Captions")}var im=s=>{s.setAttribute("data-captions-enabled",Xn(s).toString());},sm=s=>{s.setAttribute("aria-label",chunkDITZCOYN_cjs.n("closed captions"));},$s=class extends chunkDITZCOYN_cjs.O{static get observedAttributes(){return [...super.observedAttributes,chunkDITZCOYN_cjs.d.MEDIA_SUBTITLES_LIST,chunkDITZCOYN_cjs.d.MEDIA_SUBTITLES_SHOWING,chunkDITZCOYN_cjs.d.MEDIA_LANG]}connectedCallback(){super.connectedCallback(),sm(this),im(this);}attributeChangedCallback(e,t,i){super.attributeChangedCallback(e,t,i),e===chunkDITZCOYN_cjs.d.MEDIA_SUBTITLES_SHOWING?im(this):e===chunkDITZCOYN_cjs.d.MEDIA_LANG&&sm(this);}get invokeTargetElement(){var e;return this.invokeTarget!=null?super.invokeTargetElement:(e=chunkDITZCOYN_cjs.t(this))==null?void 0:e.querySelector("media-captions-menu")}get mediaSubtitlesList(){return rm(this,chunkDITZCOYN_cjs.d.MEDIA_SUBTITLES_LIST)}set mediaSubtitlesList(e){nm(this,chunkDITZCOYN_cjs.d.MEDIA_SUBTITLES_LIST,e);}get mediaSubtitlesShowing(){return rm(this,chunkDITZCOYN_cjs.d.MEDIA_SUBTITLES_SHOWING)}set mediaSubtitlesShowing(e){nm(this,chunkDITZCOYN_cjs.d.MEDIA_SUBTITLES_SHOWING,e);}};$s.getSlotTemplateHTML=wv;$s.getTooltipContentHTML=Ov;var rm=(s,e)=>{let t=s.getAttribute(e);return t?Ki(t):[]},nm=(s,e,t)=>{if(!t?.length){s.removeAttribute(e);return}let i=fi(t);s.getAttribute(e)!==i&&s.setAttribute(e,i);};chunkDITZCOYN_cjs.o.customElements.get("media-captions-menu-button")||chunkDITZCOYN_cjs.o.customElements.define("media-captions-menu-button",$s);var am=(s,e,t)=>{if(!e.has(s))throw TypeError("Cannot "+t)},Gs=(s,e,t)=>(am(s,e,"read from private field"),t?t.call(s):e.get(s)),Fd=(s,e,t)=>{if(e.has(s))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(s):e.set(s,t);},en=(s,e,t)=>(am(s,e,"access private method"),t),Ci,tn,ro,no,Ud,Nd={RATES:"rates"},ao=class extends chunkDITZCOYN_cjs.N{constructor(){super(),Fd(this,tn),Fd(this,no),Fd(this,Ci,new Ii(this,Nd.RATES,{defaultValue:sd})),en(this,tn,ro).call(this);}static get observedAttributes(){return [...super.observedAttributes,chunkDITZCOYN_cjs.d.MEDIA_PLAYBACK_RATE,Nd.RATES]}attributeChangedCallback(e,t,i){super.attributeChangedCallback(e,t,i),e===chunkDITZCOYN_cjs.d.MEDIA_PLAYBACK_RATE&&t!=i?this.value=i:e===Nd.RATES&&t!=i&&(Gs(this,Ci).value=i,en(this,tn,ro).call(this));}connectedCallback(){super.connectedCallback(),this.addEventListener("change",en(this,no,Ud));}disconnectedCallback(){super.disconnectedCallback(),this.removeEventListener("change",en(this,no,Ud));}get anchorElement(){return this.anchor!=="auto"?super.anchorElement:chunkDITZCOYN_cjs.t(this).querySelector("media-playback-rate-menu-button")}get rates(){return Gs(this,Ci)}set rates(e){e?Array.isArray(e)?Gs(this,Ci).value=e.join(" "):typeof e=="string"&&(Gs(this,Ci).value=e):Gs(this,Ci).value="",en(this,tn,ro).call(this);}get mediaPlaybackRate(){return chunkDITZCOYN_cjs.D(this,chunkDITZCOYN_cjs.d.MEDIA_PLAYBACK_RATE,Xi)}set mediaPlaybackRate(e){chunkDITZCOYN_cjs.E(this,chunkDITZCOYN_cjs.d.MEDIA_PLAYBACK_RATE,e);}};Ci=new WeakMap;tn=new WeakSet;ro=function(){this.defaultSlot.textContent="";for(let s of Gs(this,Ci)){let e=chunkDITZCOYN_cjs.L({type:"radio",text:this.formatMenuItemText(`${s}x`,s),value:s,checked:this.mediaPlaybackRate===Number(s)});e.prepend(chunkDITZCOYN_cjs.M(this,"checked-indicator")),this.defaultSlot.append(e);}};no=new WeakSet;Ud=function(){if(!this.value)return;let s=new chunkDITZCOYN_cjs.o.CustomEvent(chunkDITZCOYN_cjs.a.MEDIA_PLAYBACK_RATE_REQUEST,{composed:true,bubbles:true,detail:this.value});this.dispatchEvent(s);};chunkDITZCOYN_cjs.o.customElements.get("media-playback-rate-menu")||chunkDITZCOYN_cjs.o.customElements.define("media-playback-rate-menu",ao);var oo=1;function Fv(s){return `
1301
+ `}function Fv(){return chunkDITZCOYN_cjs.n("Captions")}var sm=s=>{s.setAttribute("data-captions-enabled",Xn(s).toString());},rm=s=>{s.setAttribute("aria-label",chunkDITZCOYN_cjs.n("closed captions"));},$s=class extends chunkDITZCOYN_cjs.O{static get observedAttributes(){return [...super.observedAttributes,chunkDITZCOYN_cjs.d.MEDIA_SUBTITLES_LIST,chunkDITZCOYN_cjs.d.MEDIA_SUBTITLES_SHOWING,chunkDITZCOYN_cjs.d.MEDIA_LANG]}connectedCallback(){super.connectedCallback(),rm(this),sm(this);}attributeChangedCallback(e,t,i){super.attributeChangedCallback(e,t,i),e===chunkDITZCOYN_cjs.d.MEDIA_SUBTITLES_SHOWING?sm(this):e===chunkDITZCOYN_cjs.d.MEDIA_LANG&&rm(this);}get invokeTargetElement(){var e;return this.invokeTarget!=null?super.invokeTargetElement:(e=chunkDITZCOYN_cjs.t(this))==null?void 0:e.querySelector("media-captions-menu")}get mediaSubtitlesList(){return nm(this,chunkDITZCOYN_cjs.d.MEDIA_SUBTITLES_LIST)}set mediaSubtitlesList(e){am(this,chunkDITZCOYN_cjs.d.MEDIA_SUBTITLES_LIST,e);}get mediaSubtitlesShowing(){return nm(this,chunkDITZCOYN_cjs.d.MEDIA_SUBTITLES_SHOWING)}set mediaSubtitlesShowing(e){am(this,chunkDITZCOYN_cjs.d.MEDIA_SUBTITLES_SHOWING,e);}};$s.getSlotTemplateHTML=Ov;$s.getTooltipContentHTML=Fv;var nm=(s,e)=>{let t=s.getAttribute(e);return t?Ki(t):[]},am=(s,e,t)=>{if(!t?.length){s.removeAttribute(e);return}let i=fi(t);s.getAttribute(e)!==i&&s.setAttribute(e,i);};chunkDITZCOYN_cjs.o.customElements.get("media-captions-menu-button")||chunkDITZCOYN_cjs.o.customElements.define("media-captions-menu-button",$s);var om=(s,e,t)=>{if(!e.has(s))throw TypeError("Cannot "+t)},Gs=(s,e,t)=>(om(s,e,"read from private field"),t?t.call(s):e.get(s)),Fd=(s,e,t)=>{if(e.has(s))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(s):e.set(s,t);},en=(s,e,t)=>(om(s,e,"access private method"),t),Ci,tn,ro,no,Ud,Nd={RATES:"rates"},ao=class extends chunkDITZCOYN_cjs.N{constructor(){super(),Fd(this,tn),Fd(this,no),Fd(this,Ci,new Ii(this,Nd.RATES,{defaultValue:sd})),en(this,tn,ro).call(this);}static get observedAttributes(){return [...super.observedAttributes,chunkDITZCOYN_cjs.d.MEDIA_PLAYBACK_RATE,Nd.RATES]}attributeChangedCallback(e,t,i){super.attributeChangedCallback(e,t,i),e===chunkDITZCOYN_cjs.d.MEDIA_PLAYBACK_RATE&&t!=i?this.value=i:e===Nd.RATES&&t!=i&&(Gs(this,Ci).value=i,en(this,tn,ro).call(this));}connectedCallback(){super.connectedCallback(),this.addEventListener("change",en(this,no,Ud));}disconnectedCallback(){super.disconnectedCallback(),this.removeEventListener("change",en(this,no,Ud));}get anchorElement(){return this.anchor!=="auto"?super.anchorElement:chunkDITZCOYN_cjs.t(this).querySelector("media-playback-rate-menu-button")}get rates(){return Gs(this,Ci)}set rates(e){e?Array.isArray(e)?Gs(this,Ci).value=e.join(" "):typeof e=="string"&&(Gs(this,Ci).value=e):Gs(this,Ci).value="",en(this,tn,ro).call(this);}get mediaPlaybackRate(){return chunkDITZCOYN_cjs.D(this,chunkDITZCOYN_cjs.d.MEDIA_PLAYBACK_RATE,Xi)}set mediaPlaybackRate(e){chunkDITZCOYN_cjs.E(this,chunkDITZCOYN_cjs.d.MEDIA_PLAYBACK_RATE,e);}};Ci=new WeakMap;tn=new WeakSet;ro=function(){this.defaultSlot.textContent="";for(let s of Gs(this,Ci)){let e=chunkDITZCOYN_cjs.L({type:"radio",text:this.formatMenuItemText(`${s}x`,s),value:s,checked:this.mediaPlaybackRate===Number(s)});e.prepend(chunkDITZCOYN_cjs.M(this,"checked-indicator")),this.defaultSlot.append(e);}};no=new WeakSet;Ud=function(){if(!this.value)return;let s=new chunkDITZCOYN_cjs.o.CustomEvent(chunkDITZCOYN_cjs.a.MEDIA_PLAYBACK_RATE_REQUEST,{composed:true,bubbles:true,detail:this.value});this.dispatchEvent(s);};chunkDITZCOYN_cjs.o.customElements.get("media-playback-rate-menu")||chunkDITZCOYN_cjs.o.customElements.define("media-playback-rate-menu",ao);var oo=1;function Nv(s){return `
1302
1302
  <style>
1303
1303
  :host {
1304
1304
  min-width: 5ch;
@@ -1310,16 +1310,16 @@
1310
1310
  }
1311
1311
  </style>
1312
1312
  <slot name="icon">${s.mediaplaybackrate||oo}x</slot>
1313
- `}function Nv(){return chunkDITZCOYN_cjs.n("Playback rate")}var Hs=class extends chunkDITZCOYN_cjs.O{static get observedAttributes(){return [...super.observedAttributes,chunkDITZCOYN_cjs.d.MEDIA_PLAYBACK_RATE]}constructor(){var e;super(),this.container=this.shadowRoot.querySelector('slot[name="icon"]'),this.container.innerHTML=`${(e=this.mediaPlaybackRate)!=null?e:oo}x`;}attributeChangedCallback(e,t,i){if(super.attributeChangedCallback(e,t,i),e===chunkDITZCOYN_cjs.d.MEDIA_PLAYBACK_RATE){let r=i?+i:Number.NaN,n=Number.isNaN(r)?oo:r;this.container.innerHTML=`${n}x`,this.setAttribute("aria-label",chunkDITZCOYN_cjs.n("Playback rate {playbackRate}",{playbackRate:n}));}}get invokeTargetElement(){return this.invokeTarget!=null?super.invokeTargetElement:chunkDITZCOYN_cjs.t(this).querySelector("media-playback-rate-menu")}get mediaPlaybackRate(){return chunkDITZCOYN_cjs.D(this,chunkDITZCOYN_cjs.d.MEDIA_PLAYBACK_RATE,oo)}set mediaPlaybackRate(e){chunkDITZCOYN_cjs.E(this,chunkDITZCOYN_cjs.d.MEDIA_PLAYBACK_RATE,e);}};Hs.getSlotTemplateHTML=Fv;Hs.getTooltipContentHTML=Nv;chunkDITZCOYN_cjs.o.customElements.get("media-playback-rate-menu-button")||chunkDITZCOYN_cjs.o.customElements.define("media-playback-rate-menu-button",Hs);var $d=(s,e,t)=>{if(!e.has(s))throw TypeError("Cannot "+t)},sn=(s,e,t)=>($d(s,e,"read from private field"),t?t.call(s):e.get(s)),lo=(s,e,t)=>{if(e.has(s))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(s):e.set(s,t);},om=(s,e,t,i)=>($d(s,e,"write to private field"),e.set(s,t),t),Ks=(s,e,t)=>($d(s,e,"access private method"),t),rn,Ws,Vs,nn,co,Bd,uo=class extends chunkDITZCOYN_cjs.N{constructor(){super(...arguments),lo(this,Vs),lo(this,co),lo(this,rn,[]),lo(this,Ws,{});}static get observedAttributes(){return [...super.observedAttributes,chunkDITZCOYN_cjs.d.MEDIA_RENDITION_LIST,chunkDITZCOYN_cjs.d.MEDIA_RENDITION_SELECTED,chunkDITZCOYN_cjs.d.MEDIA_RENDITION_UNAVAILABLE,chunkDITZCOYN_cjs.d.MEDIA_HEIGHT]}static formatMenuItemText(e,t){return super.formatMenuItemText(e,t)}static formatRendition(e,{showBitrate:t=false}={}){let i=`${Math.min(e.width,e.height)}p`;if(t&&e.bitrate){let r=e.bitrate/1e6,n=`${r.toFixed(r<1?1:0)} Mbps`;return `${i} (${n})`}return this.formatMenuItemText(i,e)}static compareRendition(e,t){var i,r;return t.height===e.height?((i=t.bitrate)!=null?i:0)-((r=e.bitrate)!=null?r:0):t.height-e.height}attributeChangedCallback(e,t,i){super.attributeChangedCallback(e,t,i),e===chunkDITZCOYN_cjs.d.MEDIA_RENDITION_SELECTED&&t!==i?(this.value=i??"auto",Ks(this,Vs,nn).call(this)):e===chunkDITZCOYN_cjs.d.MEDIA_RENDITION_LIST&&t!==i?(om(this,rn,bh(i)),Ks(this,Vs,nn).call(this)):e===chunkDITZCOYN_cjs.d.MEDIA_HEIGHT&&t!==i&&Ks(this,Vs,nn).call(this);}connectedCallback(){super.connectedCallback(),this.addEventListener("change",Ks(this,co,Bd));}disconnectedCallback(){super.disconnectedCallback(),this.removeEventListener("change",Ks(this,co,Bd));}get anchorElement(){return this.anchor!=="auto"?super.anchorElement:chunkDITZCOYN_cjs.t(this).querySelector("media-rendition-menu-button")}get mediaRenditionList(){return sn(this,rn)}set mediaRenditionList(e){om(this,rn,e),Ks(this,Vs,nn).call(this);}get mediaRenditionSelected(){return chunkDITZCOYN_cjs.H(this,chunkDITZCOYN_cjs.d.MEDIA_RENDITION_SELECTED)}set mediaRenditionSelected(e){chunkDITZCOYN_cjs.I(this,chunkDITZCOYN_cjs.d.MEDIA_RENDITION_SELECTED,e);}get mediaHeight(){return chunkDITZCOYN_cjs.D(this,chunkDITZCOYN_cjs.d.MEDIA_HEIGHT)}set mediaHeight(e){chunkDITZCOYN_cjs.E(this,chunkDITZCOYN_cjs.d.MEDIA_HEIGHT,e);}compareRendition(e,t){return this.constructor.compareRendition(e,t)}formatMenuItemText(e,t){return this.constructor.formatMenuItemText(e,t)}formatRendition(e,t){return this.constructor.formatRendition(e,t)}showRenditionBitrate(e){return this.mediaRenditionList.some(t=>t!==e&&t.height===e.height&&t.bitrate!==e.bitrate)}};rn=new WeakMap;Ws=new WeakMap;Vs=new WeakSet;nn=function(){if(sn(this,Ws).mediaRenditionList===JSON.stringify(this.mediaRenditionList)&&sn(this,Ws).mediaHeight===this.mediaHeight)return;sn(this,Ws).mediaRenditionList=JSON.stringify(this.mediaRenditionList),sn(this,Ws).mediaHeight=this.mediaHeight;let s=this.mediaRenditionList.sort(this.compareRendition.bind(this)),e=s.find(a=>a.id===this.mediaRenditionSelected);for(let a of s)a.selected=a===e;this.defaultSlot.textContent="";let t=!this.mediaRenditionSelected;for(let a of s){let o=this.formatRendition(a,{showBitrate:this.showRenditionBitrate(a)}),l=chunkDITZCOYN_cjs.L({type:"radio",text:o,value:`${a.id}`,checked:a.selected&&!t});l.prepend(chunkDITZCOYN_cjs.M(this,"checked-indicator")),this.defaultSlot.append(l);}let i=e&&this.showRenditionBitrate(e),r=t?e?this.formatMenuItemText(`${chunkDITZCOYN_cjs.n("Auto")} \u2022 ${this.formatRendition(e,{showBitrate:i})}`,e):this.formatMenuItemText(`${chunkDITZCOYN_cjs.n("Auto")} (${this.mediaHeight}p)`):this.formatMenuItemText(chunkDITZCOYN_cjs.n("Auto")),n=chunkDITZCOYN_cjs.L({type:"radio",text:r,value:"auto",checked:t});n.dataset.description=r,n.prepend(chunkDITZCOYN_cjs.M(this,"checked-indicator")),this.defaultSlot.append(n);};co=new WeakSet;Bd=function(){if(this.value==null)return;let s=new chunkDITZCOYN_cjs.o.CustomEvent(chunkDITZCOYN_cjs.a.MEDIA_RENDITION_REQUEST,{composed:true,bubbles:true,detail:this.value});this.dispatchEvent(s);};chunkDITZCOYN_cjs.o.customElements.get("media-rendition-menu")||chunkDITZCOYN_cjs.o.customElements.define("media-rendition-menu",uo);var Uv=`<svg aria-hidden="true" viewBox="0 0 24 24">
1313
+ `}function Uv(){return chunkDITZCOYN_cjs.n("Playback rate")}var Hs=class extends chunkDITZCOYN_cjs.O{static get observedAttributes(){return [...super.observedAttributes,chunkDITZCOYN_cjs.d.MEDIA_PLAYBACK_RATE]}constructor(){var e;super(),this.container=this.shadowRoot.querySelector('slot[name="icon"]'),this.container.innerHTML=`${(e=this.mediaPlaybackRate)!=null?e:oo}x`;}attributeChangedCallback(e,t,i){if(super.attributeChangedCallback(e,t,i),e===chunkDITZCOYN_cjs.d.MEDIA_PLAYBACK_RATE){let r=i?+i:Number.NaN,n=Number.isNaN(r)?oo:r;this.container.innerHTML=`${n}x`,this.setAttribute("aria-label",chunkDITZCOYN_cjs.n("Playback rate {playbackRate}",{playbackRate:n}));}}get invokeTargetElement(){return this.invokeTarget!=null?super.invokeTargetElement:chunkDITZCOYN_cjs.t(this).querySelector("media-playback-rate-menu")}get mediaPlaybackRate(){return chunkDITZCOYN_cjs.D(this,chunkDITZCOYN_cjs.d.MEDIA_PLAYBACK_RATE,oo)}set mediaPlaybackRate(e){chunkDITZCOYN_cjs.E(this,chunkDITZCOYN_cjs.d.MEDIA_PLAYBACK_RATE,e);}};Hs.getSlotTemplateHTML=Nv;Hs.getTooltipContentHTML=Uv;chunkDITZCOYN_cjs.o.customElements.get("media-playback-rate-menu-button")||chunkDITZCOYN_cjs.o.customElements.define("media-playback-rate-menu-button",Hs);var $d=(s,e,t)=>{if(!e.has(s))throw TypeError("Cannot "+t)},sn=(s,e,t)=>($d(s,e,"read from private field"),t?t.call(s):e.get(s)),lo=(s,e,t)=>{if(e.has(s))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(s):e.set(s,t);},lm=(s,e,t,i)=>($d(s,e,"write to private field"),e.set(s,t),t),Ks=(s,e,t)=>($d(s,e,"access private method"),t),rn,Ws,Vs,nn,co,Bd,uo=class extends chunkDITZCOYN_cjs.N{constructor(){super(...arguments),lo(this,Vs),lo(this,co),lo(this,rn,[]),lo(this,Ws,{});}static get observedAttributes(){return [...super.observedAttributes,chunkDITZCOYN_cjs.d.MEDIA_RENDITION_LIST,chunkDITZCOYN_cjs.d.MEDIA_RENDITION_SELECTED,chunkDITZCOYN_cjs.d.MEDIA_RENDITION_UNAVAILABLE,chunkDITZCOYN_cjs.d.MEDIA_HEIGHT]}static formatMenuItemText(e,t){return super.formatMenuItemText(e,t)}static formatRendition(e,{showBitrate:t=false}={}){let i=`${Math.min(e.width,e.height)}p`;if(t&&e.bitrate){let r=e.bitrate/1e6,n=`${r.toFixed(r<1?1:0)} Mbps`;return `${i} (${n})`}return this.formatMenuItemText(i,e)}static compareRendition(e,t){var i,r;return t.height===e.height?((i=t.bitrate)!=null?i:0)-((r=e.bitrate)!=null?r:0):t.height-e.height}attributeChangedCallback(e,t,i){super.attributeChangedCallback(e,t,i),e===chunkDITZCOYN_cjs.d.MEDIA_RENDITION_SELECTED&&t!==i?(this.value=i??"auto",Ks(this,Vs,nn).call(this)):e===chunkDITZCOYN_cjs.d.MEDIA_RENDITION_LIST&&t!==i?(lm(this,rn,_h(i)),Ks(this,Vs,nn).call(this)):e===chunkDITZCOYN_cjs.d.MEDIA_HEIGHT&&t!==i&&Ks(this,Vs,nn).call(this);}connectedCallback(){super.connectedCallback(),this.addEventListener("change",Ks(this,co,Bd));}disconnectedCallback(){super.disconnectedCallback(),this.removeEventListener("change",Ks(this,co,Bd));}get anchorElement(){return this.anchor!=="auto"?super.anchorElement:chunkDITZCOYN_cjs.t(this).querySelector("media-rendition-menu-button")}get mediaRenditionList(){return sn(this,rn)}set mediaRenditionList(e){lm(this,rn,e),Ks(this,Vs,nn).call(this);}get mediaRenditionSelected(){return chunkDITZCOYN_cjs.H(this,chunkDITZCOYN_cjs.d.MEDIA_RENDITION_SELECTED)}set mediaRenditionSelected(e){chunkDITZCOYN_cjs.I(this,chunkDITZCOYN_cjs.d.MEDIA_RENDITION_SELECTED,e);}get mediaHeight(){return chunkDITZCOYN_cjs.D(this,chunkDITZCOYN_cjs.d.MEDIA_HEIGHT)}set mediaHeight(e){chunkDITZCOYN_cjs.E(this,chunkDITZCOYN_cjs.d.MEDIA_HEIGHT,e);}compareRendition(e,t){return this.constructor.compareRendition(e,t)}formatMenuItemText(e,t){return this.constructor.formatMenuItemText(e,t)}formatRendition(e,t){return this.constructor.formatRendition(e,t)}showRenditionBitrate(e){return this.mediaRenditionList.some(t=>t!==e&&t.height===e.height&&t.bitrate!==e.bitrate)}};rn=new WeakMap;Ws=new WeakMap;Vs=new WeakSet;nn=function(){if(sn(this,Ws).mediaRenditionList===JSON.stringify(this.mediaRenditionList)&&sn(this,Ws).mediaHeight===this.mediaHeight)return;sn(this,Ws).mediaRenditionList=JSON.stringify(this.mediaRenditionList),sn(this,Ws).mediaHeight=this.mediaHeight;let s=this.mediaRenditionList.sort(this.compareRendition.bind(this)),e=s.find(a=>a.id===this.mediaRenditionSelected);for(let a of s)a.selected=a===e;this.defaultSlot.textContent="";let t=!this.mediaRenditionSelected;for(let a of s){let o=this.formatRendition(a,{showBitrate:this.showRenditionBitrate(a)}),l=chunkDITZCOYN_cjs.L({type:"radio",text:o,value:`${a.id}`,checked:a.selected&&!t});l.prepend(chunkDITZCOYN_cjs.M(this,"checked-indicator")),this.defaultSlot.append(l);}let i=e&&this.showRenditionBitrate(e),r=t?e?this.formatMenuItemText(`${chunkDITZCOYN_cjs.n("Auto")} \u2022 ${this.formatRendition(e,{showBitrate:i})}`,e):this.formatMenuItemText(`${chunkDITZCOYN_cjs.n("Auto")} (${this.mediaHeight}p)`):this.formatMenuItemText(chunkDITZCOYN_cjs.n("Auto")),n=chunkDITZCOYN_cjs.L({type:"radio",text:r,value:"auto",checked:t});n.dataset.description=r,n.prepend(chunkDITZCOYN_cjs.M(this,"checked-indicator")),this.defaultSlot.append(n);};co=new WeakSet;Bd=function(){if(this.value==null)return;let s=new chunkDITZCOYN_cjs.o.CustomEvent(chunkDITZCOYN_cjs.a.MEDIA_RENDITION_REQUEST,{composed:true,bubbles:true,detail:this.value});this.dispatchEvent(s);};chunkDITZCOYN_cjs.o.customElements.get("media-rendition-menu")||chunkDITZCOYN_cjs.o.customElements.define("media-rendition-menu",uo);var Bv=`<svg aria-hidden="true" viewBox="0 0 24 24">
1314
1314
  <path d="M13.5 2.5h2v6h-2v-2h-11v-2h11v-2Zm4 2h4v2h-4v-2Zm-12 4h2v6h-2v-2h-3v-2h3v-2Zm4 2h12v2h-12v-2Zm1 4h2v6h-2v-2h-8v-2h8v-2Zm4 2h7v2h-7v-2Z" />
1315
- </svg>`;function Bv(){return `
1315
+ </svg>`;function $v(){return `
1316
1316
  <style>
1317
1317
  :host([aria-expanded="true"]) slot[name=tooltip] {
1318
1318
  display: none;
1319
1319
  }
1320
1320
  </style>
1321
- <slot name="icon">${Uv}</slot>
1322
- `}function $v(){return chunkDITZCOYN_cjs.n("Quality")}var Ys=class extends chunkDITZCOYN_cjs.O{static get observedAttributes(){return [...super.observedAttributes,chunkDITZCOYN_cjs.d.MEDIA_RENDITION_SELECTED,chunkDITZCOYN_cjs.d.MEDIA_RENDITION_UNAVAILABLE,chunkDITZCOYN_cjs.d.MEDIA_HEIGHT]}connectedCallback(){super.connectedCallback(),this.setAttribute("aria-label",chunkDITZCOYN_cjs.n("quality"));}get invokeTargetElement(){return this.invokeTarget!=null?super.invokeTargetElement:chunkDITZCOYN_cjs.t(this).querySelector("media-rendition-menu")}get mediaRenditionSelected(){return chunkDITZCOYN_cjs.H(this,chunkDITZCOYN_cjs.d.MEDIA_RENDITION_SELECTED)}set mediaRenditionSelected(e){chunkDITZCOYN_cjs.I(this,chunkDITZCOYN_cjs.d.MEDIA_RENDITION_SELECTED,e);}get mediaHeight(){return chunkDITZCOYN_cjs.D(this,chunkDITZCOYN_cjs.d.MEDIA_HEIGHT)}set mediaHeight(e){chunkDITZCOYN_cjs.E(this,chunkDITZCOYN_cjs.d.MEDIA_HEIGHT,e);}};Ys.getSlotTemplateHTML=Bv;Ys.getTooltipContentHTML=$v;chunkDITZCOYN_cjs.o.customElements.get("media-rendition-menu-button")||chunkDITZCOYN_cjs.o.customElements.define("media-rendition-menu-button",Ys);var Kd=(s,e,t)=>{if(!e.has(s))throw TypeError("Cannot "+t)},ri=(s,e,t)=>(Kd(s,e,"read from private field"),t?t.call(s):e.get(s)),si=(s,e,t)=>{if(e.has(s))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(s):e.set(s,t);},lm=(s,e,t,i)=>(Kd(s,e,"write to private field"),e.set(s,t),t),kt=(s,e,t)=>(Kd(s,e,"access private method"),t),js,an,Eo,is,qs,Vd,dm,ho,Gd,fo,Hd,cm,go,po,mo;function Gv(s){return `
1321
+ <slot name="icon">${Bv}</slot>
1322
+ `}function Gv(){return chunkDITZCOYN_cjs.n("Quality")}var Ys=class extends chunkDITZCOYN_cjs.O{static get observedAttributes(){return [...super.observedAttributes,chunkDITZCOYN_cjs.d.MEDIA_RENDITION_SELECTED,chunkDITZCOYN_cjs.d.MEDIA_RENDITION_UNAVAILABLE,chunkDITZCOYN_cjs.d.MEDIA_HEIGHT]}connectedCallback(){super.connectedCallback(),this.setAttribute("aria-label",chunkDITZCOYN_cjs.n("quality"));}get invokeTargetElement(){return this.invokeTarget!=null?super.invokeTargetElement:chunkDITZCOYN_cjs.t(this).querySelector("media-rendition-menu")}get mediaRenditionSelected(){return chunkDITZCOYN_cjs.H(this,chunkDITZCOYN_cjs.d.MEDIA_RENDITION_SELECTED)}set mediaRenditionSelected(e){chunkDITZCOYN_cjs.I(this,chunkDITZCOYN_cjs.d.MEDIA_RENDITION_SELECTED,e);}get mediaHeight(){return chunkDITZCOYN_cjs.D(this,chunkDITZCOYN_cjs.d.MEDIA_HEIGHT)}set mediaHeight(e){chunkDITZCOYN_cjs.E(this,chunkDITZCOYN_cjs.d.MEDIA_HEIGHT,e);}};Ys.getSlotTemplateHTML=$v;Ys.getTooltipContentHTML=Gv;chunkDITZCOYN_cjs.o.customElements.get("media-rendition-menu-button")||chunkDITZCOYN_cjs.o.customElements.define("media-rendition-menu-button",Ys);var Kd=(s,e,t)=>{if(!e.has(s))throw TypeError("Cannot "+t)},ri=(s,e,t)=>(Kd(s,e,"read from private field"),t?t.call(s):e.get(s)),si=(s,e,t)=>{if(e.has(s))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(s):e.set(s,t);},dm=(s,e,t,i)=>(Kd(s,e,"write to private field"),e.set(s,t),t),kt=(s,e,t)=>(Kd(s,e,"access private method"),t),js,an,Eo,is,qs,Vd,cm,ho,Gd,fo,Hd,um,go,po,mo;function Hv(s){return `
1323
1323
  ${chunkDITZCOYN_cjs.N.getTemplateHTML(s)}
1324
1324
  <style>
1325
1325
  :host {
@@ -1333,7 +1333,7 @@
1333
1333
  overflow: hidden;
1334
1334
  }
1335
1335
  </style>
1336
- `}var on=class extends chunkDITZCOYN_cjs.N{constructor(){super(),si(this,an),si(this,is),si(this,Vd),si(this,ho),si(this,Hd),si(this,js,false),si(this,fo,e=>{let t=e.target,i=t?.nodeName==="VIDEO",r=kt(this,ho,Gd).call(this,t);(i||r)&&(ri(this,js)?kt(this,is,qs).call(this):kt(this,Hd,cm).call(this,e));}),si(this,go,e=>{let t=e.target,i=this.contains(t),r=e.button===2,n=t?.nodeName==="VIDEO",a=kt(this,ho,Gd).call(this,t);i||r&&(n||a)||kt(this,is,qs).call(this);}),si(this,po,e=>{e.key==="Escape"&&kt(this,is,qs).call(this);}),si(this,mo,e=>{var t,i;let r=e.target;if((t=r.matches)!=null&&t.call(r,'button[invoke="copy"]')){let n=(i=r.closest("media-context-menu-item"))==null?void 0:i.querySelector('input[slot="copy"]');n&&navigator.clipboard.writeText(n.value);}kt(this,is,qs).call(this);}),this.setAttribute("noautohide",""),kt(this,an,Eo).call(this);}connectedCallback(){super.connectedCallback(),chunkDITZCOYN_cjs.t(this).addEventListener("contextmenu",ri(this,fo)),this.addEventListener("click",ri(this,mo));}disconnectedCallback(){super.disconnectedCallback(),chunkDITZCOYN_cjs.t(this).removeEventListener("contextmenu",ri(this,fo)),this.removeEventListener("click",ri(this,mo)),document.removeEventListener("mousedown",ri(this,go)),document.removeEventListener("keydown",ri(this,po));}};js=new WeakMap;an=new WeakSet;Eo=function(){this.hidden=!ri(this,js);};is=new WeakSet;qs=function(){lm(this,js,false),kt(this,an,Eo).call(this);};Vd=new WeakSet;dm=function(){document.querySelectorAll("media-context-menu").forEach(e=>{var t;e!==this&&kt(t=e,is,qs).call(t);});};ho=new WeakSet;Gd=function(s){return s?s.hasAttribute("slot")&&s.getAttribute("slot")==="media"?true:s.nodeName.includes("-")&&s.tagName.includes("-")?s.hasAttribute("src")||s.hasAttribute("poster")||s.hasAttribute("preload")||s.hasAttribute("playsinline"):false:false};fo=new WeakMap;Hd=new WeakSet;cm=function(s){s.preventDefault(),kt(this,Vd,dm).call(this),lm(this,js,true),this.style.position="fixed",this.style.left=`${s.clientX}px`,this.style.top=`${s.clientY}px`,kt(this,an,Eo).call(this),document.addEventListener("mousedown",ri(this,go),{once:true}),document.addEventListener("keydown",ri(this,po),{once:true});};go=new WeakMap;po=new WeakMap;mo=new WeakMap;on.getTemplateHTML=Gv;chunkDITZCOYN_cjs.o.customElements.get("media-context-menu")||chunkDITZCOYN_cjs.o.customElements.define("media-context-menu",on);function Hv(s){return `
1336
+ `}var on=class extends chunkDITZCOYN_cjs.N{constructor(){super(),si(this,an),si(this,is),si(this,Vd),si(this,ho),si(this,Hd),si(this,js,false),si(this,fo,e=>{let t=e.target,i=t?.nodeName==="VIDEO",r=kt(this,ho,Gd).call(this,t);(i||r)&&(ri(this,js)?kt(this,is,qs).call(this):kt(this,Hd,um).call(this,e));}),si(this,go,e=>{let t=e.target,i=this.contains(t),r=e.button===2,n=t?.nodeName==="VIDEO",a=kt(this,ho,Gd).call(this,t);i||r&&(n||a)||kt(this,is,qs).call(this);}),si(this,po,e=>{e.key==="Escape"&&kt(this,is,qs).call(this);}),si(this,mo,e=>{var t,i;let r=e.target;if((t=r.matches)!=null&&t.call(r,'button[invoke="copy"]')){let n=(i=r.closest("media-context-menu-item"))==null?void 0:i.querySelector('input[slot="copy"]');n&&navigator.clipboard.writeText(n.value);}kt(this,is,qs).call(this);}),this.setAttribute("noautohide",""),kt(this,an,Eo).call(this);}connectedCallback(){super.connectedCallback(),chunkDITZCOYN_cjs.t(this).addEventListener("contextmenu",ri(this,fo)),this.addEventListener("click",ri(this,mo));}disconnectedCallback(){super.disconnectedCallback(),chunkDITZCOYN_cjs.t(this).removeEventListener("contextmenu",ri(this,fo)),this.removeEventListener("click",ri(this,mo)),document.removeEventListener("mousedown",ri(this,go)),document.removeEventListener("keydown",ri(this,po));}};js=new WeakMap;an=new WeakSet;Eo=function(){this.hidden=!ri(this,js);};is=new WeakSet;qs=function(){dm(this,js,false),kt(this,an,Eo).call(this);};Vd=new WeakSet;cm=function(){document.querySelectorAll("media-context-menu").forEach(e=>{var t;e!==this&&kt(t=e,is,qs).call(t);});};ho=new WeakSet;Gd=function(s){return s?s.hasAttribute("slot")&&s.getAttribute("slot")==="media"?true:s.nodeName.includes("-")&&s.tagName.includes("-")?s.hasAttribute("src")||s.hasAttribute("poster")||s.hasAttribute("preload")||s.hasAttribute("playsinline"):false:false};fo=new WeakMap;Hd=new WeakSet;um=function(s){s.preventDefault(),kt(this,Vd,cm).call(this),dm(this,js,true),this.style.position="fixed",this.style.left=`${s.clientX}px`,this.style.top=`${s.clientY}px`,kt(this,an,Eo).call(this),document.addEventListener("mousedown",ri(this,go),{once:true}),document.addEventListener("keydown",ri(this,po),{once:true});};go=new WeakMap;po=new WeakMap;mo=new WeakMap;on.getTemplateHTML=Hv;chunkDITZCOYN_cjs.o.customElements.get("media-context-menu")||chunkDITZCOYN_cjs.o.customElements.define("media-context-menu",on);function Kv(s){return `
1337
1337
  ${Tt.getTemplateHTML.call(this,s)}
1338
1338
  <style>
1339
1339
  ::slotted(*) {
@@ -1346,71 +1346,71 @@
1346
1346
  min-height: var(--media-control-height, 24px);
1347
1347
  }
1348
1348
  </style>
1349
- `}var zs=class extends Tt{};zs.shadowRootOptions={mode:"open"};zs.getTemplateHTML=Hv;chunkDITZCOYN_cjs.o.customElements.get("media-context-menu-item")||chunkDITZCOYN_cjs.o.customElements.define("media-context-menu-item",zs);var xn=chunkJHSFSCC2_cjs.b(chunkKVMGCTLR_cjs.b(),1);var G=Number.isFinite||function(s){return typeof s=="number"&&isFinite(s)},Kv=Number.isSafeInteger||function(s){return typeof s=="number"&&Math.abs(s)<=Vv},Vv=Number.MAX_SAFE_INTEGER||9007199254740991,z=function(s){return s.NETWORK_ERROR="networkError",s.MEDIA_ERROR="mediaError",s.KEY_SYSTEM_ERROR="keySystemError",s.MUX_ERROR="muxError",s.OTHER_ERROR="otherError",s}({}),x=function(s){return s.KEY_SYSTEM_NO_KEYS="keySystemNoKeys",s.KEY_SYSTEM_NO_ACCESS="keySystemNoAccess",s.KEY_SYSTEM_NO_SESSION="keySystemNoSession",s.KEY_SYSTEM_NO_CONFIGURED_LICENSE="keySystemNoConfiguredLicense",s.KEY_SYSTEM_LICENSE_REQUEST_FAILED="keySystemLicenseRequestFailed",s.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED="keySystemServerCertificateRequestFailed",s.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED="keySystemServerCertificateUpdateFailed",s.KEY_SYSTEM_SESSION_UPDATE_FAILED="keySystemSessionUpdateFailed",s.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED="keySystemStatusOutputRestricted",s.KEY_SYSTEM_STATUS_INTERNAL_ERROR="keySystemStatusInternalError",s.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR="keySystemDestroyMediaKeysError",s.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR="keySystemDestroyCloseSessionError",s.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR="keySystemDestroyRemoveSessionError",s.MANIFEST_LOAD_ERROR="manifestLoadError",s.MANIFEST_LOAD_TIMEOUT="manifestLoadTimeOut",s.MANIFEST_PARSING_ERROR="manifestParsingError",s.MANIFEST_INCOMPATIBLE_CODECS_ERROR="manifestIncompatibleCodecsError",s.LEVEL_EMPTY_ERROR="levelEmptyError",s.LEVEL_LOAD_ERROR="levelLoadError",s.LEVEL_LOAD_TIMEOUT="levelLoadTimeOut",s.LEVEL_PARSING_ERROR="levelParsingError",s.LEVEL_SWITCH_ERROR="levelSwitchError",s.AUDIO_TRACK_LOAD_ERROR="audioTrackLoadError",s.AUDIO_TRACK_LOAD_TIMEOUT="audioTrackLoadTimeOut",s.SUBTITLE_LOAD_ERROR="subtitleTrackLoadError",s.SUBTITLE_TRACK_LOAD_TIMEOUT="subtitleTrackLoadTimeOut",s.FRAG_LOAD_ERROR="fragLoadError",s.FRAG_LOAD_TIMEOUT="fragLoadTimeOut",s.FRAG_DECRYPT_ERROR="fragDecryptError",s.FRAG_PARSING_ERROR="fragParsingError",s.FRAG_GAP="fragGap",s.REMUX_ALLOC_ERROR="remuxAllocError",s.KEY_LOAD_ERROR="keyLoadError",s.KEY_LOAD_TIMEOUT="keyLoadTimeOut",s.BUFFER_ADD_CODEC_ERROR="bufferAddCodecError",s.BUFFER_INCOMPATIBLE_CODECS_ERROR="bufferIncompatibleCodecsError",s.BUFFER_APPEND_ERROR="bufferAppendError",s.BUFFER_APPENDING_ERROR="bufferAppendingError",s.BUFFER_STALLED_ERROR="bufferStalledError",s.BUFFER_FULL_ERROR="bufferFullError",s.BUFFER_SEEK_OVER_HOLE="bufferSeekOverHole",s.BUFFER_NUDGE_ON_STALL="bufferNudgeOnStall",s.ASSET_LIST_LOAD_ERROR="assetListLoadError",s.ASSET_LIST_LOAD_TIMEOUT="assetListLoadTimeout",s.ASSET_LIST_PARSING_ERROR="assetListParsingError",s.INTERSTITIAL_ASSET_ITEM_ERROR="interstitialAssetItemError",s.INTERNAL_EXCEPTION="internalException",s.INTERNAL_ABORTED="aborted",s.ATTACH_MEDIA_ERROR="attachMediaError",s.UNKNOWN="unknown",s}({}),g=function(s){return s.MEDIA_ATTACHING="hlsMediaAttaching",s.MEDIA_ATTACHED="hlsMediaAttached",s.MEDIA_DETACHING="hlsMediaDetaching",s.MEDIA_DETACHED="hlsMediaDetached",s.MEDIA_ENDED="hlsMediaEnded",s.STALL_RESOLVED="hlsStallResolved",s.BUFFER_RESET="hlsBufferReset",s.BUFFER_CODECS="hlsBufferCodecs",s.BUFFER_CREATED="hlsBufferCreated",s.BUFFER_APPENDING="hlsBufferAppending",s.BUFFER_APPENDED="hlsBufferAppended",s.BUFFER_EOS="hlsBufferEos",s.BUFFERED_TO_END="hlsBufferedToEnd",s.BUFFER_FLUSHING="hlsBufferFlushing",s.BUFFER_FLUSHED="hlsBufferFlushed",s.MANIFEST_LOADING="hlsManifestLoading",s.MANIFEST_LOADED="hlsManifestLoaded",s.MANIFEST_PARSED="hlsManifestParsed",s.LEVEL_SWITCHING="hlsLevelSwitching",s.LEVEL_SWITCHED="hlsLevelSwitched",s.LEVEL_LOADING="hlsLevelLoading",s.LEVEL_LOADED="hlsLevelLoaded",s.LEVEL_UPDATED="hlsLevelUpdated",s.LEVEL_PTS_UPDATED="hlsLevelPtsUpdated",s.LEVELS_UPDATED="hlsLevelsUpdated",s.AUDIO_TRACKS_UPDATED="hlsAudioTracksUpdated",s.AUDIO_TRACK_SWITCHING="hlsAudioTrackSwitching",s.AUDIO_TRACK_SWITCHED="hlsAudioTrackSwitched",s.AUDIO_TRACK_LOADING="hlsAudioTrackLoading",s.AUDIO_TRACK_LOADED="hlsAudioTrackLoaded",s.AUDIO_TRACK_UPDATED="hlsAudioTrackUpdated",s.SUBTITLE_TRACKS_UPDATED="hlsSubtitleTracksUpdated",s.SUBTITLE_TRACKS_CLEARED="hlsSubtitleTracksCleared",s.SUBTITLE_TRACK_SWITCH="hlsSubtitleTrackSwitch",s.SUBTITLE_TRACK_LOADING="hlsSubtitleTrackLoading",s.SUBTITLE_TRACK_LOADED="hlsSubtitleTrackLoaded",s.SUBTITLE_TRACK_UPDATED="hlsSubtitleTrackUpdated",s.SUBTITLE_FRAG_PROCESSED="hlsSubtitleFragProcessed",s.CUES_PARSED="hlsCuesParsed",s.NON_NATIVE_TEXT_TRACKS_FOUND="hlsNonNativeTextTracksFound",s.INIT_PTS_FOUND="hlsInitPtsFound",s.FRAG_LOADING="hlsFragLoading",s.FRAG_LOAD_EMERGENCY_ABORTED="hlsFragLoadEmergencyAborted",s.FRAG_LOADED="hlsFragLoaded",s.FRAG_DECRYPTED="hlsFragDecrypted",s.FRAG_PARSING_INIT_SEGMENT="hlsFragParsingInitSegment",s.FRAG_PARSING_USERDATA="hlsFragParsingUserdata",s.FRAG_PARSING_METADATA="hlsFragParsingMetadata",s.FRAG_PARSED="hlsFragParsed",s.FRAG_BUFFERED="hlsFragBuffered",s.FRAG_CHANGED="hlsFragChanged",s.FPS_DROP="hlsFpsDrop",s.FPS_DROP_LEVEL_CAPPING="hlsFpsDropLevelCapping",s.MAX_AUTO_LEVEL_UPDATED="hlsMaxAutoLevelUpdated",s.ERROR="hlsError",s.DESTROYING="hlsDestroying",s.KEY_LOADING="hlsKeyLoading",s.KEY_LOADED="hlsKeyLoaded",s.LIVE_BACK_BUFFER_REACHED="hlsLiveBackBufferReached",s.BACK_BUFFER_REACHED="hlsBackBufferReached",s.STEERING_MANIFEST_LOADED="hlsSteeringManifestLoaded",s.ASSET_LIST_LOADING="hlsAssetListLoading",s.ASSET_LIST_LOADED="hlsAssetListLoaded",s.INTERSTITIALS_UPDATED="hlsInterstitialsUpdated",s.INTERSTITIALS_BUFFERED_TO_BOUNDARY="hlsInterstitialsBufferedToBoundary",s.INTERSTITIAL_ASSET_PLAYER_CREATED="hlsInterstitialAssetPlayerCreated",s.INTERSTITIAL_STARTED="hlsInterstitialStarted",s.INTERSTITIAL_ASSET_STARTED="hlsInterstitialAssetStarted",s.INTERSTITIAL_ASSET_ENDED="hlsInterstitialAssetEnded",s.INTERSTITIAL_ASSET_ERROR="hlsInterstitialAssetError",s.INTERSTITIAL_ENDED="hlsInterstitialEnded",s.INTERSTITIALS_PRIMARY_RESUMED="hlsInterstitialsPrimaryResumed",s.PLAYOUT_LIMIT_REACHED="hlsPlayoutLimitReached",s.EVENT_CUE_ENTER="hlsEventCueEnter",s}({}),ce={MANIFEST:"manifest",LEVEL:"level",AUDIO_TRACK:"audioTrack",SUBTITLE_TRACK:"subtitleTrack"},W={MAIN:"main",AUDIO:"audio",SUBTITLE:"subtitle"},wi=class{constructor(e,t=0,i=0){this.halfLife=void 0,this.alpha_=void 0,this.estimate_=void 0,this.totalWeight_=void 0,this.halfLife=e,this.alpha_=e?Math.exp(Math.log(.5)/e):0,this.estimate_=t,this.totalWeight_=i;}sample(e,t){let i=Math.pow(this.alpha_,e);this.estimate_=t*(1-i)+i*this.estimate_,this.totalWeight_+=e;}getTotalWeight(){return this.totalWeight_}getEstimate(){if(this.alpha_){let e=1-Math.pow(this.alpha_,this.totalWeight_);if(e)return this.estimate_/e}return this.estimate_}},fc=class{constructor(e,t,i,r=100){this.defaultEstimate_=void 0,this.minWeight_=void 0,this.minDelayMs_=void 0,this.slow_=void 0,this.fast_=void 0,this.defaultTTFB_=void 0,this.ttfb_=void 0,this.defaultEstimate_=i,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new wi(e),this.fast_=new wi(t),this.defaultTTFB_=r,this.ttfb_=new wi(e);}update(e,t){let{slow_:i,fast_:r,ttfb_:n}=this;i.halfLife!==e&&(this.slow_=new wi(e,i.getEstimate(),i.getTotalWeight())),r.halfLife!==t&&(this.fast_=new wi(t,r.getEstimate(),r.getTotalWeight())),n.halfLife!==e&&(this.ttfb_=new wi(e,n.getEstimate(),n.getTotalWeight()));}sample(e,t){e=Math.max(e,this.minDelayMs_);let i=8*t,r=e/1e3,n=i/r;this.fast_.sample(r,n),this.slow_.sample(r,n);}sampleTTFB(e){let t=e/1e3,i=Math.sqrt(2)*Math.exp(-Math.pow(t,2)/2);this.ttfb_.sample(i,Math.max(e,5));}canEstimate(){return this.fast_.getTotalWeight()>=this.minWeight_}getEstimate(){return this.canEstimate()?Math.min(this.fast_.getEstimate(),this.slow_.getEstimate()):this.defaultEstimate_}getEstimateTTFB(){return this.ttfb_.getTotalWeight()>=this.minWeight_?this.ttfb_.getEstimate():this.defaultTTFB_}get defaultEstimate(){return this.defaultEstimate_}destroy(){}};function Wv(s,e,t){return (e=qv(e))in s?Object.defineProperty(s,e,{value:t,enumerable:true,configurable:true,writable:true}):s[e]=t,s}function ye(){return ye=Object.assign?Object.assign.bind():function(s){for(var e=1;e<arguments.length;e++){var t=arguments[e];for(var i in t)({}).hasOwnProperty.call(t,i)&&(s[i]=t[i]);}return s},ye.apply(null,arguments)}function um(s,e){var t=Object.keys(s);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(s);e&&(i=i.filter(function(r){return Object.getOwnPropertyDescriptor(s,r).enumerable})),t.push.apply(t,i);}return t}function ve(s){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?um(Object(t),true).forEach(function(i){Wv(s,i,t[i]);}):Object.getOwnPropertyDescriptors?Object.defineProperties(s,Object.getOwnPropertyDescriptors(t)):um(Object(t)).forEach(function(i){Object.defineProperty(s,i,Object.getOwnPropertyDescriptor(t,i));});}return s}function Yv(s,e){if(typeof s!="object"||!s)return s;var t=s[Symbol.toPrimitive];if(t!==void 0){var i=t.call(s,e);if(typeof i!="object")return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return (e==="string"?String:Number)(s)}function qv(s){var e=Yv(s,"string");return typeof e=="symbol"?e:e+""}var ht=class{constructor(e,t){this.trace=void 0,this.debug=void 0,this.log=void 0,this.warn=void 0,this.info=void 0,this.error=void 0;let i=`[${e}]:`;this.trace=Oi,this.debug=t.debug.bind(null,i),this.log=t.log.bind(null,i),this.warn=t.warn.bind(null,i),this.info=t.info.bind(null,i),this.error=t.error.bind(null,i);}},Oi=function(){},jv={trace:Oi,debug:Oi,log:Oi,warn:Oi,info:Oi,error:Oi};function mc(){return ye({},jv)}function zv(s,e){let t=self.console[s];return t?t.bind(self.console,`${e?"["+e+"] ":""}[${s}] >`):Oi}function hm(s,e,t){return e[s]?e[s].bind(e):zv(s,t)}var gc=mc();function Qv(s,e,t){let i=mc();if(typeof console=="object"&&s===true||typeof s=="object"){let r=["debug","log","info","warn","error"];r.forEach(n=>{i[n]=hm(n,s,t);});try{i.log(`Debug logs enabled for "${e}" in hls.js version 1.6.13`);}catch{return mc()}r.forEach(n=>{gc[n]=hm(n,s);});}else ye(gc,i);return i}var Te=gc;function Fi(s=true){return typeof self>"u"?void 0:(s||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function Xv(s){return typeof self<"u"&&s===self.ManagedMediaSource}function bg(s,e){let t=Object.keys(s),i=Object.keys(e),r=t.length,n=i.length;return !r||!n||r===n&&!t.some(a=>i.indexOf(a)===-1)}function bt(s,e=false){if(typeof TextDecoder<"u"){let d=new TextDecoder("utf-8").decode(s);if(e){let c=d.indexOf("\0");return c!==-1?d.substring(0,c):d}return d.replace(/\0/g,"")}let t=s.length,i,r,n,a="",o=0;for(;o<t;){if(i=s[o++],i===0&&e)return a;if(i===0||i===3)continue;switch(i>>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:a+=String.fromCharCode(i);break;case 12:case 13:r=s[o++],a+=String.fromCharCode((i&31)<<6|r&63);break;case 14:r=s[o++],n=s[o++],a+=String.fromCharCode((i&15)<<12|(r&63)<<6|(n&63)<<0);break}}return a}function rt(s){let e="";for(let t=0;t<s.length;t++){let i=s[t].toString(16);i.length<2&&(i="0"+i),e+=i;}return e}function _g(s){return Uint8Array.from(s.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer}function Zv(s){return s&&s.__esModule&&Object.prototype.hasOwnProperty.call(s,"default")?s.default:s}var Wd={exports:{}},fm;function Jv(){return fm||(fm=1,function(s,e){(function(t){var i=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,r=/^(?=([^\/?#]*))\1([^]*)$/,n=/(?:\/|^)\.(?=\/)/g,a=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,o={buildAbsoluteURL:function(l,d,c){if(c=c||{},l=l.trim(),d=d.trim(),!d){if(!c.alwaysNormalize)return l;var u=o.parseURL(l);if(!u)throw new Error("Error trying to parse base URL.");return u.path=o.normalizePath(u.path),o.buildURLFromParts(u)}var h=o.parseURL(d);if(!h)throw new Error("Error trying to parse relative URL.");if(h.scheme)return c.alwaysNormalize?(h.path=o.normalizePath(h.path),o.buildURLFromParts(h)):d;var f=o.parseURL(l);if(!f)throw new Error("Error trying to parse base URL.");if(!f.netLoc&&f.path&&f.path[0]!=="/"){var m=r.exec(f.path);f.netLoc=m[1],f.path=m[2];}f.netLoc&&!f.path&&(f.path="/");var p={scheme:f.scheme,netLoc:h.netLoc,path:null,params:h.params,query:h.query,fragment:h.fragment};if(!h.netLoc&&(p.netLoc=f.netLoc,h.path[0]!=="/"))if(!h.path)p.path=f.path,h.params||(p.params=f.params,h.query||(p.query=f.query));else {var E=f.path,v=E.substring(0,E.lastIndexOf("/")+1)+h.path;p.path=o.normalizePath(v);}return p.path===null&&(p.path=c.alwaysNormalize?o.normalizePath(h.path):h.path),o.buildURLFromParts(p)},parseURL:function(l){var d=i.exec(l);return d?{scheme:d[1]||"",netLoc:d[2]||"",path:d[3]||"",params:d[4]||"",query:d[5]||"",fragment:d[6]||""}:null},normalizePath:function(l){for(l=l.split("").reverse().join("").replace(n,"");l.length!==(l=l.replace(a,"")).length;);return l.split("").reverse().join("")},buildURLFromParts:function(l){return l.scheme+l.netLoc+l.path+l.params+l.query+l.fragment}};s.exports=o;})();}(Wd)),Wd.exports}var Mu=Jv(),mn=class{constructor(){this.aborted=false,this.loaded=0,this.retry=0,this.total=0,this.chunkCount=0,this.bwEstimate=0,this.loading={start:0,first:0,end:0},this.parsing={start:0,end:0},this.buffering={start:0,first:0,end:0};}},Se={AUDIO:"audio",VIDEO:"video",AUDIOVIDEO:"audiovideo"},$o=class{constructor(e){this._byteRange=null,this._url=null,this._stats=null,this._streams=null,this.base=void 0,this.relurl=void 0,typeof e=="string"&&(e={url:e}),this.base=e,eT(this,"stats");}setByteRange(e,t){let i=e.split("@",2),r;i.length===1?r=t?.byteRangeEndOffset||0:r=parseInt(i[1]),this._byteRange=[r,parseInt(i[0])+r];}get baseurl(){return this.base.url}get byteRange(){return this._byteRange===null?[]:this._byteRange}get byteRangeStartOffset(){return this.byteRange[0]}get byteRangeEndOffset(){return this.byteRange[1]}get elementaryStreams(){return this._streams===null&&(this._streams={[Se.AUDIO]:null,[Se.VIDEO]:null,[Se.AUDIOVIDEO]:null}),this._streams}set elementaryStreams(e){this._streams=e;}get hasStats(){return this._stats!==null}get hasStreams(){return this._streams!==null}get stats(){return this._stats===null&&(this._stats=new mn),this._stats}set stats(e){this._stats=e;}get url(){return !this._url&&this.baseurl&&this.relurl&&(this._url=Mu.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:true})),this._url||""}set url(e){this._url=e;}clearElementaryStreamInfo(){let{elementaryStreams:e}=this;e[Se.AUDIO]=null,e[Se.VIDEO]=null,e[Se.AUDIOVIDEO]=null;}};function Ue(s){return s.sn!=="initSegment"}var cn=class extends $o{constructor(e,t){super(t),this._decryptdata=null,this._programDateTime=null,this._ref=null,this._bitrate=void 0,this.rawProgramDateTime=null,this.tagList=[],this.duration=0,this.sn=0,this.levelkeys=void 0,this.type=void 0,this.loader=null,this.keyLoader=null,this.level=-1,this.cc=0,this.startPTS=void 0,this.endPTS=void 0,this.startDTS=void 0,this.endDTS=void 0,this.start=0,this.playlistOffset=0,this.deltaPTS=void 0,this.maxStartPTS=void 0,this.minEndPTS=void 0,this.data=void 0,this.bitrateTest=false,this.title=null,this.initSegment=null,this.endList=void 0,this.gap=void 0,this.urlId=0,this.type=e;}get byteLength(){if(this.hasStats){let e=this.stats.total;if(e)return e}if(this.byteRange.length){let e=this.byteRange[0],t=this.byteRange[1];if(G(e)&&G(t))return t-e}return null}get bitrate(){return this.byteLength?this.byteLength*8/this.duration:this._bitrate?this._bitrate:null}set bitrate(e){this._bitrate=e;}get decryptdata(){var e;let{levelkeys:t}=this;if(!t||t.NONE)return null;if(t.identity)this._decryptdata||(this._decryptdata=t.identity.getDecryptData(this.sn));else if(!((e=this._decryptdata)!=null&&e.keyId)){let i=Object.keys(t);if(i.length===1){let r=this._decryptdata=t[i[0]]||null;r&&(this._decryptdata=r.getDecryptData(this.sn,t));}}return this._decryptdata}get end(){return this.start+this.duration}get endProgramDateTime(){if(this.programDateTime===null)return null;let e=G(this.duration)?this.duration:0;return this.programDateTime+e*1e3}get encrypted(){var e;if((e=this._decryptdata)!=null&&e.encrypted)return true;if(this.levelkeys){var t;let i=Object.keys(this.levelkeys),r=i.length;if(r>1||r===1&&(t=this.levelkeys[i[0]])!=null&&t.encrypted)return true}return false}get programDateTime(){return this._programDateTime===null&&this.rawProgramDateTime&&(this.programDateTime=Date.parse(this.rawProgramDateTime)),this._programDateTime}set programDateTime(e){if(!G(e)){this._programDateTime=this.rawProgramDateTime=null;return}this._programDateTime=e;}get ref(){return Ue(this)?(this._ref||(this._ref={base:this.base,start:this.start,duration:this.duration,sn:this.sn,programDateTime:this.programDateTime}),this._ref):null}addStart(e){this.setStart(this.start+e);}setStart(e){this.start=e,this._ref&&(this._ref.start=e);}setDuration(e){this.duration=e,this._ref&&(this._ref.duration=e);}setKeyFormat(e){let t=this.levelkeys;if(t){var i;let r=t[e];r&&!((i=this._decryptdata)!=null&&i.keyId)&&(this._decryptdata=r.getDecryptData(this.sn,t));}}abortRequests(){var e,t;(e=this.loader)==null||e.abort(),(t=this.keyLoader)==null||t.abort();}setElementaryStreamInfo(e,t,i,r,n,a=false){let{elementaryStreams:o}=this,l=o[e];if(!l){o[e]={startPTS:t,endPTS:i,startDTS:r,endDTS:n,partial:a};return}l.startPTS=Math.min(l.startPTS,t),l.endPTS=Math.max(l.endPTS,i),l.startDTS=Math.min(l.startDTS,r),l.endDTS=Math.max(l.endDTS,n);}},pc=class extends $o{constructor(e,t,i,r,n){super(i),this.fragOffset=0,this.duration=0,this.gap=false,this.independent=false,this.relurl=void 0,this.fragment=void 0,this.index=void 0,this.duration=e.decimalFloatingPoint("DURATION"),this.gap=e.bool("GAP"),this.independent=e.bool("INDEPENDENT"),this.relurl=e.enumeratedString("URI"),this.fragment=t,this.index=r;let a=e.enumeratedString("BYTERANGE");a&&this.setByteRange(a,n),n&&(this.fragOffset=n.fragOffset+n.duration);}get start(){return this.fragment.start+this.fragOffset}get end(){return this.start+this.duration}get loaded(){let{elementaryStreams:e}=this;return !!(e.audio||e.video||e.audiovideo)}};function Ig(s,e){let t=Object.getPrototypeOf(s);if(t){let i=Object.getOwnPropertyDescriptor(t,e);return i||Ig(t,e)}}function eT(s,e){let t=Ig(s,e);t&&(t.enumerable=true,Object.defineProperty(s,e,t));}var mm=Math.pow(2,32)-1,tT=[].push,Lg={video:1,audio:2,id3:3,text:4};function He(s){return String.fromCharCode.apply(null,s)}function xg(s,e){let t=s[e]<<8|s[e+1];return t<0?65536+t:t}function J(s,e){let t=Rg(s,e);return t<0?4294967296+t:t}function gm(s,e){let t=J(s,e);return t*=Math.pow(2,32),t+=J(s,e+4),t}function Rg(s,e){return s[e]<<24|s[e+1]<<16|s[e+2]<<8|s[e+3]}function iT(s){let e=s.byteLength;for(let t=0;t<e;){let i=J(s,t);if(i>8&&s[t+4]===109&&s[t+5]===111&&s[t+6]===111&&s[t+7]===102)return true;t=i>1?t+i:e;}return false}function le(s,e){let t=[];if(!e.length)return t;let i=s.byteLength;for(let r=0;r<i;){let n=J(s,r),a=He(s.subarray(r+4,r+8)),o=n>1?r+n:i;if(a===e[0])if(e.length===1)t.push(s.subarray(r+8,o));else {let l=le(s.subarray(r+8,o),e.slice(1));l.length&&tT.apply(t,l);}r=o;}return t}function sT(s){let e=[],t=s[0],i=8,r=J(s,i);i+=4;let n=0,a=0;t===0?(n=J(s,i),a=J(s,i+4),i+=8):(n=gm(s,i),a=gm(s,i+8),i+=16),i+=2;let o=s.length+a,l=xg(s,i);i+=2;for(let d=0;d<l;d++){let c=i,u=J(s,c);c+=4;let h=u&2147483647;if((u&2147483648)>>>31===1)return Te.warn("SIDX has hierarchical references (not supported)"),null;let m=J(s,c);c+=4,e.push({referenceSize:h,subsegmentDuration:m,info:{duration:m/r,start:o,end:o+h-1}}),o+=h,c+=4,i=c;}return {earliestPresentationTime:n,timescale:r,version:t,referencesCount:l,references:e}}function kg(s){let e=[],t=le(s,["moov","trak"]);for(let r=0;r<t.length;r++){let n=t[r],a=le(n,["tkhd"])[0];if(a){let o=a[0],l=J(a,o===0?12:20),d=le(n,["mdia","mdhd"])[0];if(d){o=d[0];let c=J(d,o===0?12:20),u=le(n,["mdia","hdlr"])[0];if(u){let h=He(u.subarray(8,12)),f={soun:Se.AUDIO,vide:Se.VIDEO}[h],m=le(n,["mdia","minf","stbl","stsd"])[0],p=rT(m);f?(e[l]={timescale:c,type:f,stsd:p},e[f]=ve({timescale:c,id:l},p)):e[l]={timescale:c,type:h,stsd:p};}}}}return le(s,["moov","mvex","trex"]).forEach(r=>{let n=J(r,4),a=e[n];a&&(a.default={duration:J(r,12),flags:J(r,20)});}),e}function rT(s){let e=s.subarray(8),t=e.subarray(86),i=He(e.subarray(4,8)),r=i,n,a=i==="enca"||i==="encv";if(a){let d=le(e,[i])[0].subarray(i==="enca"?28:78);le(d,["sinf"]).forEach(u=>{let h=le(u,["schm"])[0];if(h){let f=He(h.subarray(4,8));if(f==="cbcs"||f==="cenc"){let m=le(u,["frma"])[0];m&&(r=He(m));}}});}let o=r;switch(r){case "avc1":case "avc2":case "avc3":case "avc4":{let l=le(t,["avcC"])[0];l&&l.length>3&&(r+="."+To(l[1])+To(l[2])+To(l[3]),n=vo(o==="avc1"?"dva1":"dvav",t));break}case "mp4a":{let l=le(e,[i])[0],d=le(l.subarray(28),["esds"])[0];if(d&&d.length>7){let c=4;if(d[c++]!==3)break;c=Yd(d,c),c+=2;let u=d[c++];if(u&128&&(c+=2),u&64&&(c+=d[c++]),d[c++]!==4)break;c=Yd(d,c);let h=d[c++];if(h===64)r+="."+To(h);else break;if(c+=12,d[c++]!==5)break;c=Yd(d,c);let f=d[c++],m=(f&248)>>3;m===31&&(m+=1+((f&7)<<3)+((d[c]&224)>>5)),r+="."+m;}break}case "hvc1":case "hev1":{let l=le(t,["hvcC"])[0];if(l&&l.length>12){let d=l[1],c=["","A","B","C"][d>>6],u=d&31,h=J(l,2),f=(d&32)>>5?"H":"L",m=l[12],p=l.subarray(6,12);r+="."+c+u,r+="."+nT(h).toString(16).toUpperCase(),r+="."+f+m;let E="";for(let v=p.length;v--;){let T=p[v];(T||E)&&(E="."+T.toString(16).toUpperCase()+E);}r+=E;}n=vo(o=="hev1"?"dvhe":"dvh1",t);break}case "dvh1":case "dvhe":case "dvav":case "dva1":case "dav1":{r=vo(r,t)||r;break}case "vp09":{let l=le(t,["vpcC"])[0];if(l&&l.length>6){let d=l[4],c=l[5],u=l[6]>>4&15;r+="."+oi(d)+"."+oi(c)+"."+oi(u);}break}case "av01":{let l=le(t,["av1C"])[0];if(l&&l.length>2){let d=l[1]>>>5,c=l[1]&31,u=l[2]>>>7?"H":"M",h=(l[2]&64)>>6,f=(l[2]&32)>>5,m=d===2&&h?f?12:10:h?10:8,p=(l[2]&16)>>4,E=(l[2]&8)>>3,v=(l[2]&4)>>2,T=l[2]&3;r+="."+d+"."+oi(c)+u+"."+oi(m)+"."+p+"."+E+v+T+"."+oi(1)+"."+oi(1)+"."+oi(1)+"."+0,n=vo("dav1",t);}break}}return {codec:r,encrypted:a,supplemental:n}}function vo(s,e){let t=le(e,["dvvC"]),i=t.length?t[0]:le(e,["dvcC"])[0];if(i){let r=i[2]>>1&127,n=i[2]<<5&32|i[3]>>3&31;return s+"."+oi(r)+"."+oi(n)}}function nT(s){let e=0;for(let t=0;t<32;t++)e|=(s>>t&1)<<31-t;return e>>>0}function Yd(s,e){let t=e+5;for(;s[e++]&128&&e<t;);return e}function To(s){return ("0"+s.toString(16).toUpperCase()).slice(-2)}function oi(s){return (s<10?"0":"")+s}function aT(s,e){if(!s||!e)return;let t=e.keyId;t&&e.isCommonEncryption&&Dg(s,(i,r)=>{let n=i.subarray(8,24);n.some(a=>a!==0)||(Te.log(`[eme] Patching keyId in 'enc${r?"a":"v"}>sinf>>tenc' box: ${rt(n)} -> ${rt(t)}`),i.set(t,8));});}function oT(s){let e=[];return Dg(s,t=>e.push(t.subarray(8,24))),e}function Dg(s,e){le(s,["moov","trak"]).forEach(i=>{let r=le(i,["mdia","minf","stbl","stsd"])[0];if(!r)return;let n=r.subarray(8),a=le(n,["enca"]),o=a.length>0;o||(a=le(n,["encv"])),a.forEach(l=>{let d=o?l.subarray(28):l.subarray(78);le(d,["sinf"]).forEach(u=>{let h=Cg(u);h&&e(h,o);});});});}function Cg(s){let e=le(s,["schm"])[0];if(e){let t=He(e.subarray(4,8));if(t==="cbcs"||t==="cenc"){let i=le(s,["schi","tenc"])[0];if(i)return i}}}function lT(s,e,t){let i={},r=le(s,["moof","traf"]);for(let n=0;n<r.length;n++){let a=r[n],o=le(a,["tfhd"])[0],l=J(o,4),d=e[l];if(!d)continue;i[l]||(i[l]={start:NaN,duration:0,sampleCount:0,timescale:d.timescale,type:d.type});let c=i[l],u=le(a,["tfdt"])[0];if(u){let S=u[0],A=J(u,4);S===1&&(A===mm?t.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"):(A*=mm+1,A+=J(u,8))),G(A)&&(!G(c.start)||A<c.start)&&(c.start=A);}let h=d.default,f=J(o,0)|h?.flags,m=h?.duration||0;f&8&&(f&2?m=J(o,12):m=J(o,8));let p=le(a,["trun"]),E=c.start||0,v=0,T=m;for(let S=0;S<p.length;S++){let A=p[S],b=J(A,4),D=c.sampleCount;c.sampleCount+=b;let I=A[3]&1,k=A[3]&4,R=A[2]&1,L=A[2]&2,M=A[2]&4,B=A[2]&8,H=8,j=b;for(I&&(H+=4),k&&b&&(!(A[H+1]&1)&&c.keyFrameIndex===void 0&&(c.keyFrameIndex=D),H+=4,R?(T=J(A,H),H+=4):T=m,L&&(H+=4),B&&(H+=4),E+=T,v+=T,j--);j--;)R?(T=J(A,H),H+=4):T=m,L&&(H+=4),M&&(A[H+1]&1||c.keyFrameIndex===void 0&&(c.keyFrameIndex=c.sampleCount-(j+1),c.keyFrameStart=E),H+=4),B&&(H+=4),E+=T,v+=T;!v&&m&&(v+=m*b);}c.duration+=v;}if(!Object.keys(i).some(n=>i[n].duration)){let n=1/0,a=0,o=le(s,["sidx"]);for(let l=0;l<o.length;l++){let d=sT(o[l]);if(d!=null&&d.references){n=Math.min(n,d.earliestPresentationTime/d.timescale);let c=d.references.reduce((u,h)=>u+h.info.duration||0,0);a=Math.max(a,c+d.earliestPresentationTime/d.timescale);}}a&&G(a)&&Object.keys(i).forEach(l=>{i[l].duration||(i[l].duration=a*i[l].timescale-i[l].start);});}return i}function dT(s){let e={valid:null,remainder:null},t=le(s,["moof"]);if(t.length<2)return e.remainder=s,e;let i=t[t.length-1];return e.valid=s.slice(0,i.byteOffset-8),e.remainder=s.slice(i.byteOffset-8),e}function Dt(s,e){let t=new Uint8Array(s.length+e.length);return t.set(s),t.set(e,s.length),t}function pm(s,e){let t=[],i=e.samples,r=e.timescale,n=e.id,a=false;return le(i,["moof"]).map(l=>{let d=l.byteOffset-8;le(l,["traf"]).map(u=>{let h=le(u,["tfdt"]).map(f=>{let m=f[0],p=J(f,4);return m===1&&(p*=Math.pow(2,32),p+=J(f,8)),p/r})[0];return h!==void 0&&(s=h),le(u,["tfhd"]).map(f=>{let m=J(f,4),p=J(f,0)&16777215,E=(p&1)!==0,v=(p&2)!==0,T=(p&8)!==0,S=0,A=(p&16)!==0,b=0,D=(p&32)!==0,I=8;m===n&&(E&&(I+=8),v&&(I+=4),T&&(S=J(f,I),I+=4),A&&(b=J(f,I),I+=4),D&&(I+=4),e.type==="video"&&(a=hl(e.codec)),le(u,["trun"]).map(k=>{let R=k[0],L=J(k,0)&16777215,M=(L&1)!==0,B=0,H=(L&4)!==0,j=(L&256)!==0,K=0,O=(L&512)!==0,Y=0,$=(L&1024)!==0,q=(L&2048)!==0,Q=0,N=J(k,4),U=8;M&&(B=J(k,U),U+=4),H&&(U+=4);let te=B+d;for(let ge=0;ge<N;ge++){if(j?(K=J(k,U),U+=4):K=S,O?(Y=J(k,U),U+=4):Y=b,$&&(U+=4),q&&(R===0?Q=J(k,U):Q=Rg(k,U),U+=4),e.type===Se.VIDEO){let ie=0;for(;ie<Y;){let de=J(i,te);if(te+=4,cT(a,i[te])){let Be=i.subarray(te,te+de);Pu(Be,a?2:1,s+Q/r,t);}te+=de,ie+=de+4;}}s+=K/r;}}));})});}),t}function hl(s){if(!s)return false;let e=s.substring(0,4);return e==="hvc1"||e==="hev1"||e==="dvh1"||e==="dvhe"}function cT(s,e){if(s){let t=e>>1&63;return t===39||t===40}else return (e&31)===6}function Pu(s,e,t,i){let r=Mg(s),n=0;n+=e;let a=0,o=0,l=0;for(;n<r.length;){a=0;do{if(n>=r.length)break;l=r[n++],a+=l;}while(l===255);o=0;do{if(n>=r.length)break;l=r[n++],o+=l;}while(l===255);let d=r.length-n,c=n;if(o<d)n+=o;else if(o>d){Te.error(`Malformed SEI payload. ${o} is too small, only ${d} bytes left to parse.`);break}if(a===4){if(r[c++]===181){let h=xg(r,c);if(c+=2,h===49){let f=J(r,c);if(c+=4,f===1195456820){let m=r[c++];if(m===3){let p=r[c++],E=31&p,v=64&p,T=v?2+E*3:0,S=new Uint8Array(T);if(v){S[0]=p;for(let A=1;A<T;A++)S[A]=r[c++];}i.push({type:m,payloadType:a,pts:t,bytes:S});}}}}}else if(a===5&&o>16){let u=[];for(let m=0;m<16;m++){let p=r[c++].toString(16);u.push(p.length==1?"0"+p:p),(m===3||m===5||m===7||m===9)&&u.push("-");}let h=o-16,f=new Uint8Array(h);for(let m=0;m<h;m++)f[m]=r[c++];i.push({payloadType:a,pts:t,uuid:u.join(""),userData:bt(f),userDataBytes:f});}}}function Mg(s){let e=s.byteLength,t=[],i=1;for(;i<e-2;)s[i]===0&&s[i+1]===0&&s[i+2]===3?(t.push(i+2),i+=2):i++;if(t.length===0)return s;let r=e-t.length,n=new Uint8Array(r),a=0;for(i=0;i<r;a++,i++)a===t[0]&&(a++,t.shift()),n[i]=s[a];return n}function uT(s){let e=s[0],t="",i="",r=0,n=0,a=0,o=0,l=0,d=0;if(e===0){for(;He(s.subarray(d,d+1))!=="\0";)t+=He(s.subarray(d,d+1)),d+=1;for(t+=He(s.subarray(d,d+1)),d+=1;He(s.subarray(d,d+1))!=="\0";)i+=He(s.subarray(d,d+1)),d+=1;i+=He(s.subarray(d,d+1)),d+=1,r=J(s,12),n=J(s,16),o=J(s,20),l=J(s,24),d=28;}else if(e===1){d+=4,r=J(s,d),d+=4;let u=J(s,d);d+=4;let h=J(s,d);for(d+=4,a=2**32*u+h,Kv(a)||(a=Number.MAX_SAFE_INTEGER,Te.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),o=J(s,d),d+=4,l=J(s,d),d+=4;He(s.subarray(d,d+1))!=="\0";)t+=He(s.subarray(d,d+1)),d+=1;for(t+=He(s.subarray(d,d+1)),d+=1;He(s.subarray(d,d+1))!=="\0";)i+=He(s.subarray(d,d+1)),d+=1;i+=He(s.subarray(d,d+1)),d+=1;}let c=s.subarray(d,s.byteLength);return {schemeIdUri:t,value:i,timeScale:r,presentationTime:a,presentationTimeDelta:n,eventDuration:o,id:l,payload:c}}function hT(s,...e){let t=e.length,i=8,r=t;for(;r--;)i+=e[r].byteLength;let n=new Uint8Array(i);for(n[0]=i>>24&255,n[1]=i>>16&255,n[2]=i>>8&255,n[3]=i&255,n.set(s,4),r=0,i=8;r<t;r++)n.set(e[r],i),i+=e[r].byteLength;return n}function fT(s,e,t){if(s.byteLength!==16)throw new RangeError("Invalid system id");let i,r;i=0,r=new Uint8Array;let n;i>0?(n=new Uint8Array(4),e.length>0&&new DataView(n.buffer).setUint32(0,e.length,false)):n=new Uint8Array;let a=new Uint8Array(4);return t.byteLength>0&&new DataView(a.buffer).setUint32(0,t.byteLength,false),hT([112,115,115,104],new Uint8Array([i,0,0,0]),s,n,r,a,t)}function mT(s){let e=[];if(s instanceof ArrayBuffer){let t=s.byteLength,i=0;for(;i+32<t;){let r=new DataView(s,i),n=gT(r);e.push(n),i+=n.size;}}return e}function gT(s){let e=s.getUint32(0),t=s.byteOffset,i=s.byteLength;if(i<e)return {offset:t,size:i};if(s.getUint32(4)!==1886614376)return {offset:t,size:e};let n=s.getUint32(8)>>>24;if(n!==0&&n!==1)return {offset:t,size:e};let a=s.buffer,o=rt(new Uint8Array(a,t+12,16)),l=null,d=null,c=0;if(n===0)c=28;else {let h=s.getUint32(28);if(!h||i<32+h*16)return {offset:t,size:e};l=[];for(let f=0;f<h;f++)l.push(new Uint8Array(a,t+32+f*16,16));c=32+h*16;}if(!c)return {offset:t,size:e};let u=s.getUint32(c);return e-32<u?{offset:t,size:e}:(d=new Uint8Array(a,t+c+4,u),{version:n,systemId:o,kids:l,data:d,offset:t,size:e})}var Pg=()=>/\(Windows.+Firefox\//i.test(navigator.userAgent),ar={audio:{a3ds:1,"ac-3":.95,"ac-4":1,alac:.9,alaw:1,dra1:1,"dts+":1,"dts-":1,dtsc:1,dtse:1,dtsh:1,"ec-3":.9,enca:1,fLaC:.9,flac:.9,FLAC:.9,g719:1,g726:1,m4ae:1,mha1:1,mha2:1,mhm1:1,mhm2:1,mlpa:1,mp4a:1,"raw ":1,Opus:1,opus:1,samr:1,sawb:1,sawp:1,sevc:1,sqcp:1,ssmv:1,twos:1,ulaw:1},video:{avc1:1,avc2:1,avc3:1,avc4:1,avcp:1,av01:.8,dav1:.8,drac:1,dva1:1,dvav:1,dvh1:.7,dvhe:.7,encv:1,hev1:.75,hvc1:.75,mjp2:1,mp4v:1,mvc1:1,mvc2:1,mvc3:1,mvc4:1,resv:1,rv60:1,s263:1,svc1:1,svc2:1,"vc-1":1,vp08:1,vp09:.9},text:{stpp:1,wvtt:1}};function wu(s,e){let t=ar[e];return !!t&&!!t[s.slice(0,4)]}function gn(s,e,t=true){return !s.split(",").some(i=>!Ou(i,e,t))}function Ou(s,e,t=true){var i;let r=Fi(t);return (i=r?.isTypeSupported(pn(s,e)))!=null?i:false}function pn(s,e){return `${e}/mp4;codecs=${s}`}function Em(s){if(s){let e=s.substring(0,4);return ar.video[e]}return 2}function Go(s){let e=Pg();return s.split(",").reduce((t,i)=>{let n=e&&hl(i)?9:ar.video[i];return n?(n*2+t)/(t?3:2):(ar.audio[i]+t)/(t?2:1)},0)}var qd={};function pT(s,e=true){if(qd[s])return qd[s];let t={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"],"mp4a.40.34":["mp3"]}[s];for(let r=0;r<t.length;r++){var i;if(Ou(t[r],"audio",e))return qd[s]=t[r],t[r];if(t[r]==="mp3"&&(i=Fi(e))!=null&&i.isTypeSupported("audio/mpeg"))return ""}return s}var ET=/flac|opus|mp4a\.40\.34/i;function Ho(s,e=true){return s.replace(ET,t=>pT(t.toLowerCase(),e))}function vT(s,e){let t=[];if(s){let i=s.split(",");for(let r=0;r<i.length;r++)wu(i[r],"video")||t.push(i[r]);}return e&&t.push(e),t.join(",")}function Po(s,e){if(s&&(s.length>4||["ac-3","ec-3","alac","fLaC","Opus"].indexOf(s)!==-1)&&(vm(s,"audio")||vm(s,"video")))return s;if(e){let t=e.split(",");if(t.length>1){if(s){for(let i=t.length;i--;)if(t[i].substring(0,4)===s.substring(0,4))return t[i]}return t[0]}}return e||s}function vm(s,e){return wu(s,e)&&Ou(s,e)}function TT(s){let e=s.split(",");for(let t=0;t<e.length;t++){let i=e[t].split(".");i.length>2&&i[0]==="avc1"&&(e[t]=`avc1.${parseInt(i[1]).toString(16)}${("000"+parseInt(i[2]).toString(16)).slice(-4)}`);}return e.join(",")}function yT(s){if(s.startsWith("av01.")){let e=s.split("."),t=["0","111","01","01","01","0"];for(let i=e.length;i>4&&i<10;i++)e[i]=t[i-4];return e.join(".")}return s}function Tm(s){let e=Fi(s)||{isTypeSupported:()=>false};return {mpeg:e.isTypeSupported("audio/mpeg"),mp3:e.isTypeSupported('audio/mp4; codecs="mp3"'),ac3:e.isTypeSupported('audio/mp4; codecs="ac-3"')}}function Ec(s){return s.replace(/^.+codecs=["']?([^"']+).*$/,"$1")}var ST={supported:true,powerEfficient:true,smooth:true},AT={supported:false,smooth:false,powerEfficient:false},wg={supported:true,configurations:[],decodingInfoResults:[ST]};function Og(s,e){return {supported:false,configurations:e,decodingInfoResults:[AT],error:s}}function bT(s,e,t,i,r,n){let a=s.videoCodec,o=s.audioCodec?s.audioGroups:null,l=n?.audioCodec,d=n?.channels,c=d?parseInt(d):l?1/0:2,u=null;if(o!=null&&o.length)try{o.length===1&&o[0]?u=e.groups[o[0]].channels:u=o.reduce((h,f)=>{if(f){let m=e.groups[f];if(!m)throw new Error(`Audio track group ${f} not found`);Object.keys(m.channels).forEach(p=>{h[p]=(h[p]||0)+m.channels[p];});}return h},{2:0});}catch{return true}return a!==void 0&&(a.split(",").some(h=>hl(h))||s.width>1920&&s.height>1088||s.height>1920&&s.width>1088||s.frameRate>Math.max(i,30)||s.videoRange!=="SDR"&&s.videoRange!==t||s.bitrate>Math.max(r,8e6))||!!u&&G(c)&&Object.keys(u).some(h=>parseInt(h)>c)}function Fg(s,e,t,i={}){let r=s.videoCodec;if(!r&&!s.audioCodec||!t)return Promise.resolve(wg);let n=[],a=_T(s),o=a.length,l=IT(s,e,o>0),d=l.length;for(let c=o||1*d||1;c--;){let u={type:"media-source"};if(o&&(u.video=a[c%o]),d){u.audio=l[c%d];let h=u.audio.bitrate;u.video&&h&&(u.video.bitrate-=h);}n.push(u);}if(r){let c=navigator.userAgent;if(r.split(",").some(u=>hl(u))&&Pg())return Promise.resolve(Og(new Error(`Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent string: (${c})`),n))}return Promise.all(n.map(c=>{let u=xT(c);return i[u]||(i[u]=t.decodingInfo(c))})).then(c=>({supported:!c.some(u=>!u.supported),configurations:n,decodingInfoResults:c})).catch(c=>({supported:false,configurations:n,decodingInfoResults:[],error:c}))}function _T(s){var e;let t=(e=s.videoCodec)==null?void 0:e.split(","),i=Ng(s),r=s.width||640,n=s.height||480,a=s.frameRate||30,o=s.videoRange.toLowerCase();return t?t.map(l=>{let d={contentType:pn(yT(l),"video"),width:r,height:n,bitrate:i,framerate:a};return o!=="sdr"&&(d.transferFunction=o),d}):[]}function IT(s,e,t){var i;let r=(i=s.audioCodec)==null?void 0:i.split(","),n=Ng(s);return r&&s.audioGroups?s.audioGroups.reduce((a,o)=>{var l;let d=o?(l=e.groups[o])==null?void 0:l.tracks:null;return d?d.reduce((c,u)=>{if(u.groupId===o){let h=parseFloat(u.channels||"");r.forEach(f=>{let m={contentType:pn(f,"audio"),bitrate:t?LT(f,n):n};h&&(m.channels=""+h),c.push(m);});}return c},a):a},[]):[]}function LT(s,e){if(e<=1)return 1;let t=128e3;return s==="ec-3"?t=768e3:s==="ac-3"&&(t=64e4),Math.min(e/2,t)}function Ng(s){return Math.ceil(Math.max(s.bitrate*.9,s.averageBitrate)/1e3)*1e3||1}function xT(s){let e="",{audio:t,video:i}=s;if(i){let r=Ec(i.contentType);e+=`${r}_r${i.height}x${i.width}f${Math.ceil(i.framerate)}${i.transferFunction||"sd"}_${Math.ceil(i.bitrate/1e5)}`;}if(t){let r=Ec(t.contentType);e+=`${i?"_":""}${r}_c${t.channels}`;}return e}var vc=["NONE","TYPE-0","TYPE-1",null];function RT(s){return vc.indexOf(s)>-1}var Ko=["SDR","PQ","HLG"];function kT(s){return !!s&&Ko.indexOf(s)>-1}var wo={No:"",Yes:"YES",v2:"v2"};function ym(s){let{canSkipUntil:e,canSkipDateRanges:t,age:i}=s,r=i<e/2;return e&&r?t?wo.v2:wo.Yes:wo.No}var Vo=class{constructor(e,t,i){this.msn=void 0,this.part=void 0,this.skip=void 0,this.msn=e,this.part=t,this.skip=i;}addDirectives(e){let t=new self.URL(e);return this.msn!==void 0&&t.searchParams.set("_HLS_msn",this.msn.toString()),this.part!==void 0&&t.searchParams.set("_HLS_part",this.part.toString()),this.skip&&t.searchParams.set("_HLS_skip",this.skip),t.href}},ds=class{constructor(e){if(this._attrs=void 0,this.audioCodec=void 0,this.bitrate=void 0,this.codecSet=void 0,this.url=void 0,this.frameRate=void 0,this.height=void 0,this.id=void 0,this.name=void 0,this.supplemental=void 0,this.videoCodec=void 0,this.width=void 0,this.details=void 0,this.fragmentError=0,this.loadError=0,this.loaded=void 0,this.realBitrate=0,this.supportedPromise=void 0,this.supportedResult=void 0,this._avgBitrate=0,this._audioGroups=void 0,this._subtitleGroups=void 0,this._urlId=0,this.url=[e.url],this._attrs=[e.attrs],this.bitrate=e.bitrate,e.details&&(this.details=e.details),this.id=e.id||0,this.name=e.name,this.width=e.width||0,this.height=e.height||0,this.frameRate=e.attrs.optionalFloat("FRAME-RATE",0),this._avgBitrate=e.attrs.decimalInteger("AVERAGE-BANDWIDTH"),this.audioCodec=e.audioCodec,this.videoCodec=e.videoCodec,this.codecSet=[e.videoCodec,e.audioCodec].filter(i=>!!i).map(i=>i.substring(0,4)).join(","),"supplemental"in e){var t;this.supplemental=e.supplemental;let i=(t=e.supplemental)==null?void 0:t.videoCodec;i&&i!==e.videoCodec&&(this.codecSet+=`,${i.substring(0,4)}`);}this.addGroupId("audio",e.attrs.AUDIO),this.addGroupId("text",e.attrs.SUBTITLES);}get maxBitrate(){return Math.max(this.realBitrate,this.bitrate)}get averageBitrate(){return this._avgBitrate||this.realBitrate||this.bitrate}get attrs(){return this._attrs[0]}get codecs(){return this.attrs.CODECS||""}get pathwayId(){return this.attrs["PATHWAY-ID"]||"."}get videoRange(){return this.attrs["VIDEO-RANGE"]||"SDR"}get score(){return this.attrs.optionalFloat("SCORE",0)}get uri(){return this.url[0]||""}hasAudioGroup(e){return Sm(this._audioGroups,e)}hasSubtitleGroup(e){return Sm(this._subtitleGroups,e)}get audioGroups(){return this._audioGroups}get subtitleGroups(){return this._subtitleGroups}addGroupId(e,t){if(t){if(e==="audio"){let i=this._audioGroups;i||(i=this._audioGroups=[]),i.indexOf(t)===-1&&i.push(t);}else if(e==="text"){let i=this._subtitleGroups;i||(i=this._subtitleGroups=[]),i.indexOf(t)===-1&&i.push(t);}}}get urlId(){return 0}set urlId(e){}get audioGroupIds(){return this.audioGroups?[this.audioGroupId]:void 0}get textGroupIds(){return this.subtitleGroups?[this.textGroupId]:void 0}get audioGroupId(){var e;return (e=this.audioGroups)==null?void 0:e[0]}get textGroupId(){var e;return (e=this.subtitleGroups)==null?void 0:e[0]}addFallback(){}};function Sm(s,e){return !e||!s?false:s.indexOf(e)!==-1}function DT(){if(typeof matchMedia=="function"){let s=matchMedia("(dynamic-range: high)"),e=matchMedia("bad query");if(s.media!==e.media)return s.matches===true}return false}function CT(s,e){let t=false,i=[];if(s&&(t=s!=="SDR",i=[s]),e){i=e.allowedVideoRanges||Ko.slice(0);let r=i.join("")!=="SDR"&&!e.videoCodec;t=e.preferHDR!==void 0?e.preferHDR:r&&DT(),t||(i=["SDR"]);}return {preferHDR:t,allowedVideoRanges:i}}var MT=s=>{let e=new WeakSet;return (t,i)=>{if(s&&(i=s(t,i)),typeof i=="object"&&i!==null){if(e.has(i))return;e.add(i);}return i}},Ae=(s,e)=>JSON.stringify(s,MT(e));function PT(s,e,t,i,r){let n=Object.keys(s),a=i?.channels,o=i?.audioCodec,l=r?.videoCodec,d=a&&parseInt(a)===2,c=false,u=false,h=1/0,f=1/0,m=1/0,p=1/0,E=0,v=[],{preferHDR:T,allowedVideoRanges:S}=CT(e,r);for(let k=n.length;k--;){let R=s[n[k]];c||(c=R.channels[2]>0),h=Math.min(h,R.minHeight),f=Math.min(f,R.minFramerate),m=Math.min(m,R.minBitrate),S.filter(M=>R.videoRanges[M]>0).length>0&&(u=true);}h=G(h)?h:0,f=G(f)?f:0;let A=Math.max(1080,h),b=Math.max(30,f);m=G(m)?m:t,t=Math.max(m,t),u||(e=void 0);let D=n.length>1;return {codecSet:n.reduce((k,R)=>{let L=s[R];if(R===k)return k;if(v=u?S.filter(M=>L.videoRanges[M]>0):[],D){if(L.minBitrate>t)return ni(R,`min bitrate of ${L.minBitrate} > current estimate of ${t}`),k;if(!L.hasDefaultAudio)return ni(R,"no renditions with default or auto-select sound found"),k;if(o&&R.indexOf(o.substring(0,4))%5!==0)return ni(R,`audio codec preference "${o}" not found`),k;if(a&&!d){if(!L.channels[a])return ni(R,`no renditions with ${a} channel sound found (channels options: ${Object.keys(L.channels)})`),k}else if((!o||d)&&c&&L.channels[2]===0)return ni(R,"no renditions with stereo sound found"),k;if(L.minHeight>A)return ni(R,`min resolution of ${L.minHeight} > maximum of ${A}`),k;if(L.minFramerate>b)return ni(R,`min framerate of ${L.minFramerate} > maximum of ${b}`),k;if(!v.some(M=>L.videoRanges[M]>0))return ni(R,`no variants with VIDEO-RANGE of ${Ae(v)} found`),k;if(l&&R.indexOf(l.substring(0,4))%5!==0)return ni(R,`video codec preference "${l}" not found`),k;if(L.maxScore<E)return ni(R,`max score of ${L.maxScore} < selected max of ${E}`),k}return k&&(Go(R)>=Go(k)||L.fragmentError>s[k].fragmentError)?k:(p=L.minIndex,E=L.maxScore,R)},void 0),videoRanges:v,preferHDR:T,minFramerate:f,minBitrate:m,minIndex:p}}function ni(s,e){Te.log(`[abr] start candidates with "${s}" ignored because ${e}`);}function Ug(s){return s.reduce((e,t)=>{let i=e.groups[t.groupId];i||(i=e.groups[t.groupId]={tracks:[],channels:{2:0},hasDefault:false,hasAutoSelect:false}),i.tracks.push(t);let r=t.channels||"2";return i.channels[r]=(i.channels[r]||0)+1,i.hasDefault=i.hasDefault||t.default,i.hasAutoSelect=i.hasAutoSelect||t.autoselect,i.hasDefault&&(e.hasDefaultAudio=true),i.hasAutoSelect&&(e.hasAutoSelectAudio=true),e},{hasDefaultAudio:false,hasAutoSelectAudio:false,groups:{}})}function wT(s,e,t,i){return s.slice(t,i+1).reduce((r,n,a)=>{if(!n.codecSet)return r;let o=n.audioGroups,l=r[n.codecSet];l||(r[n.codecSet]=l={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,minIndex:a,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!o,fragmentError:0}),l.minBitrate=Math.min(l.minBitrate,n.bitrate);let d=Math.min(n.height,n.width);return l.minHeight=Math.min(l.minHeight,d),l.minFramerate=Math.min(l.minFramerate,n.frameRate),l.minIndex=Math.min(l.minIndex,a),l.maxScore=Math.max(l.maxScore,n.score),l.fragmentError+=n.fragmentError,l.videoRanges[n.videoRange]=(l.videoRanges[n.videoRange]||0)+1,o&&o.forEach(c=>{if(!c)return;let u=e.groups[c];u&&(l.hasDefaultAudio=l.hasDefaultAudio||e.hasDefaultAudio?u.hasDefault:u.hasAutoSelect||!e.hasDefaultAudio&&!e.hasAutoSelectAudio,Object.keys(u.channels).forEach(h=>{l.channels[h]=(l.channels[h]||0)+u.channels[h];}));}),r},{})}function Am(s){if(!s)return s;let{lang:e,assocLang:t,characteristics:i,channels:r,audioCodec:n}=s;return {lang:e,assocLang:t,characteristics:i,channels:r,audioCodec:n}}function di(s,e,t){if("attrs"in s){let i=e.indexOf(s);if(i!==-1)return i}for(let i=0;i<e.length;i++){let r=e[i];if(os(s,r,t))return i}return -1}function os(s,e,t){let{groupId:i,name:r,lang:n,assocLang:a,default:o}=s,l=s.forced;return (i===void 0||e.groupId===i)&&(r===void 0||e.name===r)&&(n===void 0||OT(n,e.lang))&&(n===void 0||e.assocLang===a)&&(o===void 0||e.default===o)&&(l===void 0||e.forced===l)&&(!("characteristics"in s)||FT(s.characteristics||"",e.characteristics))&&(t===void 0||t(s,e))}function OT(s,e="--"){return s.length===e.length?s===e:s.startsWith(e)||e.startsWith(s)}function FT(s,e=""){let t=s.split(","),i=e.split(",");return t.length===i.length&&!t.some(r=>i.indexOf(r)===-1)}function ns(s,e){let{audioCodec:t,channels:i}=s;return (t===void 0||(e.audioCodec||"").substring(0,4)===t.substring(0,4))&&(i===void 0||i===(e.channels||"2"))}function NT(s,e,t,i,r){let n=e[i],o=e.reduce((h,f,m)=>{let p=f.uri;return (h[p]||(h[p]=[])).push(m),h},{})[n.uri];o.length>1&&(i=Math.max.apply(Math,o));let l=n.videoRange,d=n.frameRate,c=n.codecSet.substring(0,4),u=bm(e,i,h=>{if(h.videoRange!==l||h.frameRate!==d||h.codecSet.substring(0,4)!==c)return false;let f=h.audioGroups,m=t.filter(p=>!f||f.indexOf(p.groupId)!==-1);return di(s,m,r)>-1});return u>-1?u:bm(e,i,h=>{let f=h.audioGroups,m=t.filter(p=>!f||f.indexOf(p.groupId)!==-1);return di(s,m,r)>-1})}function bm(s,e,t){for(let i=e;i>-1;i--)if(t(s[i]))return i;for(let i=e+1;i<s.length;i++)if(t(s[i]))return i;return -1}function Wo(s,e){var t;return !!s&&s!==((t=e.loadLevelObj)==null?void 0:t.uri)}var Tc=class extends ht{constructor(e){super("abr",e.logger),this.hls=void 0,this.lastLevelLoadSec=0,this.lastLoadedFragLevel=-1,this.firstSelection=-1,this._nextAutoLevel=-1,this.nextAutoLevelKey="",this.audioTracksByGroup=null,this.codecTiers=null,this.timer=-1,this.fragCurrent=null,this.partCurrent=null,this.bitrateTestDelay=0,this.rebufferNotice=-1,this.supportedCache={},this.bwEstimator=void 0,this._abandonRulesCheck=t=>{var i;let{fragCurrent:r,partCurrent:n,hls:a}=this,{autoLevelEnabled:o,media:l}=a;if(!r||!l)return;let d=performance.now(),c=n?n.stats:r.stats,u=n?n.duration:r.duration,h=d-c.loading.start,f=a.minAutoLevel,m=r.level,p=this._nextAutoLevel;if(c.aborted||c.loaded&&c.loaded===c.total||m<=f){this.clearTimer(),this._nextAutoLevel=-1;return}if(!o)return;let E=p>-1&&p!==m,v=!!t||E;if(!v&&(l.paused||!l.playbackRate||!l.readyState))return;let T=a.mainForwardBufferInfo;if(!v&&T===null)return;let S=this.bwEstimator.getEstimateTTFB(),A=Math.abs(l.playbackRate);if(h<=Math.max(S,1e3*(u/(A*2))))return;let b=T?T.len/A:0,D=c.loading.first?c.loading.first-c.loading.start:-1,I=c.loaded&&D>-1,k=this.getBwEstimate(),R=a.levels,L=R[m],M=Math.max(c.loaded,Math.round(u*(r.bitrate||L.averageBitrate)/8)),B=I?h-D:h;B<1&&I&&(B=Math.min(h,c.loaded*8/k));let H=I?c.loaded*1e3/B:0,j=S/1e3,K=H?(M-c.loaded)/H:M*8/k+j;if(K<=b)return;let O=H?H*8:k,Y=((i=t?.details||this.hls.latestLevelDetails)==null?void 0:i.live)===true,$=this.hls.config.abrBandWidthUpFactor,q=Number.POSITIVE_INFINITY,Q;for(Q=m-1;Q>f;Q--){let ge=R[Q].maxBitrate,ie=!R[Q].details||Y;if(q=this.getTimeToLoadFrag(j,O,u*ge,ie),q<Math.min(b,u+j))break}if(q>=K||q>u*10)return;I?this.bwEstimator.sample(h-Math.min(S,D),c.loaded):this.bwEstimator.sampleTTFB(h);let N=R[Q].maxBitrate;this.getBwEstimate()*$>N&&this.resetEstimator(N);let U=this.findBestLevel(N,f,Q,0,b,1,1);U>-1&&(Q=U),this.warn(`Fragment ${r.sn}${n?" part "+n.index:""} of level ${m} is loading too slowly;
1349
+ `}var zs=class extends Tt{};zs.shadowRootOptions={mode:"open"};zs.getTemplateHTML=Kv;chunkDITZCOYN_cjs.o.customElements.get("media-context-menu-item")||chunkDITZCOYN_cjs.o.customElements.define("media-context-menu-item",zs);var xn=chunkJHSFSCC2_cjs.b(chunkKVMGCTLR_cjs.b(),1);var G=Number.isFinite||function(s){return typeof s=="number"&&isFinite(s)},Vv=Number.isSafeInteger||function(s){return typeof s=="number"&&Math.abs(s)<=Wv},Wv=Number.MAX_SAFE_INTEGER||9007199254740991,z=function(s){return s.NETWORK_ERROR="networkError",s.MEDIA_ERROR="mediaError",s.KEY_SYSTEM_ERROR="keySystemError",s.MUX_ERROR="muxError",s.OTHER_ERROR="otherError",s}({}),x=function(s){return s.KEY_SYSTEM_NO_KEYS="keySystemNoKeys",s.KEY_SYSTEM_NO_ACCESS="keySystemNoAccess",s.KEY_SYSTEM_NO_SESSION="keySystemNoSession",s.KEY_SYSTEM_NO_CONFIGURED_LICENSE="keySystemNoConfiguredLicense",s.KEY_SYSTEM_LICENSE_REQUEST_FAILED="keySystemLicenseRequestFailed",s.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED="keySystemServerCertificateRequestFailed",s.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED="keySystemServerCertificateUpdateFailed",s.KEY_SYSTEM_SESSION_UPDATE_FAILED="keySystemSessionUpdateFailed",s.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED="keySystemStatusOutputRestricted",s.KEY_SYSTEM_STATUS_INTERNAL_ERROR="keySystemStatusInternalError",s.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR="keySystemDestroyMediaKeysError",s.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR="keySystemDestroyCloseSessionError",s.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR="keySystemDestroyRemoveSessionError",s.MANIFEST_LOAD_ERROR="manifestLoadError",s.MANIFEST_LOAD_TIMEOUT="manifestLoadTimeOut",s.MANIFEST_PARSING_ERROR="manifestParsingError",s.MANIFEST_INCOMPATIBLE_CODECS_ERROR="manifestIncompatibleCodecsError",s.LEVEL_EMPTY_ERROR="levelEmptyError",s.LEVEL_LOAD_ERROR="levelLoadError",s.LEVEL_LOAD_TIMEOUT="levelLoadTimeOut",s.LEVEL_PARSING_ERROR="levelParsingError",s.LEVEL_SWITCH_ERROR="levelSwitchError",s.AUDIO_TRACK_LOAD_ERROR="audioTrackLoadError",s.AUDIO_TRACK_LOAD_TIMEOUT="audioTrackLoadTimeOut",s.SUBTITLE_LOAD_ERROR="subtitleTrackLoadError",s.SUBTITLE_TRACK_LOAD_TIMEOUT="subtitleTrackLoadTimeOut",s.FRAG_LOAD_ERROR="fragLoadError",s.FRAG_LOAD_TIMEOUT="fragLoadTimeOut",s.FRAG_DECRYPT_ERROR="fragDecryptError",s.FRAG_PARSING_ERROR="fragParsingError",s.FRAG_GAP="fragGap",s.REMUX_ALLOC_ERROR="remuxAllocError",s.KEY_LOAD_ERROR="keyLoadError",s.KEY_LOAD_TIMEOUT="keyLoadTimeOut",s.BUFFER_ADD_CODEC_ERROR="bufferAddCodecError",s.BUFFER_INCOMPATIBLE_CODECS_ERROR="bufferIncompatibleCodecsError",s.BUFFER_APPEND_ERROR="bufferAppendError",s.BUFFER_APPENDING_ERROR="bufferAppendingError",s.BUFFER_STALLED_ERROR="bufferStalledError",s.BUFFER_FULL_ERROR="bufferFullError",s.BUFFER_SEEK_OVER_HOLE="bufferSeekOverHole",s.BUFFER_NUDGE_ON_STALL="bufferNudgeOnStall",s.ASSET_LIST_LOAD_ERROR="assetListLoadError",s.ASSET_LIST_LOAD_TIMEOUT="assetListLoadTimeout",s.ASSET_LIST_PARSING_ERROR="assetListParsingError",s.INTERSTITIAL_ASSET_ITEM_ERROR="interstitialAssetItemError",s.INTERNAL_EXCEPTION="internalException",s.INTERNAL_ABORTED="aborted",s.ATTACH_MEDIA_ERROR="attachMediaError",s.UNKNOWN="unknown",s}({}),g=function(s){return s.MEDIA_ATTACHING="hlsMediaAttaching",s.MEDIA_ATTACHED="hlsMediaAttached",s.MEDIA_DETACHING="hlsMediaDetaching",s.MEDIA_DETACHED="hlsMediaDetached",s.MEDIA_ENDED="hlsMediaEnded",s.STALL_RESOLVED="hlsStallResolved",s.BUFFER_RESET="hlsBufferReset",s.BUFFER_CODECS="hlsBufferCodecs",s.BUFFER_CREATED="hlsBufferCreated",s.BUFFER_APPENDING="hlsBufferAppending",s.BUFFER_APPENDED="hlsBufferAppended",s.BUFFER_EOS="hlsBufferEos",s.BUFFERED_TO_END="hlsBufferedToEnd",s.BUFFER_FLUSHING="hlsBufferFlushing",s.BUFFER_FLUSHED="hlsBufferFlushed",s.MANIFEST_LOADING="hlsManifestLoading",s.MANIFEST_LOADED="hlsManifestLoaded",s.MANIFEST_PARSED="hlsManifestParsed",s.LEVEL_SWITCHING="hlsLevelSwitching",s.LEVEL_SWITCHED="hlsLevelSwitched",s.LEVEL_LOADING="hlsLevelLoading",s.LEVEL_LOADED="hlsLevelLoaded",s.LEVEL_UPDATED="hlsLevelUpdated",s.LEVEL_PTS_UPDATED="hlsLevelPtsUpdated",s.LEVELS_UPDATED="hlsLevelsUpdated",s.AUDIO_TRACKS_UPDATED="hlsAudioTracksUpdated",s.AUDIO_TRACK_SWITCHING="hlsAudioTrackSwitching",s.AUDIO_TRACK_SWITCHED="hlsAudioTrackSwitched",s.AUDIO_TRACK_LOADING="hlsAudioTrackLoading",s.AUDIO_TRACK_LOADED="hlsAudioTrackLoaded",s.AUDIO_TRACK_UPDATED="hlsAudioTrackUpdated",s.SUBTITLE_TRACKS_UPDATED="hlsSubtitleTracksUpdated",s.SUBTITLE_TRACKS_CLEARED="hlsSubtitleTracksCleared",s.SUBTITLE_TRACK_SWITCH="hlsSubtitleTrackSwitch",s.SUBTITLE_TRACK_LOADING="hlsSubtitleTrackLoading",s.SUBTITLE_TRACK_LOADED="hlsSubtitleTrackLoaded",s.SUBTITLE_TRACK_UPDATED="hlsSubtitleTrackUpdated",s.SUBTITLE_FRAG_PROCESSED="hlsSubtitleFragProcessed",s.CUES_PARSED="hlsCuesParsed",s.NON_NATIVE_TEXT_TRACKS_FOUND="hlsNonNativeTextTracksFound",s.INIT_PTS_FOUND="hlsInitPtsFound",s.FRAG_LOADING="hlsFragLoading",s.FRAG_LOAD_EMERGENCY_ABORTED="hlsFragLoadEmergencyAborted",s.FRAG_LOADED="hlsFragLoaded",s.FRAG_DECRYPTED="hlsFragDecrypted",s.FRAG_PARSING_INIT_SEGMENT="hlsFragParsingInitSegment",s.FRAG_PARSING_USERDATA="hlsFragParsingUserdata",s.FRAG_PARSING_METADATA="hlsFragParsingMetadata",s.FRAG_PARSED="hlsFragParsed",s.FRAG_BUFFERED="hlsFragBuffered",s.FRAG_CHANGED="hlsFragChanged",s.FPS_DROP="hlsFpsDrop",s.FPS_DROP_LEVEL_CAPPING="hlsFpsDropLevelCapping",s.MAX_AUTO_LEVEL_UPDATED="hlsMaxAutoLevelUpdated",s.ERROR="hlsError",s.DESTROYING="hlsDestroying",s.KEY_LOADING="hlsKeyLoading",s.KEY_LOADED="hlsKeyLoaded",s.LIVE_BACK_BUFFER_REACHED="hlsLiveBackBufferReached",s.BACK_BUFFER_REACHED="hlsBackBufferReached",s.STEERING_MANIFEST_LOADED="hlsSteeringManifestLoaded",s.ASSET_LIST_LOADING="hlsAssetListLoading",s.ASSET_LIST_LOADED="hlsAssetListLoaded",s.INTERSTITIALS_UPDATED="hlsInterstitialsUpdated",s.INTERSTITIALS_BUFFERED_TO_BOUNDARY="hlsInterstitialsBufferedToBoundary",s.INTERSTITIAL_ASSET_PLAYER_CREATED="hlsInterstitialAssetPlayerCreated",s.INTERSTITIAL_STARTED="hlsInterstitialStarted",s.INTERSTITIAL_ASSET_STARTED="hlsInterstitialAssetStarted",s.INTERSTITIAL_ASSET_ENDED="hlsInterstitialAssetEnded",s.INTERSTITIAL_ASSET_ERROR="hlsInterstitialAssetError",s.INTERSTITIAL_ENDED="hlsInterstitialEnded",s.INTERSTITIALS_PRIMARY_RESUMED="hlsInterstitialsPrimaryResumed",s.PLAYOUT_LIMIT_REACHED="hlsPlayoutLimitReached",s.EVENT_CUE_ENTER="hlsEventCueEnter",s}({}),ce={MANIFEST:"manifest",LEVEL:"level",AUDIO_TRACK:"audioTrack",SUBTITLE_TRACK:"subtitleTrack"},W={MAIN:"main",AUDIO:"audio",SUBTITLE:"subtitle"},wi=class{constructor(e,t=0,i=0){this.halfLife=void 0,this.alpha_=void 0,this.estimate_=void 0,this.totalWeight_=void 0,this.halfLife=e,this.alpha_=e?Math.exp(Math.log(.5)/e):0,this.estimate_=t,this.totalWeight_=i;}sample(e,t){let i=Math.pow(this.alpha_,e);this.estimate_=t*(1-i)+i*this.estimate_,this.totalWeight_+=e;}getTotalWeight(){return this.totalWeight_}getEstimate(){if(this.alpha_){let e=1-Math.pow(this.alpha_,this.totalWeight_);if(e)return this.estimate_/e}return this.estimate_}},fc=class{constructor(e,t,i,r=100){this.defaultEstimate_=void 0,this.minWeight_=void 0,this.minDelayMs_=void 0,this.slow_=void 0,this.fast_=void 0,this.defaultTTFB_=void 0,this.ttfb_=void 0,this.defaultEstimate_=i,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new wi(e),this.fast_=new wi(t),this.defaultTTFB_=r,this.ttfb_=new wi(e);}update(e,t){let{slow_:i,fast_:r,ttfb_:n}=this;i.halfLife!==e&&(this.slow_=new wi(e,i.getEstimate(),i.getTotalWeight())),r.halfLife!==t&&(this.fast_=new wi(t,r.getEstimate(),r.getTotalWeight())),n.halfLife!==e&&(this.ttfb_=new wi(e,n.getEstimate(),n.getTotalWeight()));}sample(e,t){e=Math.max(e,this.minDelayMs_);let i=8*t,r=e/1e3,n=i/r;this.fast_.sample(r,n),this.slow_.sample(r,n);}sampleTTFB(e){let t=e/1e3,i=Math.sqrt(2)*Math.exp(-Math.pow(t,2)/2);this.ttfb_.sample(i,Math.max(e,5));}canEstimate(){return this.fast_.getTotalWeight()>=this.minWeight_}getEstimate(){return this.canEstimate()?Math.min(this.fast_.getEstimate(),this.slow_.getEstimate()):this.defaultEstimate_}getEstimateTTFB(){return this.ttfb_.getTotalWeight()>=this.minWeight_?this.ttfb_.getEstimate():this.defaultTTFB_}get defaultEstimate(){return this.defaultEstimate_}destroy(){}};function Yv(s,e,t){return (e=jv(e))in s?Object.defineProperty(s,e,{value:t,enumerable:true,configurable:true,writable:true}):s[e]=t,s}function ye(){return ye=Object.assign?Object.assign.bind():function(s){for(var e=1;e<arguments.length;e++){var t=arguments[e];for(var i in t)({}).hasOwnProperty.call(t,i)&&(s[i]=t[i]);}return s},ye.apply(null,arguments)}function hm(s,e){var t=Object.keys(s);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(s);e&&(i=i.filter(function(r){return Object.getOwnPropertyDescriptor(s,r).enumerable})),t.push.apply(t,i);}return t}function ve(s){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?hm(Object(t),true).forEach(function(i){Yv(s,i,t[i]);}):Object.getOwnPropertyDescriptors?Object.defineProperties(s,Object.getOwnPropertyDescriptors(t)):hm(Object(t)).forEach(function(i){Object.defineProperty(s,i,Object.getOwnPropertyDescriptor(t,i));});}return s}function qv(s,e){if(typeof s!="object"||!s)return s;var t=s[Symbol.toPrimitive];if(t!==void 0){var i=t.call(s,e);if(typeof i!="object")return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return (e==="string"?String:Number)(s)}function jv(s){var e=qv(s,"string");return typeof e=="symbol"?e:e+""}var ht=class{constructor(e,t){this.trace=void 0,this.debug=void 0,this.log=void 0,this.warn=void 0,this.info=void 0,this.error=void 0;let i=`[${e}]:`;this.trace=Oi,this.debug=t.debug.bind(null,i),this.log=t.log.bind(null,i),this.warn=t.warn.bind(null,i),this.info=t.info.bind(null,i),this.error=t.error.bind(null,i);}},Oi=function(){},zv={trace:Oi,debug:Oi,log:Oi,warn:Oi,info:Oi,error:Oi};function mc(){return ye({},zv)}function Qv(s,e){let t=self.console[s];return t?t.bind(self.console,`${e?"["+e+"] ":""}[${s}] >`):Oi}function fm(s,e,t){return e[s]?e[s].bind(e):Qv(s,t)}var gc=mc();function Xv(s,e,t){let i=mc();if(typeof console=="object"&&s===true||typeof s=="object"){let r=["debug","log","info","warn","error"];r.forEach(n=>{i[n]=fm(n,s,t);});try{i.log(`Debug logs enabled for "${e}" in hls.js version 1.6.13`);}catch{return mc()}r.forEach(n=>{gc[n]=fm(n,s);});}else ye(gc,i);return i}var Te=gc;function Fi(s=true){return typeof self>"u"?void 0:(s||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function Zv(s){return typeof self<"u"&&s===self.ManagedMediaSource}function _g(s,e){let t=Object.keys(s),i=Object.keys(e),r=t.length,n=i.length;return !r||!n||r===n&&!t.some(a=>i.indexOf(a)===-1)}function bt(s,e=false){if(typeof TextDecoder<"u"){let d=new TextDecoder("utf-8").decode(s);if(e){let c=d.indexOf("\0");return c!==-1?d.substring(0,c):d}return d.replace(/\0/g,"")}let t=s.length,i,r,n,a="",o=0;for(;o<t;){if(i=s[o++],i===0&&e)return a;if(i===0||i===3)continue;switch(i>>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:a+=String.fromCharCode(i);break;case 12:case 13:r=s[o++],a+=String.fromCharCode((i&31)<<6|r&63);break;case 14:r=s[o++],n=s[o++],a+=String.fromCharCode((i&15)<<12|(r&63)<<6|(n&63)<<0);break}}return a}function rt(s){let e="";for(let t=0;t<s.length;t++){let i=s[t].toString(16);i.length<2&&(i="0"+i),e+=i;}return e}function Ig(s){return Uint8Array.from(s.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer}function Jv(s){return s&&s.__esModule&&Object.prototype.hasOwnProperty.call(s,"default")?s.default:s}var Wd={exports:{}},mm;function eT(){return mm||(mm=1,function(s,e){(function(t){var i=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,r=/^(?=([^\/?#]*))\1([^]*)$/,n=/(?:\/|^)\.(?=\/)/g,a=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,o={buildAbsoluteURL:function(l,d,c){if(c=c||{},l=l.trim(),d=d.trim(),!d){if(!c.alwaysNormalize)return l;var u=o.parseURL(l);if(!u)throw new Error("Error trying to parse base URL.");return u.path=o.normalizePath(u.path),o.buildURLFromParts(u)}var h=o.parseURL(d);if(!h)throw new Error("Error trying to parse relative URL.");if(h.scheme)return c.alwaysNormalize?(h.path=o.normalizePath(h.path),o.buildURLFromParts(h)):d;var f=o.parseURL(l);if(!f)throw new Error("Error trying to parse base URL.");if(!f.netLoc&&f.path&&f.path[0]!=="/"){var m=r.exec(f.path);f.netLoc=m[1],f.path=m[2];}f.netLoc&&!f.path&&(f.path="/");var p={scheme:f.scheme,netLoc:h.netLoc,path:null,params:h.params,query:h.query,fragment:h.fragment};if(!h.netLoc&&(p.netLoc=f.netLoc,h.path[0]!=="/"))if(!h.path)p.path=f.path,h.params||(p.params=f.params,h.query||(p.query=f.query));else {var E=f.path,v=E.substring(0,E.lastIndexOf("/")+1)+h.path;p.path=o.normalizePath(v);}return p.path===null&&(p.path=c.alwaysNormalize?o.normalizePath(h.path):h.path),o.buildURLFromParts(p)},parseURL:function(l){var d=i.exec(l);return d?{scheme:d[1]||"",netLoc:d[2]||"",path:d[3]||"",params:d[4]||"",query:d[5]||"",fragment:d[6]||""}:null},normalizePath:function(l){for(l=l.split("").reverse().join("").replace(n,"");l.length!==(l=l.replace(a,"")).length;);return l.split("").reverse().join("")},buildURLFromParts:function(l){return l.scheme+l.netLoc+l.path+l.params+l.query+l.fragment}};s.exports=o;})();}(Wd)),Wd.exports}var Mu=eT(),mn=class{constructor(){this.aborted=false,this.loaded=0,this.retry=0,this.total=0,this.chunkCount=0,this.bwEstimate=0,this.loading={start:0,first:0,end:0},this.parsing={start:0,end:0},this.buffering={start:0,first:0,end:0};}},Se={AUDIO:"audio",VIDEO:"video",AUDIOVIDEO:"audiovideo"},$o=class{constructor(e){this._byteRange=null,this._url=null,this._stats=null,this._streams=null,this.base=void 0,this.relurl=void 0,typeof e=="string"&&(e={url:e}),this.base=e,tT(this,"stats");}setByteRange(e,t){let i=e.split("@",2),r;i.length===1?r=t?.byteRangeEndOffset||0:r=parseInt(i[1]),this._byteRange=[r,parseInt(i[0])+r];}get baseurl(){return this.base.url}get byteRange(){return this._byteRange===null?[]:this._byteRange}get byteRangeStartOffset(){return this.byteRange[0]}get byteRangeEndOffset(){return this.byteRange[1]}get elementaryStreams(){return this._streams===null&&(this._streams={[Se.AUDIO]:null,[Se.VIDEO]:null,[Se.AUDIOVIDEO]:null}),this._streams}set elementaryStreams(e){this._streams=e;}get hasStats(){return this._stats!==null}get hasStreams(){return this._streams!==null}get stats(){return this._stats===null&&(this._stats=new mn),this._stats}set stats(e){this._stats=e;}get url(){return !this._url&&this.baseurl&&this.relurl&&(this._url=Mu.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:true})),this._url||""}set url(e){this._url=e;}clearElementaryStreamInfo(){let{elementaryStreams:e}=this;e[Se.AUDIO]=null,e[Se.VIDEO]=null,e[Se.AUDIOVIDEO]=null;}};function Ue(s){return s.sn!=="initSegment"}var cn=class extends $o{constructor(e,t){super(t),this._decryptdata=null,this._programDateTime=null,this._ref=null,this._bitrate=void 0,this.rawProgramDateTime=null,this.tagList=[],this.duration=0,this.sn=0,this.levelkeys=void 0,this.type=void 0,this.loader=null,this.keyLoader=null,this.level=-1,this.cc=0,this.startPTS=void 0,this.endPTS=void 0,this.startDTS=void 0,this.endDTS=void 0,this.start=0,this.playlistOffset=0,this.deltaPTS=void 0,this.maxStartPTS=void 0,this.minEndPTS=void 0,this.data=void 0,this.bitrateTest=false,this.title=null,this.initSegment=null,this.endList=void 0,this.gap=void 0,this.urlId=0,this.type=e;}get byteLength(){if(this.hasStats){let e=this.stats.total;if(e)return e}if(this.byteRange.length){let e=this.byteRange[0],t=this.byteRange[1];if(G(e)&&G(t))return t-e}return null}get bitrate(){return this.byteLength?this.byteLength*8/this.duration:this._bitrate?this._bitrate:null}set bitrate(e){this._bitrate=e;}get decryptdata(){var e;let{levelkeys:t}=this;if(!t||t.NONE)return null;if(t.identity)this._decryptdata||(this._decryptdata=t.identity.getDecryptData(this.sn));else if(!((e=this._decryptdata)!=null&&e.keyId)){let i=Object.keys(t);if(i.length===1){let r=this._decryptdata=t[i[0]]||null;r&&(this._decryptdata=r.getDecryptData(this.sn,t));}}return this._decryptdata}get end(){return this.start+this.duration}get endProgramDateTime(){if(this.programDateTime===null)return null;let e=G(this.duration)?this.duration:0;return this.programDateTime+e*1e3}get encrypted(){var e;if((e=this._decryptdata)!=null&&e.encrypted)return true;if(this.levelkeys){var t;let i=Object.keys(this.levelkeys),r=i.length;if(r>1||r===1&&(t=this.levelkeys[i[0]])!=null&&t.encrypted)return true}return false}get programDateTime(){return this._programDateTime===null&&this.rawProgramDateTime&&(this.programDateTime=Date.parse(this.rawProgramDateTime)),this._programDateTime}set programDateTime(e){if(!G(e)){this._programDateTime=this.rawProgramDateTime=null;return}this._programDateTime=e;}get ref(){return Ue(this)?(this._ref||(this._ref={base:this.base,start:this.start,duration:this.duration,sn:this.sn,programDateTime:this.programDateTime}),this._ref):null}addStart(e){this.setStart(this.start+e);}setStart(e){this.start=e,this._ref&&(this._ref.start=e);}setDuration(e){this.duration=e,this._ref&&(this._ref.duration=e);}setKeyFormat(e){let t=this.levelkeys;if(t){var i;let r=t[e];r&&!((i=this._decryptdata)!=null&&i.keyId)&&(this._decryptdata=r.getDecryptData(this.sn,t));}}abortRequests(){var e,t;(e=this.loader)==null||e.abort(),(t=this.keyLoader)==null||t.abort();}setElementaryStreamInfo(e,t,i,r,n,a=false){let{elementaryStreams:o}=this,l=o[e];if(!l){o[e]={startPTS:t,endPTS:i,startDTS:r,endDTS:n,partial:a};return}l.startPTS=Math.min(l.startPTS,t),l.endPTS=Math.max(l.endPTS,i),l.startDTS=Math.min(l.startDTS,r),l.endDTS=Math.max(l.endDTS,n);}},pc=class extends $o{constructor(e,t,i,r,n){super(i),this.fragOffset=0,this.duration=0,this.gap=false,this.independent=false,this.relurl=void 0,this.fragment=void 0,this.index=void 0,this.duration=e.decimalFloatingPoint("DURATION"),this.gap=e.bool("GAP"),this.independent=e.bool("INDEPENDENT"),this.relurl=e.enumeratedString("URI"),this.fragment=t,this.index=r;let a=e.enumeratedString("BYTERANGE");a&&this.setByteRange(a,n),n&&(this.fragOffset=n.fragOffset+n.duration);}get start(){return this.fragment.start+this.fragOffset}get end(){return this.start+this.duration}get loaded(){let{elementaryStreams:e}=this;return !!(e.audio||e.video||e.audiovideo)}};function Lg(s,e){let t=Object.getPrototypeOf(s);if(t){let i=Object.getOwnPropertyDescriptor(t,e);return i||Lg(t,e)}}function tT(s,e){let t=Lg(s,e);t&&(t.enumerable=true,Object.defineProperty(s,e,t));}var gm=Math.pow(2,32)-1,iT=[].push,xg={video:1,audio:2,id3:3,text:4};function He(s){return String.fromCharCode.apply(null,s)}function Rg(s,e){let t=s[e]<<8|s[e+1];return t<0?65536+t:t}function J(s,e){let t=kg(s,e);return t<0?4294967296+t:t}function pm(s,e){let t=J(s,e);return t*=Math.pow(2,32),t+=J(s,e+4),t}function kg(s,e){return s[e]<<24|s[e+1]<<16|s[e+2]<<8|s[e+3]}function sT(s){let e=s.byteLength;for(let t=0;t<e;){let i=J(s,t);if(i>8&&s[t+4]===109&&s[t+5]===111&&s[t+6]===111&&s[t+7]===102)return true;t=i>1?t+i:e;}return false}function le(s,e){let t=[];if(!e.length)return t;let i=s.byteLength;for(let r=0;r<i;){let n=J(s,r),a=He(s.subarray(r+4,r+8)),o=n>1?r+n:i;if(a===e[0])if(e.length===1)t.push(s.subarray(r+8,o));else {let l=le(s.subarray(r+8,o),e.slice(1));l.length&&iT.apply(t,l);}r=o;}return t}function rT(s){let e=[],t=s[0],i=8,r=J(s,i);i+=4;let n=0,a=0;t===0?(n=J(s,i),a=J(s,i+4),i+=8):(n=pm(s,i),a=pm(s,i+8),i+=16),i+=2;let o=s.length+a,l=Rg(s,i);i+=2;for(let d=0;d<l;d++){let c=i,u=J(s,c);c+=4;let h=u&2147483647;if((u&2147483648)>>>31===1)return Te.warn("SIDX has hierarchical references (not supported)"),null;let m=J(s,c);c+=4,e.push({referenceSize:h,subsegmentDuration:m,info:{duration:m/r,start:o,end:o+h-1}}),o+=h,c+=4,i=c;}return {earliestPresentationTime:n,timescale:r,version:t,referencesCount:l,references:e}}function Dg(s){let e=[],t=le(s,["moov","trak"]);for(let r=0;r<t.length;r++){let n=t[r],a=le(n,["tkhd"])[0];if(a){let o=a[0],l=J(a,o===0?12:20),d=le(n,["mdia","mdhd"])[0];if(d){o=d[0];let c=J(d,o===0?12:20),u=le(n,["mdia","hdlr"])[0];if(u){let h=He(u.subarray(8,12)),f={soun:Se.AUDIO,vide:Se.VIDEO}[h],m=le(n,["mdia","minf","stbl","stsd"])[0],p=nT(m);f?(e[l]={timescale:c,type:f,stsd:p},e[f]=ve({timescale:c,id:l},p)):e[l]={timescale:c,type:h,stsd:p};}}}}return le(s,["moov","mvex","trex"]).forEach(r=>{let n=J(r,4),a=e[n];a&&(a.default={duration:J(r,12),flags:J(r,20)});}),e}function nT(s){let e=s.subarray(8),t=e.subarray(86),i=He(e.subarray(4,8)),r=i,n,a=i==="enca"||i==="encv";if(a){let d=le(e,[i])[0].subarray(i==="enca"?28:78);le(d,["sinf"]).forEach(u=>{let h=le(u,["schm"])[0];if(h){let f=He(h.subarray(4,8));if(f==="cbcs"||f==="cenc"){let m=le(u,["frma"])[0];m&&(r=He(m));}}});}let o=r;switch(r){case "avc1":case "avc2":case "avc3":case "avc4":{let l=le(t,["avcC"])[0];l&&l.length>3&&(r+="."+To(l[1])+To(l[2])+To(l[3]),n=vo(o==="avc1"?"dva1":"dvav",t));break}case "mp4a":{let l=le(e,[i])[0],d=le(l.subarray(28),["esds"])[0];if(d&&d.length>7){let c=4;if(d[c++]!==3)break;c=Yd(d,c),c+=2;let u=d[c++];if(u&128&&(c+=2),u&64&&(c+=d[c++]),d[c++]!==4)break;c=Yd(d,c);let h=d[c++];if(h===64)r+="."+To(h);else break;if(c+=12,d[c++]!==5)break;c=Yd(d,c);let f=d[c++],m=(f&248)>>3;m===31&&(m+=1+((f&7)<<3)+((d[c]&224)>>5)),r+="."+m;}break}case "hvc1":case "hev1":{let l=le(t,["hvcC"])[0];if(l&&l.length>12){let d=l[1],c=["","A","B","C"][d>>6],u=d&31,h=J(l,2),f=(d&32)>>5?"H":"L",m=l[12],p=l.subarray(6,12);r+="."+c+u,r+="."+aT(h).toString(16).toUpperCase(),r+="."+f+m;let E="";for(let v=p.length;v--;){let T=p[v];(T||E)&&(E="."+T.toString(16).toUpperCase()+E);}r+=E;}n=vo(o=="hev1"?"dvhe":"dvh1",t);break}case "dvh1":case "dvhe":case "dvav":case "dva1":case "dav1":{r=vo(r,t)||r;break}case "vp09":{let l=le(t,["vpcC"])[0];if(l&&l.length>6){let d=l[4],c=l[5],u=l[6]>>4&15;r+="."+oi(d)+"."+oi(c)+"."+oi(u);}break}case "av01":{let l=le(t,["av1C"])[0];if(l&&l.length>2){let d=l[1]>>>5,c=l[1]&31,u=l[2]>>>7?"H":"M",h=(l[2]&64)>>6,f=(l[2]&32)>>5,m=d===2&&h?f?12:10:h?10:8,p=(l[2]&16)>>4,E=(l[2]&8)>>3,v=(l[2]&4)>>2,T=l[2]&3;r+="."+d+"."+oi(c)+u+"."+oi(m)+"."+p+"."+E+v+T+"."+oi(1)+"."+oi(1)+"."+oi(1)+"."+0,n=vo("dav1",t);}break}}return {codec:r,encrypted:a,supplemental:n}}function vo(s,e){let t=le(e,["dvvC"]),i=t.length?t[0]:le(e,["dvcC"])[0];if(i){let r=i[2]>>1&127,n=i[2]<<5&32|i[3]>>3&31;return s+"."+oi(r)+"."+oi(n)}}function aT(s){let e=0;for(let t=0;t<32;t++)e|=(s>>t&1)<<31-t;return e>>>0}function Yd(s,e){let t=e+5;for(;s[e++]&128&&e<t;);return e}function To(s){return ("0"+s.toString(16).toUpperCase()).slice(-2)}function oi(s){return (s<10?"0":"")+s}function oT(s,e){if(!s||!e)return;let t=e.keyId;t&&e.isCommonEncryption&&Cg(s,(i,r)=>{let n=i.subarray(8,24);n.some(a=>a!==0)||(Te.log(`[eme] Patching keyId in 'enc${r?"a":"v"}>sinf>>tenc' box: ${rt(n)} -> ${rt(t)}`),i.set(t,8));});}function lT(s){let e=[];return Cg(s,t=>e.push(t.subarray(8,24))),e}function Cg(s,e){le(s,["moov","trak"]).forEach(i=>{let r=le(i,["mdia","minf","stbl","stsd"])[0];if(!r)return;let n=r.subarray(8),a=le(n,["enca"]),o=a.length>0;o||(a=le(n,["encv"])),a.forEach(l=>{let d=o?l.subarray(28):l.subarray(78);le(d,["sinf"]).forEach(u=>{let h=Mg(u);h&&e(h,o);});});});}function Mg(s){let e=le(s,["schm"])[0];if(e){let t=He(e.subarray(4,8));if(t==="cbcs"||t==="cenc"){let i=le(s,["schi","tenc"])[0];if(i)return i}}}function dT(s,e,t){let i={},r=le(s,["moof","traf"]);for(let n=0;n<r.length;n++){let a=r[n],o=le(a,["tfhd"])[0],l=J(o,4),d=e[l];if(!d)continue;i[l]||(i[l]={start:NaN,duration:0,sampleCount:0,timescale:d.timescale,type:d.type});let c=i[l],u=le(a,["tfdt"])[0];if(u){let S=u[0],A=J(u,4);S===1&&(A===gm?t.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"):(A*=gm+1,A+=J(u,8))),G(A)&&(!G(c.start)||A<c.start)&&(c.start=A);}let h=d.default,f=J(o,0)|h?.flags,m=h?.duration||0;f&8&&(f&2?m=J(o,12):m=J(o,8));let p=le(a,["trun"]),E=c.start||0,v=0,T=m;for(let S=0;S<p.length;S++){let A=p[S],b=J(A,4),D=c.sampleCount;c.sampleCount+=b;let I=A[3]&1,k=A[3]&4,R=A[2]&1,L=A[2]&2,M=A[2]&4,B=A[2]&8,K=8,j=b;for(I&&(K+=4),k&&b&&(!(A[K+1]&1)&&c.keyFrameIndex===void 0&&(c.keyFrameIndex=D),K+=4,R?(T=J(A,K),K+=4):T=m,L&&(K+=4),B&&(K+=4),E+=T,v+=T,j--);j--;)R?(T=J(A,K),K+=4):T=m,L&&(K+=4),M&&(A[K+1]&1||c.keyFrameIndex===void 0&&(c.keyFrameIndex=c.sampleCount-(j+1),c.keyFrameStart=E),K+=4),B&&(K+=4),E+=T,v+=T;!v&&m&&(v+=m*b);}c.duration+=v;}if(!Object.keys(i).some(n=>i[n].duration)){let n=1/0,a=0,o=le(s,["sidx"]);for(let l=0;l<o.length;l++){let d=rT(o[l]);if(d!=null&&d.references){n=Math.min(n,d.earliestPresentationTime/d.timescale);let c=d.references.reduce((u,h)=>u+h.info.duration||0,0);a=Math.max(a,c+d.earliestPresentationTime/d.timescale);}}a&&G(a)&&Object.keys(i).forEach(l=>{i[l].duration||(i[l].duration=a*i[l].timescale-i[l].start);});}return i}function cT(s){let e={valid:null,remainder:null},t=le(s,["moof"]);if(t.length<2)return e.remainder=s,e;let i=t[t.length-1];return e.valid=s.slice(0,i.byteOffset-8),e.remainder=s.slice(i.byteOffset-8),e}function Dt(s,e){let t=new Uint8Array(s.length+e.length);return t.set(s),t.set(e,s.length),t}function Em(s,e){let t=[],i=e.samples,r=e.timescale,n=e.id,a=false;return le(i,["moof"]).map(l=>{let d=l.byteOffset-8;le(l,["traf"]).map(u=>{let h=le(u,["tfdt"]).map(f=>{let m=f[0],p=J(f,4);return m===1&&(p*=Math.pow(2,32),p+=J(f,8)),p/r})[0];return h!==void 0&&(s=h),le(u,["tfhd"]).map(f=>{let m=J(f,4),p=J(f,0)&16777215,E=(p&1)!==0,v=(p&2)!==0,T=(p&8)!==0,S=0,A=(p&16)!==0,b=0,D=(p&32)!==0,I=8;m===n&&(E&&(I+=8),v&&(I+=4),T&&(S=J(f,I),I+=4),A&&(b=J(f,I),I+=4),D&&(I+=4),e.type==="video"&&(a=hl(e.codec)),le(u,["trun"]).map(k=>{let R=k[0],L=J(k,0)&16777215,M=(L&1)!==0,B=0,K=(L&4)!==0,j=(L&256)!==0,V=0,O=(L&512)!==0,Y=0,$=(L&1024)!==0,q=(L&2048)!==0,Q=0,N=J(k,4),U=8;M&&(B=J(k,U),U+=4),K&&(U+=4);let te=B+d;for(let ge=0;ge<N;ge++){if(j?(V=J(k,U),U+=4):V=S,O?(Y=J(k,U),U+=4):Y=b,$&&(U+=4),q&&(R===0?Q=J(k,U):Q=kg(k,U),U+=4),e.type===Se.VIDEO){let ie=0;for(;ie<Y;){let de=J(i,te);if(te+=4,uT(a,i[te])){let Be=i.subarray(te,te+de);Pu(Be,a?2:1,s+Q/r,t);}te+=de,ie+=de+4;}}s+=V/r;}}));})});}),t}function hl(s){if(!s)return false;let e=s.substring(0,4);return e==="hvc1"||e==="hev1"||e==="dvh1"||e==="dvhe"}function uT(s,e){if(s){let t=e>>1&63;return t===39||t===40}else return (e&31)===6}function Pu(s,e,t,i){let r=Pg(s),n=0;n+=e;let a=0,o=0,l=0;for(;n<r.length;){a=0;do{if(n>=r.length)break;l=r[n++],a+=l;}while(l===255);o=0;do{if(n>=r.length)break;l=r[n++],o+=l;}while(l===255);let d=r.length-n,c=n;if(o<d)n+=o;else if(o>d){Te.error(`Malformed SEI payload. ${o} is too small, only ${d} bytes left to parse.`);break}if(a===4){if(r[c++]===181){let h=Rg(r,c);if(c+=2,h===49){let f=J(r,c);if(c+=4,f===1195456820){let m=r[c++];if(m===3){let p=r[c++],E=31&p,v=64&p,T=v?2+E*3:0,S=new Uint8Array(T);if(v){S[0]=p;for(let A=1;A<T;A++)S[A]=r[c++];}i.push({type:m,payloadType:a,pts:t,bytes:S});}}}}}else if(a===5&&o>16){let u=[];for(let m=0;m<16;m++){let p=r[c++].toString(16);u.push(p.length==1?"0"+p:p),(m===3||m===5||m===7||m===9)&&u.push("-");}let h=o-16,f=new Uint8Array(h);for(let m=0;m<h;m++)f[m]=r[c++];i.push({payloadType:a,pts:t,uuid:u.join(""),userData:bt(f),userDataBytes:f});}}}function Pg(s){let e=s.byteLength,t=[],i=1;for(;i<e-2;)s[i]===0&&s[i+1]===0&&s[i+2]===3?(t.push(i+2),i+=2):i++;if(t.length===0)return s;let r=e-t.length,n=new Uint8Array(r),a=0;for(i=0;i<r;a++,i++)a===t[0]&&(a++,t.shift()),n[i]=s[a];return n}function hT(s){let e=s[0],t="",i="",r=0,n=0,a=0,o=0,l=0,d=0;if(e===0){for(;He(s.subarray(d,d+1))!=="\0";)t+=He(s.subarray(d,d+1)),d+=1;for(t+=He(s.subarray(d,d+1)),d+=1;He(s.subarray(d,d+1))!=="\0";)i+=He(s.subarray(d,d+1)),d+=1;i+=He(s.subarray(d,d+1)),d+=1,r=J(s,12),n=J(s,16),o=J(s,20),l=J(s,24),d=28;}else if(e===1){d+=4,r=J(s,d),d+=4;let u=J(s,d);d+=4;let h=J(s,d);for(d+=4,a=2**32*u+h,Vv(a)||(a=Number.MAX_SAFE_INTEGER,Te.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),o=J(s,d),d+=4,l=J(s,d),d+=4;He(s.subarray(d,d+1))!=="\0";)t+=He(s.subarray(d,d+1)),d+=1;for(t+=He(s.subarray(d,d+1)),d+=1;He(s.subarray(d,d+1))!=="\0";)i+=He(s.subarray(d,d+1)),d+=1;i+=He(s.subarray(d,d+1)),d+=1;}let c=s.subarray(d,s.byteLength);return {schemeIdUri:t,value:i,timeScale:r,presentationTime:a,presentationTimeDelta:n,eventDuration:o,id:l,payload:c}}function fT(s,...e){let t=e.length,i=8,r=t;for(;r--;)i+=e[r].byteLength;let n=new Uint8Array(i);for(n[0]=i>>24&255,n[1]=i>>16&255,n[2]=i>>8&255,n[3]=i&255,n.set(s,4),r=0,i=8;r<t;r++)n.set(e[r],i),i+=e[r].byteLength;return n}function mT(s,e,t){if(s.byteLength!==16)throw new RangeError("Invalid system id");let i,r;i=0,r=new Uint8Array;let n;i>0?(n=new Uint8Array(4),e.length>0&&new DataView(n.buffer).setUint32(0,e.length,false)):n=new Uint8Array;let a=new Uint8Array(4);return t.byteLength>0&&new DataView(a.buffer).setUint32(0,t.byteLength,false),fT([112,115,115,104],new Uint8Array([i,0,0,0]),s,n,r,a,t)}function gT(s){let e=[];if(s instanceof ArrayBuffer){let t=s.byteLength,i=0;for(;i+32<t;){let r=new DataView(s,i),n=pT(r);e.push(n),i+=n.size;}}return e}function pT(s){let e=s.getUint32(0),t=s.byteOffset,i=s.byteLength;if(i<e)return {offset:t,size:i};if(s.getUint32(4)!==1886614376)return {offset:t,size:e};let n=s.getUint32(8)>>>24;if(n!==0&&n!==1)return {offset:t,size:e};let a=s.buffer,o=rt(new Uint8Array(a,t+12,16)),l=null,d=null,c=0;if(n===0)c=28;else {let h=s.getUint32(28);if(!h||i<32+h*16)return {offset:t,size:e};l=[];for(let f=0;f<h;f++)l.push(new Uint8Array(a,t+32+f*16,16));c=32+h*16;}if(!c)return {offset:t,size:e};let u=s.getUint32(c);return e-32<u?{offset:t,size:e}:(d=new Uint8Array(a,t+c+4,u),{version:n,systemId:o,kids:l,data:d,offset:t,size:e})}var wg=()=>/\(Windows.+Firefox\//i.test(navigator.userAgent),ar={audio:{a3ds:1,"ac-3":.95,"ac-4":1,alac:.9,alaw:1,dra1:1,"dts+":1,"dts-":1,dtsc:1,dtse:1,dtsh:1,"ec-3":.9,enca:1,fLaC:.9,flac:.9,FLAC:.9,g719:1,g726:1,m4ae:1,mha1:1,mha2:1,mhm1:1,mhm2:1,mlpa:1,mp4a:1,"raw ":1,Opus:1,opus:1,samr:1,sawb:1,sawp:1,sevc:1,sqcp:1,ssmv:1,twos:1,ulaw:1},video:{avc1:1,avc2:1,avc3:1,avc4:1,avcp:1,av01:.8,dav1:.8,drac:1,dva1:1,dvav:1,dvh1:.7,dvhe:.7,encv:1,hev1:.75,hvc1:.75,mjp2:1,mp4v:1,mvc1:1,mvc2:1,mvc3:1,mvc4:1,resv:1,rv60:1,s263:1,svc1:1,svc2:1,"vc-1":1,vp08:1,vp09:.9},text:{stpp:1,wvtt:1}};function wu(s,e){let t=ar[e];return !!t&&!!t[s.slice(0,4)]}function gn(s,e,t=true){return !s.split(",").some(i=>!Ou(i,e,t))}function Ou(s,e,t=true){var i;let r=Fi(t);return (i=r?.isTypeSupported(pn(s,e)))!=null?i:false}function pn(s,e){return `${e}/mp4;codecs=${s}`}function vm(s){if(s){let e=s.substring(0,4);return ar.video[e]}return 2}function Go(s){let e=wg();return s.split(",").reduce((t,i)=>{let n=e&&hl(i)?9:ar.video[i];return n?(n*2+t)/(t?3:2):(ar.audio[i]+t)/(t?2:1)},0)}var qd={};function ET(s,e=true){if(qd[s])return qd[s];let t={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"],"mp4a.40.34":["mp3"]}[s];for(let r=0;r<t.length;r++){var i;if(Ou(t[r],"audio",e))return qd[s]=t[r],t[r];if(t[r]==="mp3"&&(i=Fi(e))!=null&&i.isTypeSupported("audio/mpeg"))return ""}return s}var vT=/flac|opus|mp4a\.40\.34/i;function Ho(s,e=true){return s.replace(vT,t=>ET(t.toLowerCase(),e))}function TT(s,e){let t=[];if(s){let i=s.split(",");for(let r=0;r<i.length;r++)wu(i[r],"video")||t.push(i[r]);}return e&&t.push(e),t.join(",")}function Po(s,e){if(s&&(s.length>4||["ac-3","ec-3","alac","fLaC","Opus"].indexOf(s)!==-1)&&(Tm(s,"audio")||Tm(s,"video")))return s;if(e){let t=e.split(",");if(t.length>1){if(s){for(let i=t.length;i--;)if(t[i].substring(0,4)===s.substring(0,4))return t[i]}return t[0]}}return e||s}function Tm(s,e){return wu(s,e)&&Ou(s,e)}function yT(s){let e=s.split(",");for(let t=0;t<e.length;t++){let i=e[t].split(".");i.length>2&&i[0]==="avc1"&&(e[t]=`avc1.${parseInt(i[1]).toString(16)}${("000"+parseInt(i[2]).toString(16)).slice(-4)}`);}return e.join(",")}function ST(s){if(s.startsWith("av01.")){let e=s.split("."),t=["0","111","01","01","01","0"];for(let i=e.length;i>4&&i<10;i++)e[i]=t[i-4];return e.join(".")}return s}function ym(s){let e=Fi(s)||{isTypeSupported:()=>false};return {mpeg:e.isTypeSupported("audio/mpeg"),mp3:e.isTypeSupported('audio/mp4; codecs="mp3"'),ac3:e.isTypeSupported('audio/mp4; codecs="ac-3"')}}function Ec(s){return s.replace(/^.+codecs=["']?([^"']+).*$/,"$1")}var AT={supported:true,powerEfficient:true,smooth:true},bT={supported:false,smooth:false,powerEfficient:false},Og={supported:true,configurations:[],decodingInfoResults:[AT]};function Fg(s,e){return {supported:false,configurations:e,decodingInfoResults:[bT],error:s}}function _T(s,e,t,i,r,n){let a=s.videoCodec,o=s.audioCodec?s.audioGroups:null,l=n?.audioCodec,d=n?.channels,c=d?parseInt(d):l?1/0:2,u=null;if(o!=null&&o.length)try{o.length===1&&o[0]?u=e.groups[o[0]].channels:u=o.reduce((h,f)=>{if(f){let m=e.groups[f];if(!m)throw new Error(`Audio track group ${f} not found`);Object.keys(m.channels).forEach(p=>{h[p]=(h[p]||0)+m.channels[p];});}return h},{2:0});}catch{return true}return a!==void 0&&(a.split(",").some(h=>hl(h))||s.width>1920&&s.height>1088||s.height>1920&&s.width>1088||s.frameRate>Math.max(i,30)||s.videoRange!=="SDR"&&s.videoRange!==t||s.bitrate>Math.max(r,8e6))||!!u&&G(c)&&Object.keys(u).some(h=>parseInt(h)>c)}function Ng(s,e,t,i={}){let r=s.videoCodec;if(!r&&!s.audioCodec||!t)return Promise.resolve(Og);let n=[],a=IT(s),o=a.length,l=LT(s,e,o>0),d=l.length;for(let c=o||1*d||1;c--;){let u={type:"media-source"};if(o&&(u.video=a[c%o]),d){u.audio=l[c%d];let h=u.audio.bitrate;u.video&&h&&(u.video.bitrate-=h);}n.push(u);}if(r){let c=navigator.userAgent;if(r.split(",").some(u=>hl(u))&&wg())return Promise.resolve(Fg(new Error(`Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent string: (${c})`),n))}return Promise.all(n.map(c=>{let u=RT(c);return i[u]||(i[u]=t.decodingInfo(c))})).then(c=>({supported:!c.some(u=>!u.supported),configurations:n,decodingInfoResults:c})).catch(c=>({supported:false,configurations:n,decodingInfoResults:[],error:c}))}function IT(s){var e;let t=(e=s.videoCodec)==null?void 0:e.split(","),i=Ug(s),r=s.width||640,n=s.height||480,a=s.frameRate||30,o=s.videoRange.toLowerCase();return t?t.map(l=>{let d={contentType:pn(ST(l),"video"),width:r,height:n,bitrate:i,framerate:a};return o!=="sdr"&&(d.transferFunction=o),d}):[]}function LT(s,e,t){var i;let r=(i=s.audioCodec)==null?void 0:i.split(","),n=Ug(s);return r&&s.audioGroups?s.audioGroups.reduce((a,o)=>{var l;let d=o?(l=e.groups[o])==null?void 0:l.tracks:null;return d?d.reduce((c,u)=>{if(u.groupId===o){let h=parseFloat(u.channels||"");r.forEach(f=>{let m={contentType:pn(f,"audio"),bitrate:t?xT(f,n):n};h&&(m.channels=""+h),c.push(m);});}return c},a):a},[]):[]}function xT(s,e){if(e<=1)return 1;let t=128e3;return s==="ec-3"?t=768e3:s==="ac-3"&&(t=64e4),Math.min(e/2,t)}function Ug(s){return Math.ceil(Math.max(s.bitrate*.9,s.averageBitrate)/1e3)*1e3||1}function RT(s){let e="",{audio:t,video:i}=s;if(i){let r=Ec(i.contentType);e+=`${r}_r${i.height}x${i.width}f${Math.ceil(i.framerate)}${i.transferFunction||"sd"}_${Math.ceil(i.bitrate/1e5)}`;}if(t){let r=Ec(t.contentType);e+=`${i?"_":""}${r}_c${t.channels}`;}return e}var vc=["NONE","TYPE-0","TYPE-1",null];function kT(s){return vc.indexOf(s)>-1}var Ko=["SDR","PQ","HLG"];function DT(s){return !!s&&Ko.indexOf(s)>-1}var wo={No:"",Yes:"YES",v2:"v2"};function Sm(s){let{canSkipUntil:e,canSkipDateRanges:t,age:i}=s,r=i<e/2;return e&&r?t?wo.v2:wo.Yes:wo.No}var Vo=class{constructor(e,t,i){this.msn=void 0,this.part=void 0,this.skip=void 0,this.msn=e,this.part=t,this.skip=i;}addDirectives(e){let t=new self.URL(e);return this.msn!==void 0&&t.searchParams.set("_HLS_msn",this.msn.toString()),this.part!==void 0&&t.searchParams.set("_HLS_part",this.part.toString()),this.skip&&t.searchParams.set("_HLS_skip",this.skip),t.href}},ds=class{constructor(e){if(this._attrs=void 0,this.audioCodec=void 0,this.bitrate=void 0,this.codecSet=void 0,this.url=void 0,this.frameRate=void 0,this.height=void 0,this.id=void 0,this.name=void 0,this.supplemental=void 0,this.videoCodec=void 0,this.width=void 0,this.details=void 0,this.fragmentError=0,this.loadError=0,this.loaded=void 0,this.realBitrate=0,this.supportedPromise=void 0,this.supportedResult=void 0,this._avgBitrate=0,this._audioGroups=void 0,this._subtitleGroups=void 0,this._urlId=0,this.url=[e.url],this._attrs=[e.attrs],this.bitrate=e.bitrate,e.details&&(this.details=e.details),this.id=e.id||0,this.name=e.name,this.width=e.width||0,this.height=e.height||0,this.frameRate=e.attrs.optionalFloat("FRAME-RATE",0),this._avgBitrate=e.attrs.decimalInteger("AVERAGE-BANDWIDTH"),this.audioCodec=e.audioCodec,this.videoCodec=e.videoCodec,this.codecSet=[e.videoCodec,e.audioCodec].filter(i=>!!i).map(i=>i.substring(0,4)).join(","),"supplemental"in e){var t;this.supplemental=e.supplemental;let i=(t=e.supplemental)==null?void 0:t.videoCodec;i&&i!==e.videoCodec&&(this.codecSet+=`,${i.substring(0,4)}`);}this.addGroupId("audio",e.attrs.AUDIO),this.addGroupId("text",e.attrs.SUBTITLES);}get maxBitrate(){return Math.max(this.realBitrate,this.bitrate)}get averageBitrate(){return this._avgBitrate||this.realBitrate||this.bitrate}get attrs(){return this._attrs[0]}get codecs(){return this.attrs.CODECS||""}get pathwayId(){return this.attrs["PATHWAY-ID"]||"."}get videoRange(){return this.attrs["VIDEO-RANGE"]||"SDR"}get score(){return this.attrs.optionalFloat("SCORE",0)}get uri(){return this.url[0]||""}hasAudioGroup(e){return Am(this._audioGroups,e)}hasSubtitleGroup(e){return Am(this._subtitleGroups,e)}get audioGroups(){return this._audioGroups}get subtitleGroups(){return this._subtitleGroups}addGroupId(e,t){if(t){if(e==="audio"){let i=this._audioGroups;i||(i=this._audioGroups=[]),i.indexOf(t)===-1&&i.push(t);}else if(e==="text"){let i=this._subtitleGroups;i||(i=this._subtitleGroups=[]),i.indexOf(t)===-1&&i.push(t);}}}get urlId(){return 0}set urlId(e){}get audioGroupIds(){return this.audioGroups?[this.audioGroupId]:void 0}get textGroupIds(){return this.subtitleGroups?[this.textGroupId]:void 0}get audioGroupId(){var e;return (e=this.audioGroups)==null?void 0:e[0]}get textGroupId(){var e;return (e=this.subtitleGroups)==null?void 0:e[0]}addFallback(){}};function Am(s,e){return !e||!s?false:s.indexOf(e)!==-1}function CT(){if(typeof matchMedia=="function"){let s=matchMedia("(dynamic-range: high)"),e=matchMedia("bad query");if(s.media!==e.media)return s.matches===true}return false}function MT(s,e){let t=false,i=[];if(s&&(t=s!=="SDR",i=[s]),e){i=e.allowedVideoRanges||Ko.slice(0);let r=i.join("")!=="SDR"&&!e.videoCodec;t=e.preferHDR!==void 0?e.preferHDR:r&&CT(),t||(i=["SDR"]);}return {preferHDR:t,allowedVideoRanges:i}}var PT=s=>{let e=new WeakSet;return (t,i)=>{if(s&&(i=s(t,i)),typeof i=="object"&&i!==null){if(e.has(i))return;e.add(i);}return i}},Ae=(s,e)=>JSON.stringify(s,PT(e));function wT(s,e,t,i,r){let n=Object.keys(s),a=i?.channels,o=i?.audioCodec,l=r?.videoCodec,d=a&&parseInt(a)===2,c=false,u=false,h=1/0,f=1/0,m=1/0,p=1/0,E=0,v=[],{preferHDR:T,allowedVideoRanges:S}=MT(e,r);for(let k=n.length;k--;){let R=s[n[k]];c||(c=R.channels[2]>0),h=Math.min(h,R.minHeight),f=Math.min(f,R.minFramerate),m=Math.min(m,R.minBitrate),S.filter(M=>R.videoRanges[M]>0).length>0&&(u=true);}h=G(h)?h:0,f=G(f)?f:0;let A=Math.max(1080,h),b=Math.max(30,f);m=G(m)?m:t,t=Math.max(m,t),u||(e=void 0);let D=n.length>1;return {codecSet:n.reduce((k,R)=>{let L=s[R];if(R===k)return k;if(v=u?S.filter(M=>L.videoRanges[M]>0):[],D){if(L.minBitrate>t)return ni(R,`min bitrate of ${L.minBitrate} > current estimate of ${t}`),k;if(!L.hasDefaultAudio)return ni(R,"no renditions with default or auto-select sound found"),k;if(o&&R.indexOf(o.substring(0,4))%5!==0)return ni(R,`audio codec preference "${o}" not found`),k;if(a&&!d){if(!L.channels[a])return ni(R,`no renditions with ${a} channel sound found (channels options: ${Object.keys(L.channels)})`),k}else if((!o||d)&&c&&L.channels[2]===0)return ni(R,"no renditions with stereo sound found"),k;if(L.minHeight>A)return ni(R,`min resolution of ${L.minHeight} > maximum of ${A}`),k;if(L.minFramerate>b)return ni(R,`min framerate of ${L.minFramerate} > maximum of ${b}`),k;if(!v.some(M=>L.videoRanges[M]>0))return ni(R,`no variants with VIDEO-RANGE of ${Ae(v)} found`),k;if(l&&R.indexOf(l.substring(0,4))%5!==0)return ni(R,`video codec preference "${l}" not found`),k;if(L.maxScore<E)return ni(R,`max score of ${L.maxScore} < selected max of ${E}`),k}return k&&(Go(R)>=Go(k)||L.fragmentError>s[k].fragmentError)?k:(p=L.minIndex,E=L.maxScore,R)},void 0),videoRanges:v,preferHDR:T,minFramerate:f,minBitrate:m,minIndex:p}}function ni(s,e){Te.log(`[abr] start candidates with "${s}" ignored because ${e}`);}function Bg(s){return s.reduce((e,t)=>{let i=e.groups[t.groupId];i||(i=e.groups[t.groupId]={tracks:[],channels:{2:0},hasDefault:false,hasAutoSelect:false}),i.tracks.push(t);let r=t.channels||"2";return i.channels[r]=(i.channels[r]||0)+1,i.hasDefault=i.hasDefault||t.default,i.hasAutoSelect=i.hasAutoSelect||t.autoselect,i.hasDefault&&(e.hasDefaultAudio=true),i.hasAutoSelect&&(e.hasAutoSelectAudio=true),e},{hasDefaultAudio:false,hasAutoSelectAudio:false,groups:{}})}function OT(s,e,t,i){return s.slice(t,i+1).reduce((r,n,a)=>{if(!n.codecSet)return r;let o=n.audioGroups,l=r[n.codecSet];l||(r[n.codecSet]=l={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,minIndex:a,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!o,fragmentError:0}),l.minBitrate=Math.min(l.minBitrate,n.bitrate);let d=Math.min(n.height,n.width);return l.minHeight=Math.min(l.minHeight,d),l.minFramerate=Math.min(l.minFramerate,n.frameRate),l.minIndex=Math.min(l.minIndex,a),l.maxScore=Math.max(l.maxScore,n.score),l.fragmentError+=n.fragmentError,l.videoRanges[n.videoRange]=(l.videoRanges[n.videoRange]||0)+1,o&&o.forEach(c=>{if(!c)return;let u=e.groups[c];u&&(l.hasDefaultAudio=l.hasDefaultAudio||e.hasDefaultAudio?u.hasDefault:u.hasAutoSelect||!e.hasDefaultAudio&&!e.hasAutoSelectAudio,Object.keys(u.channels).forEach(h=>{l.channels[h]=(l.channels[h]||0)+u.channels[h];}));}),r},{})}function bm(s){if(!s)return s;let{lang:e,assocLang:t,characteristics:i,channels:r,audioCodec:n}=s;return {lang:e,assocLang:t,characteristics:i,channels:r,audioCodec:n}}function di(s,e,t){if("attrs"in s){let i=e.indexOf(s);if(i!==-1)return i}for(let i=0;i<e.length;i++){let r=e[i];if(os(s,r,t))return i}return -1}function os(s,e,t){let{groupId:i,name:r,lang:n,assocLang:a,default:o}=s,l=s.forced;return (i===void 0||e.groupId===i)&&(r===void 0||e.name===r)&&(n===void 0||FT(n,e.lang))&&(n===void 0||e.assocLang===a)&&(o===void 0||e.default===o)&&(l===void 0||e.forced===l)&&(!("characteristics"in s)||NT(s.characteristics||"",e.characteristics))&&(t===void 0||t(s,e))}function FT(s,e="--"){return s.length===e.length?s===e:s.startsWith(e)||e.startsWith(s)}function NT(s,e=""){let t=s.split(","),i=e.split(",");return t.length===i.length&&!t.some(r=>i.indexOf(r)===-1)}function ns(s,e){let{audioCodec:t,channels:i}=s;return (t===void 0||(e.audioCodec||"").substring(0,4)===t.substring(0,4))&&(i===void 0||i===(e.channels||"2"))}function UT(s,e,t,i,r){let n=e[i],o=e.reduce((h,f,m)=>{let p=f.uri;return (h[p]||(h[p]=[])).push(m),h},{})[n.uri];o.length>1&&(i=Math.max.apply(Math,o));let l=n.videoRange,d=n.frameRate,c=n.codecSet.substring(0,4),u=_m(e,i,h=>{if(h.videoRange!==l||h.frameRate!==d||h.codecSet.substring(0,4)!==c)return false;let f=h.audioGroups,m=t.filter(p=>!f||f.indexOf(p.groupId)!==-1);return di(s,m,r)>-1});return u>-1?u:_m(e,i,h=>{let f=h.audioGroups,m=t.filter(p=>!f||f.indexOf(p.groupId)!==-1);return di(s,m,r)>-1})}function _m(s,e,t){for(let i=e;i>-1;i--)if(t(s[i]))return i;for(let i=e+1;i<s.length;i++)if(t(s[i]))return i;return -1}function Wo(s,e){var t;return !!s&&s!==((t=e.loadLevelObj)==null?void 0:t.uri)}var Tc=class extends ht{constructor(e){super("abr",e.logger),this.hls=void 0,this.lastLevelLoadSec=0,this.lastLoadedFragLevel=-1,this.firstSelection=-1,this._nextAutoLevel=-1,this.nextAutoLevelKey="",this.audioTracksByGroup=null,this.codecTiers=null,this.timer=-1,this.fragCurrent=null,this.partCurrent=null,this.bitrateTestDelay=0,this.rebufferNotice=-1,this.supportedCache={},this.bwEstimator=void 0,this._abandonRulesCheck=t=>{var i;let{fragCurrent:r,partCurrent:n,hls:a}=this,{autoLevelEnabled:o,media:l}=a;if(!r||!l)return;let d=performance.now(),c=n?n.stats:r.stats,u=n?n.duration:r.duration,h=d-c.loading.start,f=a.minAutoLevel,m=r.level,p=this._nextAutoLevel;if(c.aborted||c.loaded&&c.loaded===c.total||m<=f){this.clearTimer(),this._nextAutoLevel=-1;return}if(!o)return;let E=p>-1&&p!==m,v=!!t||E;if(!v&&(l.paused||!l.playbackRate||!l.readyState))return;let T=a.mainForwardBufferInfo;if(!v&&T===null)return;let S=this.bwEstimator.getEstimateTTFB(),A=Math.abs(l.playbackRate);if(h<=Math.max(S,1e3*(u/(A*2))))return;let b=T?T.len/A:0,D=c.loading.first?c.loading.first-c.loading.start:-1,I=c.loaded&&D>-1,k=this.getBwEstimate(),R=a.levels,L=R[m],M=Math.max(c.loaded,Math.round(u*(r.bitrate||L.averageBitrate)/8)),B=I?h-D:h;B<1&&I&&(B=Math.min(h,c.loaded*8/k));let K=I?c.loaded*1e3/B:0,j=S/1e3,V=K?(M-c.loaded)/K:M*8/k+j;if(V<=b)return;let O=K?K*8:k,Y=((i=t?.details||this.hls.latestLevelDetails)==null?void 0:i.live)===true,$=this.hls.config.abrBandWidthUpFactor,q=Number.POSITIVE_INFINITY,Q;for(Q=m-1;Q>f;Q--){let ge=R[Q].maxBitrate,ie=!R[Q].details||Y;if(q=this.getTimeToLoadFrag(j,O,u*ge,ie),q<Math.min(b,u+j))break}if(q>=V||q>u*10)return;I?this.bwEstimator.sample(h-Math.min(S,D),c.loaded):this.bwEstimator.sampleTTFB(h);let N=R[Q].maxBitrate;this.getBwEstimate()*$>N&&this.resetEstimator(N);let U=this.findBestLevel(N,f,Q,0,b,1,1);U>-1&&(Q=U),this.warn(`Fragment ${r.sn}${n?" part "+n.index:""} of level ${m} is loading too slowly;
1350
1350
  Fragment duration: ${r.duration.toFixed(3)}
1351
1351
  Time to underbuffer: ${b.toFixed(3)} s
1352
- Estimated load time for current fragment: ${K.toFixed(3)} s
1352
+ Estimated load time for current fragment: ${V.toFixed(3)} s
1353
1353
  Estimated load time for down switch fragment: ${q.toFixed(3)} s
1354
1354
  TTFB estimate: ${D|0} ms
1355
1355
  Current BW estimate: ${G(k)?k|0:"Unknown"} bps
1356
1356
  New BW estimate: ${this.getBwEstimate()|0} bps
1357
1357
  Switching to level ${Q} @ ${N|0} bps`),a.nextLoadLevel=a.nextAutoLevel=Q,this.clearTimer();let te=()=>{if(this.clearTimer(),this.fragCurrent===r&&this.hls.loadLevel===Q&&Q>0){let ge=this.getStarvationDelay();if(this.warn(`Aborting inflight request ${Q>0?"and switching down":""}
1358
1358
  Fragment duration: ${r.duration.toFixed(3)} s
1359
- Time to underbuffer: ${ge.toFixed(3)} s`),r.abortRequests(),this.fragCurrent=this.partCurrent=null,Q>f){let ie=this.findBestLevel(this.hls.levels[f].bitrate,f,Q,0,ge,1,1);ie===-1&&(ie=f),this.hls.nextLoadLevel=this.hls.nextAutoLevel=ie,this.resetEstimator(this.hls.levels[ie].bitrate);}}};E||K>q*2?te():this.timer=self.setInterval(te,q*1e3),a.trigger(g.FRAG_LOAD_EMERGENCY_ABORTED,{frag:r,part:n,stats:c});},this.hls=e,this.bwEstimator=this.initEstimator(),this.registerListeners();}resetEstimator(e){e&&(this.log(`setting initial bwe to ${e}`),this.hls.config.abrEwmaDefaultEstimate=e),this.firstSelection=-1,this.bwEstimator=this.initEstimator();}initEstimator(){let e=this.hls.config;return new fc(e.abrEwmaSlowVoD,e.abrEwmaFastVoD,e.abrEwmaDefaultEstimate)}registerListeners(){let{hls:e}=this;e.on(g.MANIFEST_LOADING,this.onManifestLoading,this),e.on(g.FRAG_LOADING,this.onFragLoading,this),e.on(g.FRAG_LOADED,this.onFragLoaded,this),e.on(g.FRAG_BUFFERED,this.onFragBuffered,this),e.on(g.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(g.LEVEL_LOADED,this.onLevelLoaded,this),e.on(g.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(g.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.on(g.ERROR,this.onError,this);}unregisterListeners(){let{hls:e}=this;e&&(e.off(g.MANIFEST_LOADING,this.onManifestLoading,this),e.off(g.FRAG_LOADING,this.onFragLoading,this),e.off(g.FRAG_LOADED,this.onFragLoaded,this),e.off(g.FRAG_BUFFERED,this.onFragBuffered,this),e.off(g.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(g.LEVEL_LOADED,this.onLevelLoaded,this),e.off(g.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(g.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.off(g.ERROR,this.onError,this));}destroy(){this.unregisterListeners(),this.clearTimer(),this.hls=this._abandonRulesCheck=this.supportedCache=null,this.fragCurrent=this.partCurrent=null;}onManifestLoading(e,t){this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.lastLevelLoadSec=0,this.supportedCache={},this.fragCurrent=this.partCurrent=null,this.onLevelsUpdated(),this.clearTimer();}onLevelsUpdated(){this.lastLoadedFragLevel>-1&&this.fragCurrent&&(this.lastLoadedFragLevel=this.fragCurrent.level),this._nextAutoLevel=-1,this.onMaxAutoLevelUpdated(),this.codecTiers=null,this.audioTracksByGroup=null;}onMaxAutoLevelUpdated(){this.firstSelection=-1,this.nextAutoLevelKey="";}onFragLoading(e,t){let i=t.frag;if(!this.ignoreFragment(i)){if(!i.bitrateTest){var r;this.fragCurrent=i,this.partCurrent=(r=t.part)!=null?r:null;}this.clearTimer(),this.timer=self.setInterval(this._abandonRulesCheck,100);}}onLevelSwitching(e,t){this.clearTimer();}onError(e,t){if(!t.fatal)switch(t.details){case x.BUFFER_ADD_CODEC_ERROR:case x.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case x.FRAG_LOAD_TIMEOUT:{let i=t.frag,{fragCurrent:r,partCurrent:n}=this;if(i&&r&&i.sn===r.sn&&i.level===r.level){let a=performance.now(),o=n?n.stats:i.stats,l=a-o.loading.start,d=o.loading.first?o.loading.first-o.loading.start:-1;if(o.loaded&&d>-1){let u=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(l-Math.min(u,d),o.loaded);}else this.bwEstimator.sampleTTFB(l);}break}}}getTimeToLoadFrag(e,t,i,r){let n=e+i/t,a=r?e+this.lastLevelLoadSec:0;return n+a}onLevelLoaded(e,t){let i=this.hls.config,{loading:r}=t.stats,n=r.end-r.first;G(n)&&(this.lastLevelLoadSec=n/1e3),t.details.live?this.bwEstimator.update(i.abrEwmaSlowLive,i.abrEwmaFastLive):this.bwEstimator.update(i.abrEwmaSlowVoD,i.abrEwmaFastVoD),this.timer>-1&&this._abandonRulesCheck(t.levelInfo);}onFragLoaded(e,{frag:t,part:i}){let r=i?i.stats:t.stats;if(t.type===W.MAIN&&this.bwEstimator.sampleTTFB(r.loading.first-r.loading.start),!this.ignoreFragment(t)){if(this.clearTimer(),t.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,this.hls.config.abrMaxWithRealBitrate){let n=i?i.duration:t.duration,a=this.hls.levels[t.level],o=(a.loaded?a.loaded.bytes:0)+r.loaded,l=(a.loaded?a.loaded.duration:0)+n;a.loaded={bytes:o,duration:l},a.realBitrate=Math.round(8*o/l);}if(t.bitrateTest){let n={stats:r,frag:t,part:i,id:t.type};this.onFragBuffered(g.FRAG_BUFFERED,n),t.bitrateTest=false;}else this.lastLoadedFragLevel=t.level;}}onFragBuffered(e,t){let{frag:i,part:r}=t,n=r!=null&&r.stats.loaded?r.stats:i.stats;if(n.aborted||this.ignoreFragment(i))return;let a=n.parsing.end-n.loading.start-Math.min(n.loading.first-n.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(a,n.loaded),n.bwEstimate=this.getBwEstimate(),i.bitrateTest?this.bitrateTestDelay=a/1e3:this.bitrateTestDelay=0;}ignoreFragment(e){return e.type!==W.MAIN||e.sn==="initSegment"}clearTimer(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1);}get firstAutoLevel(){let{maxAutoLevel:e,minAutoLevel:t}=this.hls,i=this.getBwEstimate(),r=this.hls.config.maxStarvationDelay,n=this.findBestLevel(i,t,e,0,r,1,1);if(n>-1)return n;let a=this.hls.firstLevel,o=Math.min(Math.max(a,t),e);return this.warn(`Could not find best starting auto level. Defaulting to first in playlist ${a} clamped to ${o}`),o}get forcedAutoLevel(){return this.nextAutoLevelKey?-1:this._nextAutoLevel}get nextAutoLevel(){let e=this.forcedAutoLevel,i=this.bwEstimator.canEstimate(),r=this.lastLoadedFragLevel>-1;if(e!==-1&&(!i||!r||this.nextAutoLevelKey===this.getAutoLevelKey()))return e;let n=i&&r?this.getNextABRAutoLevel():this.firstAutoLevel;if(e!==-1){let a=this.hls.levels;if(a.length>Math.max(e,n)&&a[e].loadError<=a[n].loadError)return e}return this._nextAutoLevel=n,this.nextAutoLevelKey=this.getAutoLevelKey(),n}getAutoLevelKey(){return `${this.getBwEstimate()}_${this.getStarvationDelay().toFixed(2)}`}getNextABRAutoLevel(){let{fragCurrent:e,partCurrent:t,hls:i}=this;if(i.levels.length<=1)return i.loadLevel;let{maxAutoLevel:r,config:n,minAutoLevel:a}=i,o=t?t.duration:e?e.duration:0,l=this.getBwEstimate(),d=this.getStarvationDelay(),c=n.abrBandWidthFactor,u=n.abrBandWidthUpFactor;if(d){let E=this.findBestLevel(l,a,r,d,0,c,u);if(E>=0)return this.rebufferNotice=-1,E}let h=o?Math.min(o,n.maxStarvationDelay):n.maxStarvationDelay;if(!d){let E=this.bitrateTestDelay;E&&(h=(o?Math.min(o,n.maxLoadingDelay):n.maxLoadingDelay)-E,this.info(`bitrate test took ${Math.round(1e3*E)}ms, set first fragment max fetchDuration to ${Math.round(1e3*h)} ms`),c=u=1);}let f=this.findBestLevel(l,a,r,d,h,c,u);if(this.rebufferNotice!==f&&(this.rebufferNotice=f,this.info(`${d?"rebuffering expected":"buffer is empty"}, optimal quality level ${f}`)),f>-1)return f;let m=i.levels[a],p=i.loadLevelObj;return p&&m?.bitrate<p.bitrate?a:i.loadLevel}getStarvationDelay(){let e=this.hls,t=e.media;if(!t)return 1/0;let i=t&&t.playbackRate!==0?Math.abs(t.playbackRate):1,r=e.mainForwardBufferInfo;return (r?r.len:0)/i}getBwEstimate(){return this.bwEstimator.canEstimate()?this.bwEstimator.getEstimate():this.hls.config.abrEwmaDefaultEstimate}findBestLevel(e,t,i,r,n,a,o){var l;let d=r+n,c=this.lastLoadedFragLevel,u=c===-1?this.hls.firstLevel:c,{fragCurrent:h,partCurrent:f}=this,{levels:m,allAudioTracks:p,loadLevel:E,config:v}=this.hls;if(m.length===1)return 0;let T=m[u],S=!!((l=this.hls.latestLevelDetails)!=null&&l.live),A=E===-1||c===-1,b,D="SDR",I=T?.frameRate||0,{audioPreference:k,videoPreference:R}=v,L=this.audioTracksByGroup||(this.audioTracksByGroup=Ug(p)),M=-1;if(A){if(this.firstSelection!==-1)return this.firstSelection;let O=this.codecTiers||(this.codecTiers=wT(m,L,t,i)),Y=PT(O,D,e,k,R),{codecSet:$,videoRanges:q,minFramerate:Q,minBitrate:N,minIndex:U,preferHDR:te}=Y;M=U,b=$,D=te?q[q.length-1]:q[0],I=Q,e=Math.max(e,N),this.log(`picked start tier ${Ae(Y)}`);}else b=T?.codecSet,D=T?.videoRange;let B=f?f.duration:h?h.duration:0,H=this.bwEstimator.getEstimateTTFB()/1e3,j=[];for(let O=i;O>=t;O--){var K;let Y=m[O],$=O>u;if(!Y)continue;if(v.useMediaCapabilities&&!Y.supportedResult&&!Y.supportedPromise){let ie=navigator.mediaCapabilities;typeof ie?.decodingInfo=="function"&&bT(Y,L,D,I,e,k)?(Y.supportedPromise=Fg(Y,L,ie,this.supportedCache),Y.supportedPromise.then(de=>{if(!this.hls)return;Y.supportedResult=de;let Be=this.hls.levels,Fe=Be.indexOf(Y);de.error?this.warn(`MediaCapabilities decodingInfo error: "${de.error}" for level ${Fe} ${Ae(de)}`):de.supported?de.decodingInfoResults.some(tt=>tt.smooth===false||tt.powerEfficient===false)&&this.log(`MediaCapabilities decodingInfo for level ${Fe} not smooth or powerEfficient: ${Ae(de)}`):(this.warn(`Unsupported MediaCapabilities decodingInfo result for level ${Fe} ${Ae(de)}`),Fe>-1&&Be.length>1&&(this.log(`Removing unsupported level ${Fe}`),this.hls.removeLevel(Fe),this.hls.loadLevel===-1&&(this.hls.nextLoadLevel=0)));}).catch(de=>{this.warn(`Error handling MediaCapabilities decodingInfo: ${de}`);})):Y.supportedResult=wg;}if((b&&Y.codecSet!==b||D&&Y.videoRange!==D||$&&I>Y.frameRate||!$&&I>0&&I<Y.frameRate||(K=Y.supportedResult)!=null&&(K=K.decodingInfoResults)!=null&&K.some(ie=>ie.smooth===false))&&(!A||O!==M)){j.push(O);continue}let q=Y.details,Q=(f?q?.partTarget:q?.averagetargetduration)||B,N;$?N=o*e:N=a*e;let U=B&&r>=B*2&&n===0?Y.averageBitrate:Y.maxBitrate,te=this.getTimeToLoadFrag(H,N,U*Q,q===void 0);if(N>=U&&(O===c||Y.loadError===0&&Y.fragmentError===0)&&(te<=H||!G(te)||S&&!this.bitrateTestDelay||te<d)){let ie=this.forcedAutoLevel;return O!==E&&(ie===-1||ie!==E)&&(j.length&&this.trace(`Skipped level(s) ${j.join(",")} of ${i} max with CODECS and VIDEO-RANGE:"${m[j[0]].codecs}" ${m[j[0]].videoRange}; not compatible with "${b}" ${D}`),this.info(`switch candidate:${u}->${O} adjustedbw(${Math.round(N)})-bitrate=${Math.round(N-U)} ttfb:${H.toFixed(1)} avgDuration:${Q.toFixed(1)} maxFetchDuration:${d.toFixed(1)} fetchDuration:${te.toFixed(1)} firstSelection:${A} codecSet:${Y.codecSet} videoRange:${Y.videoRange} hls.loadLevel:${E}`)),A&&(this.firstSelection=O),O}}return -1}set nextAutoLevel(e){let t=this.deriveNextAutoLevel(e);this._nextAutoLevel!==t&&(this.nextAutoLevelKey="",this._nextAutoLevel=t);}deriveNextAutoLevel(e){let{maxAutoLevel:t,minAutoLevel:i}=this.hls;return Math.min(Math.max(e,i),t)}},Bg={search:function(s,e){let t=0,i=s.length-1,r=null,n=null;for(;t<=i;){r=(t+i)/2|0,n=s[r];let a=e(n);if(a>0)t=r+1;else if(a<0)i=r-1;else return n}return null}};function UT(s,e,t){if(e===null||!Array.isArray(s)||!s.length||!G(e))return null;let i=s[0].programDateTime;if(e<(i||0))return null;let r=s[s.length-1].endProgramDateTime;if(e>=(r||0))return null;for(let n=0;n<s.length;++n){let a=s[n];if($T(e,t,a))return a}return null}function cs(s,e,t=0,i=0,r=.005){let n=null;if(s){n=e[1+s.sn-e[0].sn]||null;let o=s.endDTS-t;o>0&&o<15e-7&&(t+=15e-7),n&&s.level!==n.level&&n.end<=s.end&&(n=e[2+s.sn-e[0].sn]||null);}else t===0&&e[0].start===0&&(n=e[0]);if(n&&((!s||s.level===n.level)&&_m(t,i,n)===0||BT(n,s,Math.min(r,i))))return n;let a=Bg.search(e,_m.bind(null,t,i));return a&&(a!==s||!n)?a:n}function BT(s,e,t){if(e&&e.start===0&&e.level<s.level&&(e.endPTS||0)>0){let i=e.tagList.reduce((r,n)=>(n[0]==="INF"&&(r+=parseFloat(n[1])),r),t);return s.start<=i}return false}function _m(s=0,e=0,t){if(t.start<=s&&t.start+t.duration>s)return 0;let i=Math.min(e,t.duration+(t.deltaPTS?t.deltaPTS:0));return t.start+t.duration-i<=s?1:t.start-i>s&&t.start?-1:0}function $T(s,e,t){let i=Math.min(e,t.duration+(t.deltaPTS?t.deltaPTS:0))*1e3;return (t.endProgramDateTime||0)-i>s}function $g(s,e,t){if(s&&s.startCC<=e&&s.endCC>=e){let i=s.fragments,{fragmentHint:r}=s;r&&(i=i.concat(r));let n;return Bg.search(i,a=>a.cc<e?1:a.cc>e?-1:(n=a,a.end<=t?1:a.start>t?-1:0)),n||null}return null}function Yo(s){switch(s.details){case x.FRAG_LOAD_TIMEOUT:case x.KEY_LOAD_TIMEOUT:case x.LEVEL_LOAD_TIMEOUT:case x.MANIFEST_LOAD_TIMEOUT:return true}return false}function Gg(s){return s.details.startsWith("key")}function Hg(s){return Gg(s)&&!!s.frag&&!s.frag.decryptdata}function Im(s,e){let t=Yo(e);return s.default[`${t?"timeout":"error"}Retry`]}function Fu(s,e){let t=s.backoff==="linear"?1:Math.pow(2,e);return Math.min(t*s.retryDelayMs,s.maxRetryDelayMs)}function Lm(s){return ve(ve({},s),{errorRetry:null,timeoutRetry:null})}function qo(s,e,t,i){if(!s)return false;let r=i?.code,n=e<s.maxNumRetry&&(GT(r)||!!t);return s.shouldRetry?s.shouldRetry(s,e,t,i,n):n}function GT(s){return yc(s)||!!s&&(s<400||s>499)}function yc(s){return s===0&&navigator.onLine===false}var ze={DoNothing:0,SendAlternateToPenaltyBox:2,RemoveAlternatePermanently:3,RetryRequest:5},yt={None:0,MoveAllAlternatesMatchingHost:1,MoveAllAlternatesMatchingHDCP:2,MoveAllAlternatesMatchingKey:4},Sc=class extends ht{constructor(e){super("error-controller",e.logger),this.hls=void 0,this.playlistError=0,this.hls=e,this.registerListeners();}registerListeners(){let e=this.hls;e.on(g.ERROR,this.onError,this),e.on(g.MANIFEST_LOADING,this.onManifestLoading,this),e.on(g.LEVEL_UPDATED,this.onLevelUpdated,this);}unregisterListeners(){let e=this.hls;e&&(e.off(g.ERROR,this.onError,this),e.off(g.ERROR,this.onErrorOut,this),e.off(g.MANIFEST_LOADING,this.onManifestLoading,this),e.off(g.LEVEL_UPDATED,this.onLevelUpdated,this));}destroy(){this.unregisterListeners(),this.hls=null;}startLoad(e){}stopLoad(){this.playlistError=0;}getVariantLevelIndex(e){return e?.type===W.MAIN?e.level:this.getVariantIndex()}getVariantIndex(){var e;let t=this.hls,i=t.currentLevel;return (e=t.loadLevelObj)!=null&&e.details||i===-1?t.loadLevel:i}variantHasKey(e,t){if(e){var i;if((i=e.details)!=null&&i.hasKey(t))return true;let r=e.audioGroups;if(r)return this.hls.allAudioTracks.filter(a=>r.indexOf(a.groupId)>=0).some(a=>{var o;return (o=a.details)==null?void 0:o.hasKey(t)})}return false}onManifestLoading(){this.playlistError=0;}onLevelUpdated(){this.playlistError=0;}onError(e,t){var i;if(t.fatal)return;let r=this.hls,n=t.context;switch(t.details){case x.FRAG_LOAD_ERROR:case x.FRAG_LOAD_TIMEOUT:case x.KEY_LOAD_ERROR:case x.KEY_LOAD_TIMEOUT:t.errorAction=this.getFragRetryOrSwitchAction(t);return;case x.FRAG_PARSING_ERROR:if((i=t.frag)!=null&&i.gap){t.errorAction=ir();return}case x.FRAG_GAP:case x.FRAG_DECRYPT_ERROR:{t.errorAction=this.getFragRetryOrSwitchAction(t),t.errorAction.action=ze.SendAlternateToPenaltyBox;return}case x.LEVEL_EMPTY_ERROR:case x.LEVEL_PARSING_ERROR:{var a;let l=t.parent===W.MAIN?t.level:r.loadLevel;t.details===x.LEVEL_EMPTY_ERROR&&((a=t.context)!=null&&(a=a.levelDetails)!=null&&a.live)?t.errorAction=this.getPlaylistRetryOrSwitchAction(t,l):(t.levelRetry=false,t.errorAction=this.getLevelSwitchAction(t,l));}return;case x.LEVEL_LOAD_ERROR:case x.LEVEL_LOAD_TIMEOUT:typeof n?.level=="number"&&(t.errorAction=this.getPlaylistRetryOrSwitchAction(t,n.level));return;case x.AUDIO_TRACK_LOAD_ERROR:case x.AUDIO_TRACK_LOAD_TIMEOUT:case x.SUBTITLE_LOAD_ERROR:case x.SUBTITLE_TRACK_LOAD_TIMEOUT:if(n){let l=r.loadLevelObj;if(l&&(n.type===ce.AUDIO_TRACK&&l.hasAudioGroup(n.groupId)||n.type===ce.SUBTITLE_TRACK&&l.hasSubtitleGroup(n.groupId))){t.errorAction=this.getPlaylistRetryOrSwitchAction(t,r.loadLevel),t.errorAction.action=ze.SendAlternateToPenaltyBox,t.errorAction.flags=yt.MoveAllAlternatesMatchingHost;return}}return;case x.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:t.errorAction={action:ze.SendAlternateToPenaltyBox,flags:yt.MoveAllAlternatesMatchingHDCP};return;case x.KEY_SYSTEM_SESSION_UPDATE_FAILED:case x.KEY_SYSTEM_STATUS_INTERNAL_ERROR:case x.KEY_SYSTEM_NO_SESSION:t.errorAction={action:ze.SendAlternateToPenaltyBox,flags:yt.MoveAllAlternatesMatchingKey};return;case x.BUFFER_ADD_CODEC_ERROR:case x.REMUX_ALLOC_ERROR:case x.BUFFER_APPEND_ERROR:if(!t.errorAction){var o;t.errorAction=this.getLevelSwitchAction(t,(o=t.level)!=null?o:r.loadLevel);}return;case x.INTERNAL_EXCEPTION:case x.BUFFER_APPENDING_ERROR:case x.BUFFER_FULL_ERROR:case x.LEVEL_SWITCH_ERROR:case x.BUFFER_STALLED_ERROR:case x.BUFFER_SEEK_OVER_HOLE:case x.BUFFER_NUDGE_ON_STALL:t.errorAction=ir();return}t.type===z.KEY_SYSTEM_ERROR&&(t.levelRetry=false,t.errorAction=ir());}getPlaylistRetryOrSwitchAction(e,t){let i=this.hls,r=Im(i.config.playlistLoadPolicy,e),n=this.playlistError++;if(qo(r,n,Yo(e),e.response))return {action:ze.RetryRequest,flags:yt.None,retryConfig:r,retryCount:n};let o=this.getLevelSwitchAction(e,t);return r&&(o.retryConfig=r,o.retryCount=n),o}getFragRetryOrSwitchAction(e){let t=this.hls,i=this.getVariantLevelIndex(e.frag),r=t.levels[i],{fragLoadPolicy:n,keyLoadPolicy:a}=t.config,o=Im(Gg(e)?a:n,e),l=t.levels.reduce((c,u)=>c+u.fragmentError,0);if(r&&(e.details!==x.FRAG_GAP&&r.fragmentError++,!Hg(e)&&qo(o,l,Yo(e),e.response)))return {action:ze.RetryRequest,flags:yt.None,retryConfig:o,retryCount:l};let d=this.getLevelSwitchAction(e,i);return o&&(d.retryConfig=o,d.retryCount=l),d}getLevelSwitchAction(e,t){let i=this.hls;t==null&&(t=i.loadLevel);let r=this.hls.levels[t];if(r){var n,a;let d=e.details;r.loadError++,d===x.BUFFER_APPEND_ERROR&&r.fragmentError++;let c=-1,{levels:u,loadLevel:h,minAutoLevel:f,maxAutoLevel:m}=i;!i.autoLevelEnabled&&!i.config.preserveManualLevelOnError&&(i.loadLevel=-1);let p=(n=e.frag)==null?void 0:n.type,v=(p===W.AUDIO&&d===x.FRAG_PARSING_ERROR||e.sourceBufferName==="audio"&&(d===x.BUFFER_ADD_CODEC_ERROR||d===x.BUFFER_APPEND_ERROR))&&u.some(({audioCodec:D})=>r.audioCodec!==D),S=e.sourceBufferName==="video"&&(d===x.BUFFER_ADD_CODEC_ERROR||d===x.BUFFER_APPEND_ERROR)&&u.some(({codecSet:D,audioCodec:I})=>r.codecSet!==D&&r.audioCodec===I),{type:A,groupId:b}=(a=e.context)!=null?a:{};for(let D=u.length;D--;){let I=(D+h)%u.length;if(I!==h&&I>=f&&I<=m&&u[I].loadError===0){var o,l;let k=u[I];if(d===x.FRAG_GAP&&p===W.MAIN&&e.frag){let R=u[I].details;if(R){let L=cs(e.frag,R.fragments,e.frag.start);if(L!=null&&L.gap)continue}}else {if(A===ce.AUDIO_TRACK&&k.hasAudioGroup(b)||A===ce.SUBTITLE_TRACK&&k.hasSubtitleGroup(b))continue;if(p===W.AUDIO&&(o=r.audioGroups)!=null&&o.some(R=>k.hasAudioGroup(R))||p===W.SUBTITLE&&(l=r.subtitleGroups)!=null&&l.some(R=>k.hasSubtitleGroup(R))||v&&r.audioCodec===k.audioCodec||S&&r.codecSet===k.codecSet||!v&&r.codecSet!==k.codecSet)continue}c=I;break}}if(c>-1&&i.loadLevel!==c)return e.levelRetry=true,this.playlistError=0,{action:ze.SendAlternateToPenaltyBox,flags:yt.None,nextAutoLevel:c}}return {action:ze.SendAlternateToPenaltyBox,flags:yt.MoveAllAlternatesMatchingHost}}onErrorOut(e,t){var i;switch((i=t.errorAction)==null?void 0:i.action){case ze.DoNothing:break;case ze.SendAlternateToPenaltyBox:this.sendAlternateToPenaltyBox(t),!t.errorAction.resolved&&t.details!==x.FRAG_GAP?t.fatal=true:/MediaSource readyState: ended/.test(t.error.message)&&(this.warn(`MediaSource ended after "${t.sourceBufferName}" sourceBuffer append error. Attempting to recover from media error.`),this.hls.recoverMediaError());break;}if(t.fatal){this.hls.stopLoad();return}}sendAlternateToPenaltyBox(e){let t=this.hls,i=e.errorAction;if(!i)return;let{flags:r}=i,n=i.nextAutoLevel;switch(r){case yt.None:this.switchLevel(e,n);break;case yt.MoveAllAlternatesMatchingHDCP:{let l=this.getVariantLevelIndex(e.frag),d=t.levels[l],c=d?.attrs["HDCP-LEVEL"];if(i.hdcpLevel=c,c==="NONE")this.warn("HDCP policy resticted output with HDCP-LEVEL=NONE");else if(c){t.maxHdcpLevel=vc[vc.indexOf(c)-1],i.resolved=true,this.warn(`Restricting playback to HDCP-LEVEL of "${t.maxHdcpLevel}" or lower`);break}}case yt.MoveAllAlternatesMatchingKey:{let l=e.decryptdata;if(l){let d=this.hls.levels,c=d.length;for(let h=c;h--;)if(this.variantHasKey(d[h],l)){var a,o;this.log(`Banned key found in level ${h} (${d[h].bitrate}bps) or audio group "${(a=d[h].audioGroups)==null?void 0:a.join(",")}" (${(o=e.frag)==null?void 0:o.type} fragment) ${rt(l.keyId||[])}`),d[h].fragmentError++,d[h].loadError++,this.log(`Removing level ${h} with key error (${e.error})`),this.hls.removeLevel(h);}let u=e.frag;if(this.hls.levels.length<c)i.resolved=true;else if(u&&u.type!==W.MAIN){let h=u.decryptdata;h&&!l.matches(h)&&(i.resolved=true);}}break}}i.resolved||this.switchLevel(e,n);}switchLevel(e,t){if(t!==void 0&&e.errorAction&&(this.warn(`switching to level ${t} after ${e.details}`),this.hls.nextAutoLevel=t,e.errorAction.resolved=true,this.hls.nextLoadLevel=this.hls.nextAutoLevel,e.details===x.BUFFER_ADD_CODEC_ERROR&&e.mimeType&&e.sourceBufferName!=="audiovideo")){let i=Ec(e.mimeType),r=this.hls.levels;for(let n=r.length;n--;)r[n][`${e.sourceBufferName}Codec`]===i&&(this.log(`Removing level ${n} for ${e.details} ("${i}" not supported)`),this.hls.removeLevel(n));}}};function ir(s){let e={action:ze.DoNothing,flags:yt.None};return s&&(e.resolved=true),e}var Ke={NOT_LOADED:"NOT_LOADED",APPENDING:"APPENDING",PARTIAL:"PARTIAL",OK:"OK"},Ac=class{constructor(e){this.activePartLists=Object.create(null),this.endListFragments=Object.create(null),this.fragments=Object.create(null),this.timeRanges=Object.create(null),this.bufferPadding=.2,this.hls=void 0,this.hasGaps=false,this.hls=e,this._registerListeners();}_registerListeners(){let{hls:e}=this;e&&(e.on(g.MANIFEST_LOADING,this.onManifestLoading,this),e.on(g.BUFFER_APPENDED,this.onBufferAppended,this),e.on(g.FRAG_BUFFERED,this.onFragBuffered,this),e.on(g.FRAG_LOADED,this.onFragLoaded,this));}_unregisterListeners(){let{hls:e}=this;e&&(e.off(g.MANIFEST_LOADING,this.onManifestLoading,this),e.off(g.BUFFER_APPENDED,this.onBufferAppended,this),e.off(g.FRAG_BUFFERED,this.onFragBuffered,this),e.off(g.FRAG_LOADED,this.onFragLoaded,this));}destroy(){this._unregisterListeners(),this.hls=this.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null;}getAppendedFrag(e,t){let i=this.activePartLists[t];if(i)for(let r=i.length;r--;){let n=i[r];if(!n)break;if(n.start<=e&&e<=n.end&&n.loaded)return n}return this.getBufferedFrag(e,t)}getBufferedFrag(e,t){return this.getFragAtPos(e,t,true)}getFragAtPos(e,t,i){let{fragments:r}=this,n=Object.keys(r);for(let a=n.length;a--;){let o=r[n[a]];if(o?.body.type===t&&(!i||o.buffered)){let l=o.body;if(l.start<=e&&e<=l.end)return l}}return null}detectEvictedFragments(e,t,i,r,n){this.timeRanges&&(this.timeRanges[e]=t);let a=r?.fragment.sn||-1;Object.keys(this.fragments).forEach(o=>{let l=this.fragments[o];if(!l||a>=l.body.sn)return;if(!l.buffered&&(!l.loaded||n)){l.body.type===i&&this.removeFragment(l.body);return}let d=l.range[e];if(d){if(d.time.length===0){this.removeFragment(l.body);return}d.time.some(c=>{let u=!this.isTimeBuffered(c.startPTS,c.endPTS,t);return u&&this.removeFragment(l.body),u});}});}detectPartialFragments(e){let t=this.timeRanges;if(!t||e.frag.sn==="initSegment")return;let i=e.frag,r=Qs(i),n=this.fragments[r];if(!n||n.buffered&&i.gap)return;let a=!i.relurl;Object.keys(t).forEach(o=>{let l=i.elementaryStreams[o];if(!l)return;let d=t[o],c=a||l.partial===true;n.range[o]=this.getBufferedTimes(i,e.part,c,d);}),n.loaded=null,Object.keys(n.range).length?(n.buffered=true,(n.body.endList=i.endList||n.body.endList)&&(this.endListFragments[n.body.type]=n),yo(n)||this.removeParts(i.sn-1,i.type)):this.removeFragment(n.body);}removeParts(e,t){let i=this.activePartLists[t];i&&(this.activePartLists[t]=xm(i,r=>r.fragment.sn>=e));}fragBuffered(e,t){let i=Qs(e),r=this.fragments[i];!r&&t&&(r=this.fragments[i]={body:e,appendedPTS:null,loaded:null,buffered:false,range:Object.create(null)},e.gap&&(this.hasGaps=true)),r&&(r.loaded=null,r.buffered=true);}getBufferedTimes(e,t,i,r){let n={time:[],partial:i},a=e.start,o=e.end,l=e.minEndPTS||o,d=e.maxStartPTS||a;for(let c=0;c<r.length;c++){let u=r.start(c)-this.bufferPadding,h=r.end(c)+this.bufferPadding;if(d>=u&&l<=h){n.time.push({startPTS:Math.max(a,r.start(c)),endPTS:Math.min(o,r.end(c))});break}else if(a<h&&o>u){let f=Math.max(a,r.start(c)),m=Math.min(o,r.end(c));m>f&&(n.partial=true,n.time.push({startPTS:f,endPTS:m}));}else if(o<=u)break}return n}getPartialFragment(e){let t=null,i,r,n,a=0,{bufferPadding:o,fragments:l}=this;return Object.keys(l).forEach(d=>{let c=l[d];c&&yo(c)&&(r=c.body.start-o,n=c.body.end+o,e>=r&&e<=n&&(i=Math.min(e-r,n-e),a<=i&&(t=c.body,a=i)));}),t}isEndListAppended(e){let t=this.endListFragments[e];return t!==void 0&&(t.buffered||yo(t))}getState(e){let t=Qs(e),i=this.fragments[t];return i?i.buffered?yo(i)?Ke.PARTIAL:Ke.OK:Ke.APPENDING:Ke.NOT_LOADED}isTimeBuffered(e,t,i){let r,n;for(let a=0;a<i.length;a++){if(r=i.start(a)-this.bufferPadding,n=i.end(a)+this.bufferPadding,e>=r&&t<=n)return true;if(t<=r)return false}return false}onManifestLoading(){this.removeAllFragments();}onFragLoaded(e,t){if(t.frag.sn==="initSegment"||t.frag.bitrateTest)return;let i=t.frag,r=t.part?null:t,n=Qs(i);this.fragments[n]={body:i,appendedPTS:null,loaded:r,buffered:false,range:Object.create(null)};}onBufferAppended(e,t){let{frag:i,part:r,timeRanges:n,type:a}=t;if(i.sn==="initSegment")return;let o=i.type;if(r){let d=this.activePartLists[o];d||(this.activePartLists[o]=d=[]),d.push(r);}this.timeRanges=n;let l=n[a];this.detectEvictedFragments(a,l,o,r);}onFragBuffered(e,t){this.detectPartialFragments(t);}hasFragment(e){let t=Qs(e);return !!this.fragments[t]}hasFragments(e){let{fragments:t}=this,i=Object.keys(t);if(!e)return i.length>0;for(let r=i.length;r--;){let n=t[i[r]];if(n?.body.type===e)return true}return false}hasParts(e){var t;return !!((t=this.activePartLists[e])!=null&&t.length)}removeFragmentsInRange(e,t,i,r,n){r&&!this.hasGaps||Object.keys(this.fragments).forEach(a=>{let o=this.fragments[a];if(!o)return;let l=o.body;l.type!==i||r&&!l.gap||l.start<t&&l.end>e&&(o.buffered||n)&&this.removeFragment(l);});}removeFragment(e){let t=Qs(e);e.clearElementaryStreamInfo();let i=this.activePartLists[e.type];if(i){let r=e.sn;this.activePartLists[e.type]=xm(i,n=>n.fragment.sn!==r);}delete this.fragments[t],e.endList&&delete this.endListFragments[e.type];}removeAllFragments(){var e;this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=false;let t=(e=this.hls)==null||(e=e.latestLevelDetails)==null?void 0:e.partList;t&&t.forEach(i=>i.clearElementaryStreamInfo());}};function yo(s){var e,t,i;return s.buffered&&!!(s.body.gap||(e=s.range.video)!=null&&e.partial||(t=s.range.audio)!=null&&t.partial||(i=s.range.audiovideo)!=null&&i.partial)}function Qs(s){return `${s.type}_${s.level}_${s.sn}`}function xm(s,e){return s.filter(t=>{let i=e(t);return i||t.clearElementaryStreamInfo(),i})}var Ni={cbc:0,ctr:1},bc=class{constructor(e,t,i){this.subtle=void 0,this.aesIV=void 0,this.aesMode=void 0,this.subtle=e,this.aesIV=t,this.aesMode=i;}decrypt(e,t){switch(this.aesMode){case Ni.cbc:return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},t,e);case Ni.ctr:return this.subtle.decrypt({name:"AES-CTR",counter:this.aesIV,length:64},t,e);default:throw new Error(`[AESCrypto] invalid aes mode ${this.aesMode}`)}}};function HT(s){let e=s.byteLength,t=e&&new DataView(s.buffer).getUint8(e-1);return t?s.slice(0,e-t):s}var _c=class{constructor(){this.rcon=[0,1,2,4,8,16,32,64,128,27,54],this.subMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.invSubMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.sBox=new Uint32Array(256),this.invSBox=new Uint32Array(256),this.key=new Uint32Array(0),this.ksRows=0,this.keySize=0,this.keySchedule=void 0,this.invKeySchedule=void 0,this.initTable();}uint8ArrayToUint32Array_(e){let t=new DataView(e),i=new Uint32Array(4);for(let r=0;r<4;r++)i[r]=t.getUint32(r*4);return i}initTable(){let e=this.sBox,t=this.invSBox,i=this.subMix,r=i[0],n=i[1],a=i[2],o=i[3],l=this.invSubMix,d=l[0],c=l[1],u=l[2],h=l[3],f=new Uint32Array(256),m=0,p=0,E=0;for(E=0;E<256;E++)E<128?f[E]=E<<1:f[E]=E<<1^283;for(E=0;E<256;E++){let v=p^p<<1^p<<2^p<<3^p<<4;v=v>>>8^v&255^99,e[m]=v,t[v]=m;let T=f[m],S=f[T],A=f[S],b=f[v]*257^v*16843008;r[m]=b<<24|b>>>8,n[m]=b<<16|b>>>16,a[m]=b<<8|b>>>24,o[m]=b,b=A*16843009^S*65537^T*257^m*16843008,d[v]=b<<24|b>>>8,c[v]=b<<16|b>>>16,u[v]=b<<8|b>>>24,h[v]=b,m?(m=T^f[f[f[A^T]]],p^=f[f[p]]):m=p=1;}}expandKey(e){let t=this.uint8ArrayToUint32Array_(e),i=true,r=0;for(;r<t.length&&i;)i=t[r]===this.key[r],r++;if(i)return;this.key=t;let n=this.keySize=t.length;if(n!==4&&n!==6&&n!==8)throw new Error("Invalid aes key size="+n);let a=this.ksRows=(n+6+1)*4,o,l,d=this.keySchedule=new Uint32Array(a),c=this.invKeySchedule=new Uint32Array(a),u=this.sBox,h=this.rcon,f=this.invSubMix,m=f[0],p=f[1],E=f[2],v=f[3],T,S;for(o=0;o<a;o++){if(o<n){T=d[o]=t[o];continue}S=T,o%n===0?(S=S<<8|S>>>24,S=u[S>>>24]<<24|u[S>>>16&255]<<16|u[S>>>8&255]<<8|u[S&255],S^=h[o/n|0]<<24):n>6&&o%n===4&&(S=u[S>>>24]<<24|u[S>>>16&255]<<16|u[S>>>8&255]<<8|u[S&255]),d[o]=T=(d[o-n]^S)>>>0;}for(l=0;l<a;l++)o=a-l,l&3?S=d[o]:S=d[o-4],l<4||o<=4?c[l]=S:c[l]=m[u[S>>>24]]^p[u[S>>>16&255]]^E[u[S>>>8&255]]^v[u[S&255]],c[l]=c[l]>>>0;}networkToHostOrderSwap(e){return e<<24|(e&65280)<<8|(e&16711680)>>8|e>>>24}decrypt(e,t,i){let r=this.keySize+6,n=this.invKeySchedule,a=this.invSBox,o=this.invSubMix,l=o[0],d=o[1],c=o[2],u=o[3],h=this.uint8ArrayToUint32Array_(i),f=h[0],m=h[1],p=h[2],E=h[3],v=new Int32Array(e),T=new Int32Array(v.length),S,A,b,D,I,k,R,L,M,B,H,j,K,O,Y=this.networkToHostOrderSwap;for(;t<v.length;){for(M=Y(v[t]),B=Y(v[t+1]),H=Y(v[t+2]),j=Y(v[t+3]),I=M^n[0],k=j^n[1],R=H^n[2],L=B^n[3],K=4,O=1;O<r;O++)S=l[I>>>24]^d[k>>16&255]^c[R>>8&255]^u[L&255]^n[K],A=l[k>>>24]^d[R>>16&255]^c[L>>8&255]^u[I&255]^n[K+1],b=l[R>>>24]^d[L>>16&255]^c[I>>8&255]^u[k&255]^n[K+2],D=l[L>>>24]^d[I>>16&255]^c[k>>8&255]^u[R&255]^n[K+3],I=S,k=A,R=b,L=D,K=K+4;S=a[I>>>24]<<24^a[k>>16&255]<<16^a[R>>8&255]<<8^a[L&255]^n[K],A=a[k>>>24]<<24^a[R>>16&255]<<16^a[L>>8&255]<<8^a[I&255]^n[K+1],b=a[R>>>24]<<24^a[L>>16&255]<<16^a[I>>8&255]<<8^a[k&255]^n[K+2],D=a[L>>>24]<<24^a[I>>16&255]<<16^a[k>>8&255]<<8^a[R&255]^n[K+3],T[t]=Y(S^f),T[t+1]=Y(D^m),T[t+2]=Y(b^p),T[t+3]=Y(A^E),f=M,m=B,p=H,E=j,t=t+4;}return T.buffer}},Ic=class{constructor(e,t,i){this.subtle=void 0,this.key=void 0,this.aesMode=void 0,this.subtle=e,this.key=t,this.aesMode=i;}expandKey(){let e=KT(this.aesMode);return this.subtle.importKey("raw",this.key,{name:e},false,["encrypt","decrypt"])}};function KT(s){switch(s){case Ni.cbc:return "AES-CBC";case Ni.ctr:return "AES-CTR";default:throw new Error(`[FastAESKey] invalid aes mode ${s}`)}}var VT=16,En=class{constructor(e,{removePKCS7Padding:t=true}={}){if(this.logEnabled=true,this.removePKCS7Padding=void 0,this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null,this.useSoftware=void 0,this.enableSoftwareAES=void 0,this.enableSoftwareAES=e.enableSoftwareAES,this.removePKCS7Padding=t,t)try{let i=self.crypto;i&&(this.subtle=i.subtle||i.webkitSubtle);}catch{}this.useSoftware=!this.subtle;}destroy(){this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null;}isSync(){return this.useSoftware}flush(){let{currentResult:e,remainderData:t}=this;if(!e||t)return this.reset(),null;let i=new Uint8Array(e);return this.reset(),this.removePKCS7Padding?HT(i):i}reset(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&(this.softwareDecrypter=null);}decrypt(e,t,i,r){return this.useSoftware?new Promise((n,a)=>{let o=ArrayBuffer.isView(e)?e:new Uint8Array(e);this.softwareDecrypt(o,t,i,r);let l=this.flush();l?n(l.buffer):a(new Error("[softwareDecrypt] Failed to decrypt data"));}):this.webCryptoDecrypt(new Uint8Array(e),t,i,r)}softwareDecrypt(e,t,i,r){let{currentIV:n,currentResult:a,remainderData:o}=this;if(r!==Ni.cbc||t.byteLength!==16)return Te.warn("SoftwareDecrypt: can only handle AES-128-CBC"),null;this.logOnce("JS AES decrypt"),o&&(e=Dt(o,e),this.remainderData=null);let l=this.getValidChunk(e);if(!l.length)return null;n&&(i=n);let d=this.softwareDecrypter;d||(d=this.softwareDecrypter=new _c),d.expandKey(t);let c=a;return this.currentResult=d.decrypt(l.buffer,0,i),this.currentIV=l.slice(-16).buffer,c||null}webCryptoDecrypt(e,t,i,r){if(this.key!==t||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(e,t,i,r));this.key=t,this.fastAesKey=new Ic(this.subtle,t,r);}return this.fastAesKey.expandKey().then(n=>this.subtle?(this.logOnce("WebCrypto AES decrypt"),new bc(this.subtle,new Uint8Array(i),r).decrypt(e.buffer,n)):Promise.reject(new Error("web crypto not initialized"))).catch(n=>(Te.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${n.name}: ${n.message}`),this.onWebCryptoError(e,t,i,r)))}onWebCryptoError(e,t,i,r){let n=this.enableSoftwareAES;if(n){this.useSoftware=true,this.logEnabled=true,this.softwareDecrypt(e,t,i,r);let a=this.flush();if(a)return a.buffer}throw new Error("WebCrypto"+(n?" and softwareDecrypt":"")+": failed to decrypt data")}getValidChunk(e){let t=e,i=e.length-e.length%VT;return i!==e.length&&(t=e.slice(0,i),this.remainderData=e.slice(i)),t}logOnce(e){this.logEnabled&&(Te.log(`[decrypter]: ${e}`),this.logEnabled=false);}},Rm=Math.pow(2,17),Lc=class{constructor(e){this.config=void 0,this.loader=null,this.partLoadTimeout=-1,this.config=e;}destroy(){this.loader&&(this.loader.destroy(),this.loader=null);}abort(){this.loader&&this.loader.abort();}load(e,t){let i=e.url;if(!i)return Promise.reject(new Ht({type:z.NETWORK_ERROR,details:x.FRAG_LOAD_ERROR,fatal:false,frag:e,error:new Error(`Fragment does not have a ${i?"part list":"url"}`),networkDetails:null}));this.abort();let r=this.config,n=r.fLoader,a=r.loader;return new Promise((o,l)=>{if(this.loader&&this.loader.destroy(),e.gap)if(e.tagList.some(m=>m[0]==="GAP")){l(Dm(e));return}else e.gap=false;let d=this.loader=n?new n(r):new a(r),c=km(e);e.loader=d;let u=Lm(r.fragLoadPolicy.default),h={loadPolicy:u,timeout:u.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:e.sn==="initSegment"?1/0:Rm};e.stats=d.stats;let f={onSuccess:(m,p,E,v)=>{this.resetLoader(e,d);let T=m.data;E.resetIV&&e.decryptdata&&(e.decryptdata.iv=new Uint8Array(T.slice(0,16)),T=T.slice(16)),o({frag:e,part:null,payload:T,networkDetails:v});},onError:(m,p,E,v)=>{this.resetLoader(e,d),l(new Ht({type:z.NETWORK_ERROR,details:x.FRAG_LOAD_ERROR,fatal:false,frag:e,response:ve({url:i,data:void 0},m),error:new Error(`HTTP Error ${m.code} ${m.text}`),networkDetails:E,stats:v}));},onAbort:(m,p,E)=>{this.resetLoader(e,d),l(new Ht({type:z.NETWORK_ERROR,details:x.INTERNAL_ABORTED,fatal:false,frag:e,error:new Error("Aborted"),networkDetails:E,stats:m}));},onTimeout:(m,p,E)=>{this.resetLoader(e,d),l(new Ht({type:z.NETWORK_ERROR,details:x.FRAG_LOAD_TIMEOUT,fatal:false,frag:e,error:new Error(`Timeout after ${h.timeout}ms`),networkDetails:E,stats:m}));}};t&&(f.onProgress=(m,p,E,v)=>t({frag:e,part:null,payload:E,networkDetails:v})),d.load(c,h,f);})}loadPart(e,t,i){this.abort();let r=this.config,n=r.fLoader,a=r.loader;return new Promise((o,l)=>{if(this.loader&&this.loader.destroy(),e.gap||t.gap){l(Dm(e,t));return}let d=this.loader=n?new n(r):new a(r),c=km(e,t);e.loader=d;let u=Lm(r.fragLoadPolicy.default),h={loadPolicy:u,timeout:u.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:Rm};t.stats=d.stats,d.load(c,h,{onSuccess:(f,m,p,E)=>{this.resetLoader(e,d),this.updateStatsFromPart(e,t);let v={frag:e,part:t,payload:f.data,networkDetails:E};i(v),o(v);},onError:(f,m,p,E)=>{this.resetLoader(e,d),l(new Ht({type:z.NETWORK_ERROR,details:x.FRAG_LOAD_ERROR,fatal:false,frag:e,part:t,response:ve({url:c.url,data:void 0},f),error:new Error(`HTTP Error ${f.code} ${f.text}`),networkDetails:p,stats:E}));},onAbort:(f,m,p)=>{e.stats.aborted=t.stats.aborted,this.resetLoader(e,d),l(new Ht({type:z.NETWORK_ERROR,details:x.INTERNAL_ABORTED,fatal:false,frag:e,part:t,error:new Error("Aborted"),networkDetails:p,stats:f}));},onTimeout:(f,m,p)=>{this.resetLoader(e,d),l(new Ht({type:z.NETWORK_ERROR,details:x.FRAG_LOAD_TIMEOUT,fatal:false,frag:e,part:t,error:new Error(`Timeout after ${h.timeout}ms`),networkDetails:p,stats:f}));}});})}updateStatsFromPart(e,t){let i=e.stats,r=t.stats,n=r.total;if(i.loaded+=r.loaded,n){let l=Math.round(e.duration/t.duration),d=Math.min(Math.round(i.loaded/n),l),u=(l-d)*Math.round(i.loaded/d);i.total=i.loaded+u;}else i.total=Math.max(i.loaded,i.total);let a=i.loading,o=r.loading;a.start?a.first+=o.first-o.start:(a.start=o.start,a.first=o.first),a.end=o.end;}resetLoader(e,t){e.loader=null,this.loader===t&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),t.destroy();}};function km(s,e=null){let t=e||s,i={frag:s,part:e,responseType:"arraybuffer",url:t.url,headers:{},rangeStart:0,rangeEnd:0},r=t.byteRangeStartOffset,n=t.byteRangeEndOffset;if(G(r)&&G(n)){var a;let o=r,l=n;if(s.sn==="initSegment"&&WT((a=s.decryptdata)==null?void 0:a.method)){let d=n-r;d%16&&(l=n+(16-d%16)),r!==0&&(i.resetIV=true,o=r-16);}i.rangeStart=o,i.rangeEnd=l;}return i}function Dm(s,e){let t=new Error(`GAP ${s.gap?"tag":"attribute"} found`),i={type:z.MEDIA_ERROR,details:x.FRAG_GAP,fatal:false,frag:s,error:t,networkDetails:null};return e&&(i.part=e),(e||s).stats.aborted=true,new Ht(i)}function WT(s){return s==="AES-128"||s==="AES-256"}var Ht=class extends Error{constructor(e){super(e.error.message),this.data=void 0,this.data=e;}},jo=class extends ht{constructor(e,t){super(e,t),this._boundTick=void 0,this._tickTimer=null,this._tickInterval=null,this._tickCallCount=0,this._boundTick=this.tick.bind(this);}destroy(){this.onHandlerDestroying(),this.onHandlerDestroyed();}onHandlerDestroying(){this.clearNextTick(),this.clearInterval();}onHandlerDestroyed(){}hasInterval(){return !!this._tickInterval}hasNextTick(){return !!this._tickTimer}setInterval(e){return this._tickInterval?false:(this._tickCallCount=0,this._tickInterval=self.setInterval(this._boundTick,e),true)}clearInterval(){return this._tickInterval?(self.clearInterval(this._tickInterval),this._tickInterval=null,true):false}clearNextTick(){return this._tickTimer?(self.clearTimeout(this._tickTimer),this._tickTimer=null,true):false}tick(){this._tickCallCount++,this._tickCallCount===1&&(this.doTick(),this._tickCallCount>1&&this.tickImmediate(),this._tickCallCount=0);}tickImmediate(){this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0);}doTick(){}},vn=class{constructor(e,t,i,r=0,n=-1,a=false){this.level=void 0,this.sn=void 0,this.part=void 0,this.id=void 0,this.size=void 0,this.partial=void 0,this.transmuxing=So(),this.buffering={audio:So(),video:So(),audiovideo:So()},this.level=e,this.sn=t,this.id=i,this.size=r,this.part=n,this.partial=a;}};function So(){return {start:0,executeStart:0,executeEnd:0,end:0}}var Cm={length:0,start:()=>0,end:()=>0},re=class s{static isBuffered(e,t){if(e){let i=s.getBuffered(e);for(let r=i.length;r--;)if(t>=i.start(r)&&t<=i.end(r))return true}return false}static bufferedRanges(e){if(e){let t=s.getBuffered(e);return s.timeRangesToArray(t)}return []}static timeRangesToArray(e){let t=[];for(let i=0;i<e.length;i++)t.push({start:e.start(i),end:e.end(i)});return t}static bufferInfo(e,t,i){if(e){let r=s.bufferedRanges(e);if(r.length)return s.bufferedInfo(r,t,i)}return {len:0,start:t,end:t,bufferedIndex:-1}}static bufferedInfo(e,t,i){t=Math.max(0,t),e.length>1&&e.sort((c,u)=>c.start-u.start||u.end-c.end);let r=-1,n=[];if(i)for(let c=0;c<e.length;c++){t>=e[c].start&&t<=e[c].end&&(r=c);let u=n.length;if(u){let h=n[u-1].end;e[c].start-h<i?e[c].end>h&&(n[u-1].end=e[c].end):n.push(e[c]);}else n.push(e[c]);}else n=e;let a=0,o,l=t,d=t;for(let c=0;c<n.length;c++){let u=n[c].start,h=n[c].end;if(r===-1&&t>=u&&t<=h&&(r=c),t+i>=u&&t<h)l=u,d=h,a=d-t;else if(t+i<u){o=u;break}}return {len:a,start:l||0,end:d||0,nextStart:o,buffered:e,bufferedIndex:r}}static getBuffered(e){try{return e.buffered||Cm}catch(t){return Te.log("failed to get media.buffered",t),Cm}}},Kg=/\{\$([a-zA-Z0-9-_]+)\}/g;function Mm(s){return Kg.test(s)}function xc(s,e){if(s.variableList!==null||s.hasVariableRefs){let t=s.variableList;return e.replace(Kg,i=>{let r=i.substring(2,i.length-1),n=t?.[r];return n===void 0?(s.playlistParsingError||(s.playlistParsingError=new Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${r}"`)),i):n})}return e}function Pm(s,e,t){let i=s.variableList;i||(s.variableList=i={});let r,n;if("QUERYPARAM"in e){r=e.QUERYPARAM;try{let a=new self.URL(t).searchParams;if(a.has(r))n=a.get(r);else throw new Error(`"${r}" does not match any query parameter in URI: "${t}"`)}catch(a){s.playlistParsingError||(s.playlistParsingError=new Error(`EXT-X-DEFINE QUERYPARAM: ${a.message}`));}}else r=e.NAME,n=e.VALUE;r in i?s.playlistParsingError||(s.playlistParsingError=new Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${r}"`)):i[r]=n||"";}function YT(s,e,t){let i=e.IMPORT;if(t&&i in t){let r=s.variableList;r||(s.variableList=r={}),r[i]=t[i];}else s.playlistParsingError||(s.playlistParsingError=new Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${i}"`));}var qT=/^(\d+)x(\d+)$/,wm=/(.+?)=(".*?"|.*?)(?:,|$)/g,Re=class s{constructor(e,t){typeof e=="string"&&(e=s.parseAttrList(e,t)),ye(this,e);}get clientAttrs(){return Object.keys(this).filter(e=>e.substring(0,2)==="X-")}decimalInteger(e){let t=parseInt(this[e],10);return t>Number.MAX_SAFE_INTEGER?1/0:t}hexadecimalInteger(e){if(this[e]){let t=(this[e]||"0x").slice(2);t=(t.length&1?"0":"")+t;let i=new Uint8Array(t.length/2);for(let r=0;r<t.length/2;r++)i[r]=parseInt(t.slice(r*2,r*2+2),16);return i}return null}hexadecimalIntegerAsNumber(e){let t=parseInt(this[e],16);return t>Number.MAX_SAFE_INTEGER?1/0:t}decimalFloatingPoint(e){return parseFloat(this[e])}optionalFloat(e,t){let i=this[e];return i?parseFloat(i):t}enumeratedString(e){return this[e]}enumeratedStringList(e,t){let i=this[e];return (i?i.split(/[ ,]+/):[]).reduce((r,n)=>(r[n.toLowerCase()]=true,r),t)}bool(e){return this[e]==="YES"}decimalResolution(e){let t=qT.exec(this[e]);if(t!==null)return {width:parseInt(t[1],10),height:parseInt(t[2],10)}}static parseAttrList(e,t){let i,r={},n='"';for(wm.lastIndex=0;(i=wm.exec(e))!==null;){let a=i[1].trim(),o=i[2],l=o.indexOf(n)===0&&o.lastIndexOf(n)===o.length-1,d=false;if(l)o=o.slice(1,-1);else switch(a){case "IV":case "SCTE35-CMD":case "SCTE35-IN":case "SCTE35-OUT":d=true;}if(t&&(l||d))o=xc(t,o);else if(!d&&!l)switch(a){case "CLOSED-CAPTIONS":if(o==="NONE")break;case "ALLOWED-CPC":case "CLASS":case "ASSOC-LANGUAGE":case "AUDIO":case "BYTERANGE":case "CHANNELS":case "CHARACTERISTICS":case "CODECS":case "DATA-ID":case "END-DATE":case "GROUP-ID":case "ID":case "IMPORT":case "INSTREAM-ID":case "KEYFORMAT":case "KEYFORMATVERSIONS":case "LANGUAGE":case "NAME":case "PATHWAY-ID":case "QUERYPARAM":case "RECENTLY-REMOVED-DATERANGES":case "SERVER-URI":case "STABLE-RENDITION-ID":case "STABLE-VARIANT-ID":case "START-DATE":case "SUBTITLES":case "SUPPLEMENTAL-CODECS":case "URI":case "VALUE":case "VIDEO":case "X-ASSET-LIST":case "X-ASSET-URI":Te.warn(`${e}: attribute ${a} is missing quotes`);}r[a]=o;}return r}},jT="com.apple.hls.interstitial";function zT(s){return s!=="ID"&&s!=="CLASS"&&s!=="CUE"&&s!=="START-DATE"&&s!=="DURATION"&&s!=="END-DATE"&&s!=="END-ON-NEXT"}function QT(s){return s==="SCTE35-OUT"||s==="SCTE35-IN"||s==="SCTE35-CMD"}var zo=class{constructor(e,t,i=0){var r;if(this.attr=void 0,this.tagAnchor=void 0,this.tagOrder=void 0,this._startDate=void 0,this._endDate=void 0,this._dateAtEnd=void 0,this._cue=void 0,this._badValueForSameId=void 0,this.tagAnchor=t?.tagAnchor||null,this.tagOrder=(r=t?.tagOrder)!=null?r:i,t){let n=t.attr;for(let a in n)if(Object.prototype.hasOwnProperty.call(e,a)&&e[a]!==n[a]){Te.warn(`DATERANGE tag attribute: "${a}" does not match for tags with ID: "${e.ID}"`),this._badValueForSameId=a;break}e=ye(new Re({}),n,e);}if(this.attr=e,t?(this._startDate=t._startDate,this._cue=t._cue,this._endDate=t._endDate,this._dateAtEnd=t._dateAtEnd):this._startDate=new Date(e["START-DATE"]),"END-DATE"in this.attr){let n=t?.endDate||new Date(this.attr["END-DATE"]);G(n.getTime())&&(this._endDate=n);}}get id(){return this.attr.ID}get class(){return this.attr.CLASS}get cue(){let e=this._cue;return e===void 0?this._cue=this.attr.enumeratedStringList(this.attr.CUE?"CUE":"X-CUE",{pre:false,post:false,once:false}):e}get startTime(){let{tagAnchor:e}=this;return e===null||e.programDateTime===null?(Te.warn(`Expected tagAnchor Fragment with PDT set for DateRange "${this.id}": ${e}`),NaN):e.start+(this.startDate.getTime()-e.programDateTime)/1e3}get startDate(){return this._startDate}get endDate(){let e=this._endDate||this._dateAtEnd;if(e)return e;let t=this.duration;return t!==null?this._dateAtEnd=new Date(this._startDate.getTime()+t*1e3):null}get duration(){if("DURATION"in this.attr){let e=this.attr.decimalFloatingPoint("DURATION");if(G(e))return e}else if(this._endDate)return (this._endDate.getTime()-this._startDate.getTime())/1e3;return null}get plannedDuration(){return "PLANNED-DURATION"in this.attr?this.attr.decimalFloatingPoint("PLANNED-DURATION"):null}get endOnNext(){return this.attr.bool("END-ON-NEXT")}get isInterstitial(){return this.class===jT}get isValid(){return !!this.id&&!this._badValueForSameId&&G(this.startDate.getTime())&&(this.duration===null||this.duration>=0)&&(!this.endOnNext||!!this.class)&&(!this.attr.CUE||!this.cue.pre&&!this.cue.post||this.cue.pre!==this.cue.post)&&(!this.isInterstitial||"X-ASSET-URI"in this.attr||"X-ASSET-LIST"in this.attr)}},XT=10,Rc=class{constructor(e){this.PTSKnown=false,this.alignedSliding=false,this.averagetargetduration=void 0,this.endCC=0,this.endSN=0,this.fragments=void 0,this.fragmentHint=void 0,this.partList=null,this.dateRanges=void 0,this.dateRangeTagCount=0,this.live=true,this.requestScheduled=-1,this.ageHeader=0,this.advancedDateTime=void 0,this.updated=true,this.advanced=true,this.misses=0,this.startCC=0,this.startSN=0,this.startTimeOffset=null,this.targetduration=0,this.totalduration=0,this.type=null,this.url=void 0,this.m3u8="",this.version=null,this.canBlockReload=false,this.canSkipUntil=0,this.canSkipDateRanges=false,this.skippedSegments=0,this.recentlyRemovedDateranges=void 0,this.partHoldBack=0,this.holdBack=0,this.partTarget=0,this.preloadHint=void 0,this.renditionReports=void 0,this.tuneInGoal=0,this.deltaUpdateFailed=void 0,this.driftStartTime=0,this.driftEndTime=0,this.driftStart=0,this.driftEnd=0,this.encryptedFragments=void 0,this.playlistParsingError=null,this.variableList=null,this.hasVariableRefs=false,this.appliedTimelineOffset=void 0,this.fragments=[],this.encryptedFragments=[],this.dateRanges={},this.url=e;}reloaded(e){if(!e){this.advanced=true,this.updated=true;return}let t=this.lastPartSn-e.lastPartSn,i=this.lastPartIndex-e.lastPartIndex;this.updated=this.endSN!==e.endSN||!!i||!!t||!this.live,this.advanced=this.endSN>e.endSN||t>0||t===0&&i>0,this.updated||this.advanced?this.misses=Math.floor(e.misses*.6):this.misses=e.misses+1;}hasKey(e){return this.encryptedFragments.some(t=>{let i=t.decryptdata;return i||(t.setKeyFormat(e.keyFormat),i=t.decryptdata),!!i&&e.matches(i)})}get hasProgramDateTime(){return this.fragments.length?G(this.fragments[this.fragments.length-1].programDateTime):false}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||XT}get drift(){let e=this.driftEndTime-this.driftStartTime;return e>0?(this.driftEnd-this.driftStart)*1e3/e:1}get edge(){return this.partEnd||this.fragmentEnd}get partEnd(){var e;return (e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].end:this.fragmentEnd}get fragmentEnd(){return this.fragments.length?this.fragments[this.fragments.length-1].end:0}get fragmentStart(){return this.fragments.length?this.fragments[0].start:0}get age(){return this.advancedDateTime?Math.max(Date.now()-this.advancedDateTime,0)/1e3:0}get lastPartIndex(){var e;return (e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].index:-1}get maxPartIndex(){let e=this.partList;if(e){let t=this.lastPartIndex;if(t!==-1){for(let i=e.length;i--;)if(e[i].index>t)return e[i].index;return t}}return 0}get lastPartSn(){var e;return (e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}get expired(){if(this.live&&this.age&&this.misses<3){let e=this.partEnd-this.fragmentStart;return this.age>Math.max(e,this.totalduration)+this.levelTargetDuration}return false}};function Qo(s,e){return s.length===e.length?!s.some((t,i)=>t!==e[i]):false}function Om(s,e){return !s&&!e?true:!s||!e?false:Qo(s,e)}function sr(s){return s==="AES-128"||s==="AES-256"||s==="AES-256-CTR"}function Nu(s){switch(s){case "AES-128":case "AES-256":return Ni.cbc;case "AES-256-CTR":return Ni.ctr;default:throw new Error(`invalid full segment method ${s}`)}}function Uu(s){return Uint8Array.from(atob(s),e=>e.charCodeAt(0))}function kc(s){return Uint8Array.from(unescape(encodeURIComponent(s)),e=>e.charCodeAt(0))}function ZT(s){let e=kc(s).subarray(0,16),t=new Uint8Array(16);return t.set(e,16-e.length),t}function Vg(s){let e=function(i,r,n){let a=i[r];i[r]=i[n],i[n]=a;};e(s,0,3),e(s,1,2),e(s,4,5),e(s,6,7);}function Wg(s){let e=s.split(":"),t=null;if(e[0]==="data"&&e.length===2){let i=e[1].split(";"),r=i[i.length-1].split(",");if(r.length===2){let n=r[0]==="base64",a=r[1];n?(i.splice(-1,1),t=Uu(a)):t=ZT(a);}}return t}var Xo=typeof self<"u"?self:void 0,ke={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},Xe={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.streamingkeydelivery",PLAYREADY:"com.microsoft.playready",WIDEVINE:"urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed"};function Oo(s){switch(s){case Xe.FAIRPLAY:return ke.FAIRPLAY;case Xe.PLAYREADY:return ke.PLAYREADY;case Xe.WIDEVINE:return ke.WIDEVINE;case Xe.CLEARKEY:return ke.CLEARKEY}}function jd(s){switch(s){case ke.FAIRPLAY:return Xe.FAIRPLAY;case ke.PLAYREADY:return Xe.PLAYREADY;case ke.WIDEVINE:return Xe.WIDEVINE;case ke.CLEARKEY:return Xe.CLEARKEY}}function dn(s){let{drmSystems:e,widevineLicenseUrl:t}=s,i=e?[ke.FAIRPLAY,ke.WIDEVINE,ke.PLAYREADY,ke.CLEARKEY].filter(r=>!!e[r]):[];return !i[ke.WIDEVINE]&&t&&i.push(ke.WIDEVINE),i}var Yg=function(s){return Xo!=null&&(s=Xo.navigator)!=null&&s.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null}();function JT(s,e,t,i){let r;switch(s){case ke.FAIRPLAY:r=["cenc","sinf"];break;case ke.WIDEVINE:case ke.PLAYREADY:r=["cenc"];break;case ke.CLEARKEY:r=["cenc","keyids"];break;default:throw new Error(`Unknown key-system: ${s}`)}return ey(r,e,t,i)}function ey(s,e,t,i){return [{initDataTypes:s,persistentState:i.persistentState||"optional",distinctiveIdentifier:i.distinctiveIdentifier||"optional",sessionTypes:i.sessionTypes||[i.sessionType||"temporary"],audioCapabilities:e.map(n=>({contentType:`audio/mp4; codecs=${n}`,robustness:i.audioRobustness||"",encryptionScheme:i.audioEncryptionScheme||null})),videoCapabilities:t.map(n=>({contentType:`video/mp4; codecs=${n}`,robustness:i.videoRobustness||"",encryptionScheme:i.videoEncryptionScheme||null}))}]}function ty(s){var e;return !!s&&(s.sessionType==="persistent-license"||!!((e=s.sessionTypes)!=null&&e.some(t=>t==="persistent-license")))}function qg(s){let e=new Uint16Array(s.buffer,s.byteOffset,s.byteLength/2),t=String.fromCharCode.apply(null,Array.from(e)),i=t.substring(t.indexOf("<"),t.length),a=new DOMParser().parseFromString(i,"text/xml").getElementsByTagName("KID")[0];if(a){let o=a.childNodes[0]?a.childNodes[0].nodeValue:a.getAttribute("VALUE");if(o){let l=Uu(o).subarray(0,16);return Vg(l),l}}return null}var Ao={},Tn=class s{static clearKeyUriToKeyIdMap(){Ao={};}static setKeyIdForUri(e,t){Ao[e]=t;}constructor(e,t,i,r=[1],n=null,a){this.uri=void 0,this.method=void 0,this.keyFormat=void 0,this.keyFormatVersions=void 0,this.encrypted=void 0,this.isCommonEncryption=void 0,this.iv=null,this.key=null,this.keyId=null,this.pssh=null,this.method=e,this.uri=t,this.keyFormat=i,this.keyFormatVersions=r,this.iv=n,this.encrypted=e?e!=="NONE":false,this.isCommonEncryption=this.encrypted&&!sr(e),a!=null&&a.startsWith("0x")&&(this.keyId=new Uint8Array(_g(a)));}matches(e){return e.uri===this.uri&&e.method===this.method&&e.encrypted===this.encrypted&&e.keyFormat===this.keyFormat&&Qo(e.keyFormatVersions,this.keyFormatVersions)&&Om(e.iv,this.iv)&&Om(e.keyId,this.keyId)}isSupported(){if(this.method){if(sr(this.method)||this.method==="NONE")return true;if(this.keyFormat==="identity")return this.method==="SAMPLE-AES";switch(this.keyFormat){case Xe.FAIRPLAY:case Xe.WIDEVINE:case Xe.PLAYREADY:case Xe.CLEARKEY:return ["SAMPLE-AES","SAMPLE-AES-CENC","SAMPLE-AES-CTR"].indexOf(this.method)!==-1}}return false}getDecryptData(e,t){if(!this.encrypted||!this.uri)return null;if(sr(this.method)){let n=this.iv;return n||(typeof e!="number"&&(Te.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),e=0),n=sy(e)),new s(this.method,this.uri,"identity",this.keyFormatVersions,n)}if(this.keyId){let n=Ao[this.uri];if(n&&!Qo(this.keyId,n)&&s.setKeyIdForUri(this.uri,this.keyId),this.pssh)return this}let i=Wg(this.uri);if(i)switch(this.keyFormat){case Xe.WIDEVINE:if(this.pssh=i,!this.keyId){let n=mT(i.buffer);if(n.length){var r;let a=n[0];this.keyId=(r=a.kids)!=null&&r.length?a.kids[0]:null;}}this.keyId||(this.keyId=Fm(t));break;case Xe.PLAYREADY:{let n=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=fT(n,null,i),this.keyId=qg(i);break}default:{let n=i.subarray(0,16);if(n.length!==16){let a=new Uint8Array(16);a.set(n,16-n.length),n=a;}this.keyId=n;break}}if(!this.keyId||this.keyId.byteLength!==16){let n;n=iy(t),n||(n=Fm(t),n||(n=Ao[this.uri])),n&&(this.keyId=n,s.setKeyIdForUri(this.uri,n));}return this}};function iy(s){let e=s?.[Xe.WIDEVINE];return e?e.keyId:null}function Fm(s){let e=s?.[Xe.PLAYREADY];if(e){let t=Wg(e.uri);if(t)return qg(t)}return null}function sy(s){let e=new Uint8Array(16);for(let t=12;t<16;t++)e[t]=s>>8*(15-t)&255;return e}var Nm=/#EXT-X-STREAM-INF:([^\r\n]*)(?:[\r\n](?:#[^\r\n]*)?)*([^\r\n]+)|#EXT-X-(SESSION-DATA|SESSION-KEY|DEFINE|CONTENT-STEERING|START):([^\r\n]*)[\r\n]+/g,Um=/#EXT-X-MEDIA:(.*)/g,ry=/^#EXT(?:INF|-X-TARGETDURATION):/m,zd=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#.*/.source].join("|"),"g"),ny=new RegExp([/#EXT-X-(PROGRAM-DATE-TIME|BYTERANGE|DATERANGE|DEFINE|KEY|MAP|PART|PART-INF|PLAYLIST-TYPE|PRELOAD-HINT|RENDITION-REPORT|SERVER-CONTROL|SKIP|START):(.+)/.source,/#EXT-X-(BITRATE|DISCONTINUITY-SEQUENCE|MEDIA-SEQUENCE|TARGETDURATION|VERSION): *(\d+)/.source,/#EXT-X-(DISCONTINUITY|ENDLIST|GAP|INDEPENDENT-SEGMENTS)/.source,/(#)([^:]*):(.*)/.source,/(#)(.*)(?:.*)\r?\n?/.source].join("|")),as=class s{static findGroup(e,t){for(let i=0;i<e.length;i++){let r=e[i];if(r.id===t)return r}}static resolve(e,t){return Mu.buildAbsoluteURL(t,e,{alwaysNormalize:true})}static isMediaPlaylist(e){return ry.test(e)}static parseMasterPlaylist(e,t){let i=Mm(e),r={contentSteering:null,levels:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:i},n=[];if(Nm.lastIndex=0,!e.startsWith("#EXTM3U"))return r.playlistParsingError=new Error("no EXTM3U delimiter"),r;let a;for(;(a=Nm.exec(e))!=null;)if(a[1]){var o;let d=new Re(a[1],r),c=xc(r,a[2]),u={attrs:d,bitrate:d.decimalInteger("BANDWIDTH")||d.decimalInteger("AVERAGE-BANDWIDTH"),name:d.NAME,url:s.resolve(c,t)},h=d.decimalResolution("RESOLUTION");h&&(u.width=h.width,u.height=h.height),Gm(d.CODECS,u);let f=d["SUPPLEMENTAL-CODECS"];f&&(u.supplemental={},Gm(f,u.supplemental)),(o=u.unknownCodecs)!=null&&o.length||n.push(u),r.levels.push(u);}else if(a[3]){let d=a[3],c=a[4];switch(d){case "SESSION-DATA":{let u=new Re(c,r),h=u["DATA-ID"];h&&(r.sessionData===null&&(r.sessionData={}),r.sessionData[h]=u);break}case "SESSION-KEY":{let u=Bm(c,t,r);u.encrypted&&u.isSupported()?(r.sessionKeys===null&&(r.sessionKeys=[]),r.sessionKeys.push(u)):Te.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${c}"`);break}case "DEFINE":{{let u=new Re(c,r);Pm(r,u,t);}break}case "CONTENT-STEERING":{let u=new Re(c,r);r.contentSteering={uri:s.resolve(u["SERVER-URI"],t),pathwayId:u["PATHWAY-ID"]||"."};break}case "START":{r.startTimeOffset=$m(c);break}}}let l=n.length>0&&n.length<r.levels.length;return r.levels=l?n:r.levels,r.levels.length===0&&(r.playlistParsingError=new Error("no levels found in manifest")),r}static parseMasterPlaylistMedia(e,t,i){let r,n={},a=i.levels,o={AUDIO:a.map(d=>({id:d.attrs.AUDIO,audioCodec:d.audioCodec})),SUBTITLES:a.map(d=>({id:d.attrs.SUBTITLES,textCodec:d.textCodec})),"CLOSED-CAPTIONS":[]},l=0;for(Um.lastIndex=0;(r=Um.exec(e))!==null;){let d=new Re(r[1],i),c=d.TYPE;if(c){let u=o[c],h=n[c]||[];n[c]=h;let f=d.LANGUAGE,m=d["ASSOC-LANGUAGE"],p=d.CHANNELS,E=d.CHARACTERISTICS,v=d["INSTREAM-ID"],T={attrs:d,bitrate:0,id:l++,groupId:d["GROUP-ID"]||"",name:d.NAME||f||"",type:c,default:d.bool("DEFAULT"),autoselect:d.bool("AUTOSELECT"),forced:d.bool("FORCED"),lang:f,url:d.URI?s.resolve(d.URI,t):""};if(m&&(T.assocLang=m),p&&(T.channels=p),E&&(T.characteristics=E),v&&(T.instreamId=v),u!=null&&u.length){let S=s.findGroup(u,T.groupId)||u[0];Hm(T,S,"audioCodec"),Hm(T,S,"textCodec");}h.push(T);}}return n}static parseLevelPlaylist(e,t,i,r,n,a){var o;let l={url:t},d=new Rc(t),c=d.fragments,u=[],h=null,f=0,m=0,p=0,E=0,v=0,T=null,S=new cn(r,l),A,b,D,I=-1,k=false,R=null,L;if(zd.lastIndex=0,d.m3u8=e,d.hasVariableRefs=Mm(e),((o=zd.exec(e))==null?void 0:o[0])!=="#EXTM3U")return d.playlistParsingError=new Error("Missing format identifier #EXTM3U"),d;for(;(A=zd.exec(e))!==null;){k&&(k=false,S=new cn(r,l),S.playlistOffset=p,S.setStart(p),S.sn=f,S.cc=E,v&&(S.bitrate=v),S.level=i,h&&(S.initSegment=h,h.rawProgramDateTime&&(S.rawProgramDateTime=h.rawProgramDateTime,h.rawProgramDateTime=null),R&&(S.setByteRange(R),R=null)));let j=A[1];if(j){S.duration=parseFloat(j);let K=(" "+A[2]).slice(1);S.title=K||null,S.tagList.push(K?["INF",j,K]:["INF",j]);}else if(A[3]){if(G(S.duration)){S.playlistOffset=p,S.setStart(p),D&&Vm(S,D,d),S.sn=f,S.level=i,S.cc=E,c.push(S);let K=(" "+A[3]).slice(1);S.relurl=xc(d,K),Dc(S,T,u),T=S,p+=S.duration,f++,m=0,k=true;}}else {if(A=A[0].match(ny),!A){Te.warn("No matches on slow regex match for level playlist!");continue}for(b=1;b<A.length&&A[b]===void 0;b++);let K=(" "+A[b]).slice(1),O=(" "+A[b+1]).slice(1),Y=A[b+2]?(" "+A[b+2]).slice(1):null;switch(K){case "BYTERANGE":T?S.setByteRange(O,T):S.setByteRange(O);break;case "PROGRAM-DATE-TIME":S.rawProgramDateTime=O,S.tagList.push(["PROGRAM-DATE-TIME",O]),I===-1&&(I=c.length);break;case "PLAYLIST-TYPE":d.type&&Ei(d,K,A),d.type=O.toUpperCase();break;case "MEDIA-SEQUENCE":d.startSN!==0?Ei(d,K,A):c.length>0&&Wm(d,K,A),f=d.startSN=parseInt(O);break;case "SKIP":{d.skippedSegments&&Ei(d,K,A);let $=new Re(O,d),q=$.decimalInteger("SKIPPED-SEGMENTS");if(G(q)){d.skippedSegments+=q;for(let N=q;N--;)c.push(null);f+=q;}let Q=$.enumeratedString("RECENTLY-REMOVED-DATERANGES");Q&&(d.recentlyRemovedDateranges=(d.recentlyRemovedDateranges||[]).concat(Q.split(" ")));break}case "TARGETDURATION":d.targetduration!==0&&Ei(d,K,A),d.targetduration=Math.max(parseInt(O),1);break;case "VERSION":d.version!==null&&Ei(d,K,A),d.version=parseInt(O);break;case "INDEPENDENT-SEGMENTS":break;case "ENDLIST":d.live||Ei(d,K,A),d.live=false;break;case "#":(O||Y)&&S.tagList.push(Y?[O,Y]:[O]);break;case "DISCONTINUITY":E++,S.tagList.push(["DIS"]);break;case "GAP":S.gap=true,S.tagList.push([K]);break;case "BITRATE":S.tagList.push([K,O]),v=parseInt(O)*1e3,G(v)?S.bitrate=v:v=0;break;case "DATERANGE":{let $=new Re(O,d),q=new zo($,d.dateRanges[$.ID],d.dateRangeTagCount);d.dateRangeTagCount++,q.isValid||d.skippedSegments?d.dateRanges[q.id]=q:Te.warn(`Ignoring invalid DATERANGE tag: "${O}"`),S.tagList.push(["EXT-X-DATERANGE",O]);break}case "DEFINE":{{let $=new Re(O,d);"IMPORT"in $?YT(d,$,a):Pm(d,$,t);}break}case "DISCONTINUITY-SEQUENCE":d.startCC!==0?Ei(d,K,A):c.length>0&&Wm(d,K,A),d.startCC=E=parseInt(O);break;case "KEY":{let $=Bm(O,t,d);if($.isSupported()){if($.method==="NONE"){D=void 0;break}D||(D={});let q=D[$.keyFormat];q!=null&&q.matches($)||(q&&(D=ye({},D)),D[$.keyFormat]=$);}else Te.warn(`[Keys] Ignoring unsupported EXT-X-KEY tag: "${O}"`);break}case "START":d.startTimeOffset=$m(O);break;case "MAP":{let $=new Re(O,d);if(S.duration){let q=new cn(r,l);Km(q,$,i,D),h=q,S.initSegment=h,h.rawProgramDateTime&&!S.rawProgramDateTime&&(S.rawProgramDateTime=h.rawProgramDateTime);}else {let q=S.byteRangeEndOffset;if(q){let Q=S.byteRangeStartOffset;R=`${q-Q}@${Q}`;}else R=null;Km(S,$,i,D),h=S,k=true;}h.cc=E;break}case "SERVER-CONTROL":{L&&Ei(d,K,A),L=new Re(O),d.canBlockReload=L.bool("CAN-BLOCK-RELOAD"),d.canSkipUntil=L.optionalFloat("CAN-SKIP-UNTIL",0),d.canSkipDateRanges=d.canSkipUntil>0&&L.bool("CAN-SKIP-DATERANGES"),d.partHoldBack=L.optionalFloat("PART-HOLD-BACK",0),d.holdBack=L.optionalFloat("HOLD-BACK",0);break}case "PART-INF":{d.partTarget&&Ei(d,K,A);let $=new Re(O);d.partTarget=$.decimalFloatingPoint("PART-TARGET");break}case "PART":{let $=d.partList;$||($=d.partList=[]);let q=m>0?$[$.length-1]:void 0,Q=m++,N=new Re(O,d),U=new pc(N,S,l,Q,q);$.push(U),S.duration+=U.duration;break}case "PRELOAD-HINT":{let $=new Re(O,d);d.preloadHint=$;break}case "RENDITION-REPORT":{let $=new Re(O,d);d.renditionReports=d.renditionReports||[],d.renditionReports.push($);break}default:Te.warn(`line parsed but not handled: ${A}`);break}}}T&&!T.relurl?(c.pop(),p-=T.duration,d.partList&&(d.fragmentHint=T)):d.partList&&(Dc(S,T,u),S.cc=E,d.fragmentHint=S,D&&Vm(S,D,d)),d.targetduration||(d.playlistParsingError=new Error("Missing Target Duration"));let M=c.length,B=c[0],H=c[M-1];if(p+=d.skippedSegments*d.targetduration,p>0&&M&&H){d.averagetargetduration=p/M;let j=H.sn;d.endSN=j!=="initSegment"?j:0,d.live||(H.endList=true),I>0&&(oy(c,I),B&&u.unshift(B));}return d.fragmentHint&&(p+=d.fragmentHint.duration),d.totalduration=p,u.length&&d.dateRangeTagCount&&B&&jg(u,d),d.endCC=E,d}};function jg(s,e){let t=s.length;if(!t)if(e.hasProgramDateTime){let o=e.fragments[e.fragments.length-1];s.push(o),t++;}else return;let i=s[t-1],r=e.live?1/0:e.totalduration,n=Object.keys(e.dateRanges);for(let o=n.length;o--;){let l=e.dateRanges[n[o]],d=l.startDate.getTime();l.tagAnchor=i.ref;for(let c=t;c--;){var a;if(((a=s[c])==null?void 0:a.sn)<e.startSN)break;let u=ay(e,d,s,c,r);if(u!==-1){l.tagAnchor=e.fragments[u].ref;break}}}}function ay(s,e,t,i,r){let n=t[i];if(n){let o=n.programDateTime;if(e>=o||i===0){var a;let l=(((a=t[i+1])==null?void 0:a.start)||r)-n.start;if(e<=o+l*1e3){let d=t[i].sn-s.startSN;if(d<0)return -1;let c=s.fragments;if(c.length>t.length){let h=(t[i+1]||c[c.length-1]).sn-s.startSN;for(let f=h;f>d;f--){let m=c[f].programDateTime;if(e>=m&&e<m+c[f].duration*1e3)return f}}return d}}}return -1}function Bm(s,e,t){var i,r;let n=new Re(s,t),a=(i=n.METHOD)!=null?i:"",o=n.URI,l=n.hexadecimalInteger("IV"),d=n.KEYFORMATVERSIONS,c=(r=n.KEYFORMAT)!=null?r:"identity";o&&n.IV&&!l&&Te.error(`Invalid IV: ${n.IV}`);let u=o?as.resolve(o,e):"",h=(d||"1").split("/").map(Number).filter(Number.isFinite);return new Tn(a,u,c,h,l,n.KEYID)}function $m(s){let t=new Re(s).decimalFloatingPoint("TIME-OFFSET");return G(t)?t:null}function Gm(s,e){let t=(s||"").split(/[ ,]+/).filter(i=>i);["video","audio","text"].forEach(i=>{let r=t.filter(n=>wu(n,i));r.length&&(e[`${i}Codec`]=r.map(n=>n.split("/")[0]).join(","),t=t.filter(n=>r.indexOf(n)===-1));}),e.unknownCodecs=t;}function Hm(s,e,t){let i=e[t];i&&(s[t]=i);}function oy(s,e){let t=s[e];for(let i=e;i--;){let r=s[i];if(!r)return;r.programDateTime=t.programDateTime-r.duration*1e3,t=r;}}function Dc(s,e,t){s.rawProgramDateTime?t.push(s):e!=null&&e.programDateTime&&(s.programDateTime=e.endProgramDateTime);}function Km(s,e,t,i){s.relurl=e.URI,e.BYTERANGE&&s.setByteRange(e.BYTERANGE),s.level=t,s.sn="initSegment",i&&(s.levelkeys=i),s.initSegment=null;}function Vm(s,e,t){s.levelkeys=e;let{encryptedFragments:i}=t;(!i.length||i[i.length-1].levelkeys!==e)&&Object.keys(e).some(r=>e[r].isCommonEncryption)&&i.push(s);}function Ei(s,e,t){s.playlistParsingError=new Error(`#EXT-X-${e} must not appear more than once (${t[0]})`);}function Wm(s,e,t){s.playlistParsingError=new Error(`#EXT-X-${e} must appear before the first Media Segment (${t[0]})`);}function Qd(s,e){let t=e.startPTS;if(G(t)){let i=0,r;e.sn>s.sn?(i=t-s.start,r=s):(i=s.start-t,r=e),r.duration!==i&&r.setDuration(i);}else e.sn>s.sn?s.cc===e.cc&&s.minEndPTS?e.setStart(s.start+(s.minEndPTS-s.start)):e.setStart(s.start+s.duration):e.setStart(Math.max(s.start-e.duration,0));}function zg(s,e,t,i,r,n,a){i-t<=0&&(a.warn("Fragment should have a positive duration",e),i=t+e.duration,n=r+e.duration);let l=t,d=i,c=e.startPTS,u=e.endPTS;if(G(c)){let v=Math.abs(c-t);s&&v>s.totalduration?a.warn(`media timestamps and playlist times differ by ${v}s for level ${e.level} ${s.url}`):G(e.deltaPTS)?e.deltaPTS=Math.max(v,e.deltaPTS):e.deltaPTS=v,l=Math.max(t,c),t=Math.min(t,c),r=e.startDTS!==void 0?Math.min(r,e.startDTS):r,d=Math.min(i,u),i=Math.max(i,u),n=e.endDTS!==void 0?Math.max(n,e.endDTS):n;}let h=t-e.start;e.start!==0&&e.setStart(t),e.setDuration(i-e.start),e.startPTS=t,e.maxStartPTS=l,e.startDTS=r,e.endPTS=i,e.minEndPTS=d,e.endDTS=n;let f=e.sn;if(!s||f<s.startSN||f>s.endSN)return 0;let m,p=f-s.startSN,E=s.fragments;for(E[p]=e,m=p;m>0;m--)Qd(E[m],E[m-1]);for(m=p;m<E.length-1;m++)Qd(E[m],E[m+1]);return s.fragmentHint&&Qd(E[E.length-1],s.fragmentHint),s.PTSKnown=s.alignedSliding=true,h}function ly(s,e,t){if(s===e)return;let i=null,r=s.fragments;for(let c=r.length-1;c>=0;c--){let u=r[c].initSegment;if(u){i=u;break}}s.fragmentHint&&delete s.fragmentHint.endPTS;let n;uy(s,e,(c,u,h,f)=>{if((!e.startCC||e.skippedSegments)&&u.cc!==c.cc){let m=c.cc-u.cc;for(let p=h;p<f.length;p++)f[p].cc+=m;e.endCC=f[f.length-1].cc;}G(c.startPTS)&&G(c.endPTS)&&(u.setStart(u.startPTS=c.startPTS),u.startDTS=c.startDTS,u.maxStartPTS=c.maxStartPTS,u.endPTS=c.endPTS,u.endDTS=c.endDTS,u.minEndPTS=c.minEndPTS,u.setDuration(c.endPTS-c.startPTS),u.duration&&(n=u),e.PTSKnown=e.alignedSliding=true),c.hasStreams&&(u.elementaryStreams=c.elementaryStreams),u.loader=c.loader,c.hasStats&&(u.stats=c.stats),c.initSegment&&(u.initSegment=c.initSegment,i=c.initSegment);});let a=e.fragments,o=e.fragmentHint?a.concat(e.fragmentHint):a;if(i&&o.forEach(c=>{var u;c&&(!c.initSegment||c.initSegment.relurl===((u=i)==null?void 0:u.relurl))&&(c.initSegment=i);}),e.skippedSegments){if(e.deltaUpdateFailed=a.some(c=>!c),e.deltaUpdateFailed){t.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let c=e.skippedSegments;c--;)a.shift();e.startSN=a[0].sn;}else {e.canSkipDateRanges&&(e.dateRanges=dy(s.dateRanges,e,t));let c=s.fragments.filter(u=>u.rawProgramDateTime);if(s.hasProgramDateTime&&!e.hasProgramDateTime)for(let u=1;u<o.length;u++)o[u].programDateTime===null&&Dc(o[u],o[u-1],c);jg(c,e);}e.endCC=a[a.length-1].cc;}if(!e.startCC){var l;let c=Zg(s,e.startSN-1);e.startCC=(l=c?.cc)!=null?l:a[0].cc;}cy(s.partList,e.partList,(c,u)=>{u.elementaryStreams=c.elementaryStreams,u.stats=c.stats;}),n?zg(e,n,n.startPTS,n.endPTS,n.startDTS,n.endDTS,t):Qg(s,e),a.length&&(e.totalduration=e.edge-a[0].start),e.driftStartTime=s.driftStartTime,e.driftStart=s.driftStart;let d=e.advancedDateTime;if(e.advanced&&d){let c=e.edge;e.driftStart||(e.driftStartTime=d,e.driftStart=c),e.driftEndTime=d,e.driftEnd=c;}else e.driftEndTime=s.driftEndTime,e.driftEnd=s.driftEnd,e.advancedDateTime=s.advancedDateTime;e.requestScheduled===-1&&(e.requestScheduled=s.requestScheduled);}function dy(s,e,t){let{dateRanges:i,recentlyRemovedDateranges:r}=e,n=ye({},s);r&&r.forEach(l=>{delete n[l];});let o=Object.keys(n).length;return o?(Object.keys(i).forEach(l=>{let d=n[l],c=new zo(i[l].attr,d);c.isValid?(n[l]=c,d||(c.tagOrder+=o)):t.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${Ae(i[l].attr)}"`);}),n):i}function cy(s,e,t){if(s&&e){let i=0;for(let r=0,n=s.length;r<=n;r++){let a=s[r],o=e[r+i];a&&o&&a.index===o.index&&a.fragment.sn===o.fragment.sn?t(a,o):i--;}}}function uy(s,e,t){let i=e.skippedSegments,r=Math.max(s.startSN,e.startSN)-e.startSN,n=(s.fragmentHint?1:0)+(i?e.endSN:Math.min(s.endSN,e.endSN))-e.startSN,a=e.startSN-s.startSN,o=e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments,l=s.fragmentHint?s.fragments.concat(s.fragmentHint):s.fragments;for(let d=r;d<=n;d++){let c=l[a+d],u=o[d];if(i&&!u&&c&&(u=e.fragments[d]=c),c&&u){t(c,u,d,o);let h=c.relurl,f=u.relurl;if(h&&hy(h,f)){e.playlistParsingError=Ym(`media sequence mismatch ${u.sn}:`,s,e,c,u);return}else if(c.cc!==u.cc){e.playlistParsingError=Ym(`discontinuity sequence mismatch (${c.cc}!=${u.cc})`,s,e,c,u);return}}}}function Ym(s,e,t,i,r){return new Error(`${s} ${r.url}
1359
+ Time to underbuffer: ${ge.toFixed(3)} s`),r.abortRequests(),this.fragCurrent=this.partCurrent=null,Q>f){let ie=this.findBestLevel(this.hls.levels[f].bitrate,f,Q,0,ge,1,1);ie===-1&&(ie=f),this.hls.nextLoadLevel=this.hls.nextAutoLevel=ie,this.resetEstimator(this.hls.levels[ie].bitrate);}}};E||V>q*2?te():this.timer=self.setInterval(te,q*1e3),a.trigger(g.FRAG_LOAD_EMERGENCY_ABORTED,{frag:r,part:n,stats:c});},this.hls=e,this.bwEstimator=this.initEstimator(),this.registerListeners();}resetEstimator(e){e&&(this.log(`setting initial bwe to ${e}`),this.hls.config.abrEwmaDefaultEstimate=e),this.firstSelection=-1,this.bwEstimator=this.initEstimator();}initEstimator(){let e=this.hls.config;return new fc(e.abrEwmaSlowVoD,e.abrEwmaFastVoD,e.abrEwmaDefaultEstimate)}registerListeners(){let{hls:e}=this;e.on(g.MANIFEST_LOADING,this.onManifestLoading,this),e.on(g.FRAG_LOADING,this.onFragLoading,this),e.on(g.FRAG_LOADED,this.onFragLoaded,this),e.on(g.FRAG_BUFFERED,this.onFragBuffered,this),e.on(g.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(g.LEVEL_LOADED,this.onLevelLoaded,this),e.on(g.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(g.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.on(g.ERROR,this.onError,this);}unregisterListeners(){let{hls:e}=this;e&&(e.off(g.MANIFEST_LOADING,this.onManifestLoading,this),e.off(g.FRAG_LOADING,this.onFragLoading,this),e.off(g.FRAG_LOADED,this.onFragLoaded,this),e.off(g.FRAG_BUFFERED,this.onFragBuffered,this),e.off(g.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(g.LEVEL_LOADED,this.onLevelLoaded,this),e.off(g.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(g.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.off(g.ERROR,this.onError,this));}destroy(){this.unregisterListeners(),this.clearTimer(),this.hls=this._abandonRulesCheck=this.supportedCache=null,this.fragCurrent=this.partCurrent=null;}onManifestLoading(e,t){this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.lastLevelLoadSec=0,this.supportedCache={},this.fragCurrent=this.partCurrent=null,this.onLevelsUpdated(),this.clearTimer();}onLevelsUpdated(){this.lastLoadedFragLevel>-1&&this.fragCurrent&&(this.lastLoadedFragLevel=this.fragCurrent.level),this._nextAutoLevel=-1,this.onMaxAutoLevelUpdated(),this.codecTiers=null,this.audioTracksByGroup=null;}onMaxAutoLevelUpdated(){this.firstSelection=-1,this.nextAutoLevelKey="";}onFragLoading(e,t){let i=t.frag;if(!this.ignoreFragment(i)){if(!i.bitrateTest){var r;this.fragCurrent=i,this.partCurrent=(r=t.part)!=null?r:null;}this.clearTimer(),this.timer=self.setInterval(this._abandonRulesCheck,100);}}onLevelSwitching(e,t){this.clearTimer();}onError(e,t){if(!t.fatal)switch(t.details){case x.BUFFER_ADD_CODEC_ERROR:case x.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case x.FRAG_LOAD_TIMEOUT:{let i=t.frag,{fragCurrent:r,partCurrent:n}=this;if(i&&r&&i.sn===r.sn&&i.level===r.level){let a=performance.now(),o=n?n.stats:i.stats,l=a-o.loading.start,d=o.loading.first?o.loading.first-o.loading.start:-1;if(o.loaded&&d>-1){let u=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(l-Math.min(u,d),o.loaded);}else this.bwEstimator.sampleTTFB(l);}break}}}getTimeToLoadFrag(e,t,i,r){let n=e+i/t,a=r?e+this.lastLevelLoadSec:0;return n+a}onLevelLoaded(e,t){let i=this.hls.config,{loading:r}=t.stats,n=r.end-r.first;G(n)&&(this.lastLevelLoadSec=n/1e3),t.details.live?this.bwEstimator.update(i.abrEwmaSlowLive,i.abrEwmaFastLive):this.bwEstimator.update(i.abrEwmaSlowVoD,i.abrEwmaFastVoD),this.timer>-1&&this._abandonRulesCheck(t.levelInfo);}onFragLoaded(e,{frag:t,part:i}){let r=i?i.stats:t.stats;if(t.type===W.MAIN&&this.bwEstimator.sampleTTFB(r.loading.first-r.loading.start),!this.ignoreFragment(t)){if(this.clearTimer(),t.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,this.hls.config.abrMaxWithRealBitrate){let n=i?i.duration:t.duration,a=this.hls.levels[t.level],o=(a.loaded?a.loaded.bytes:0)+r.loaded,l=(a.loaded?a.loaded.duration:0)+n;a.loaded={bytes:o,duration:l},a.realBitrate=Math.round(8*o/l);}if(t.bitrateTest){let n={stats:r,frag:t,part:i,id:t.type};this.onFragBuffered(g.FRAG_BUFFERED,n),t.bitrateTest=false;}else this.lastLoadedFragLevel=t.level;}}onFragBuffered(e,t){let{frag:i,part:r}=t,n=r!=null&&r.stats.loaded?r.stats:i.stats;if(n.aborted||this.ignoreFragment(i))return;let a=n.parsing.end-n.loading.start-Math.min(n.loading.first-n.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(a,n.loaded),n.bwEstimate=this.getBwEstimate(),i.bitrateTest?this.bitrateTestDelay=a/1e3:this.bitrateTestDelay=0;}ignoreFragment(e){return e.type!==W.MAIN||e.sn==="initSegment"}clearTimer(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1);}get firstAutoLevel(){let{maxAutoLevel:e,minAutoLevel:t}=this.hls,i=this.getBwEstimate(),r=this.hls.config.maxStarvationDelay,n=this.findBestLevel(i,t,e,0,r,1,1);if(n>-1)return n;let a=this.hls.firstLevel,o=Math.min(Math.max(a,t),e);return this.warn(`Could not find best starting auto level. Defaulting to first in playlist ${a} clamped to ${o}`),o}get forcedAutoLevel(){return this.nextAutoLevelKey?-1:this._nextAutoLevel}get nextAutoLevel(){let e=this.forcedAutoLevel,i=this.bwEstimator.canEstimate(),r=this.lastLoadedFragLevel>-1;if(e!==-1&&(!i||!r||this.nextAutoLevelKey===this.getAutoLevelKey()))return e;let n=i&&r?this.getNextABRAutoLevel():this.firstAutoLevel;if(e!==-1){let a=this.hls.levels;if(a.length>Math.max(e,n)&&a[e].loadError<=a[n].loadError)return e}return this._nextAutoLevel=n,this.nextAutoLevelKey=this.getAutoLevelKey(),n}getAutoLevelKey(){return `${this.getBwEstimate()}_${this.getStarvationDelay().toFixed(2)}`}getNextABRAutoLevel(){let{fragCurrent:e,partCurrent:t,hls:i}=this;if(i.levels.length<=1)return i.loadLevel;let{maxAutoLevel:r,config:n,minAutoLevel:a}=i,o=t?t.duration:e?e.duration:0,l=this.getBwEstimate(),d=this.getStarvationDelay(),c=n.abrBandWidthFactor,u=n.abrBandWidthUpFactor;if(d){let E=this.findBestLevel(l,a,r,d,0,c,u);if(E>=0)return this.rebufferNotice=-1,E}let h=o?Math.min(o,n.maxStarvationDelay):n.maxStarvationDelay;if(!d){let E=this.bitrateTestDelay;E&&(h=(o?Math.min(o,n.maxLoadingDelay):n.maxLoadingDelay)-E,this.info(`bitrate test took ${Math.round(1e3*E)}ms, set first fragment max fetchDuration to ${Math.round(1e3*h)} ms`),c=u=1);}let f=this.findBestLevel(l,a,r,d,h,c,u);if(this.rebufferNotice!==f&&(this.rebufferNotice=f,this.info(`${d?"rebuffering expected":"buffer is empty"}, optimal quality level ${f}`)),f>-1)return f;let m=i.levels[a],p=i.loadLevelObj;return p&&m?.bitrate<p.bitrate?a:i.loadLevel}getStarvationDelay(){let e=this.hls,t=e.media;if(!t)return 1/0;let i=t&&t.playbackRate!==0?Math.abs(t.playbackRate):1,r=e.mainForwardBufferInfo;return (r?r.len:0)/i}getBwEstimate(){return this.bwEstimator.canEstimate()?this.bwEstimator.getEstimate():this.hls.config.abrEwmaDefaultEstimate}findBestLevel(e,t,i,r,n,a,o){var l;let d=r+n,c=this.lastLoadedFragLevel,u=c===-1?this.hls.firstLevel:c,{fragCurrent:h,partCurrent:f}=this,{levels:m,allAudioTracks:p,loadLevel:E,config:v}=this.hls;if(m.length===1)return 0;let T=m[u],S=!!((l=this.hls.latestLevelDetails)!=null&&l.live),A=E===-1||c===-1,b,D="SDR",I=T?.frameRate||0,{audioPreference:k,videoPreference:R}=v,L=this.audioTracksByGroup||(this.audioTracksByGroup=Bg(p)),M=-1;if(A){if(this.firstSelection!==-1)return this.firstSelection;let O=this.codecTiers||(this.codecTiers=OT(m,L,t,i)),Y=wT(O,D,e,k,R),{codecSet:$,videoRanges:q,minFramerate:Q,minBitrate:N,minIndex:U,preferHDR:te}=Y;M=U,b=$,D=te?q[q.length-1]:q[0],I=Q,e=Math.max(e,N),this.log(`picked start tier ${Ae(Y)}`);}else b=T?.codecSet,D=T?.videoRange;let B=f?f.duration:h?h.duration:0,K=this.bwEstimator.getEstimateTTFB()/1e3,j=[];for(let O=i;O>=t;O--){var V;let Y=m[O],$=O>u;if(!Y)continue;if(v.useMediaCapabilities&&!Y.supportedResult&&!Y.supportedPromise){let ie=navigator.mediaCapabilities;typeof ie?.decodingInfo=="function"&&_T(Y,L,D,I,e,k)?(Y.supportedPromise=Ng(Y,L,ie,this.supportedCache),Y.supportedPromise.then(de=>{if(!this.hls)return;Y.supportedResult=de;let Be=this.hls.levels,Fe=Be.indexOf(Y);de.error?this.warn(`MediaCapabilities decodingInfo error: "${de.error}" for level ${Fe} ${Ae(de)}`):de.supported?de.decodingInfoResults.some(tt=>tt.smooth===false||tt.powerEfficient===false)&&this.log(`MediaCapabilities decodingInfo for level ${Fe} not smooth or powerEfficient: ${Ae(de)}`):(this.warn(`Unsupported MediaCapabilities decodingInfo result for level ${Fe} ${Ae(de)}`),Fe>-1&&Be.length>1&&(this.log(`Removing unsupported level ${Fe}`),this.hls.removeLevel(Fe),this.hls.loadLevel===-1&&(this.hls.nextLoadLevel=0)));}).catch(de=>{this.warn(`Error handling MediaCapabilities decodingInfo: ${de}`);})):Y.supportedResult=Og;}if((b&&Y.codecSet!==b||D&&Y.videoRange!==D||$&&I>Y.frameRate||!$&&I>0&&I<Y.frameRate||(V=Y.supportedResult)!=null&&(V=V.decodingInfoResults)!=null&&V.some(ie=>ie.smooth===false))&&(!A||O!==M)){j.push(O);continue}let q=Y.details,Q=(f?q?.partTarget:q?.averagetargetduration)||B,N;$?N=o*e:N=a*e;let U=B&&r>=B*2&&n===0?Y.averageBitrate:Y.maxBitrate,te=this.getTimeToLoadFrag(K,N,U*Q,q===void 0);if(N>=U&&(O===c||Y.loadError===0&&Y.fragmentError===0)&&(te<=K||!G(te)||S&&!this.bitrateTestDelay||te<d)){let ie=this.forcedAutoLevel;return O!==E&&(ie===-1||ie!==E)&&(j.length&&this.trace(`Skipped level(s) ${j.join(",")} of ${i} max with CODECS and VIDEO-RANGE:"${m[j[0]].codecs}" ${m[j[0]].videoRange}; not compatible with "${b}" ${D}`),this.info(`switch candidate:${u}->${O} adjustedbw(${Math.round(N)})-bitrate=${Math.round(N-U)} ttfb:${K.toFixed(1)} avgDuration:${Q.toFixed(1)} maxFetchDuration:${d.toFixed(1)} fetchDuration:${te.toFixed(1)} firstSelection:${A} codecSet:${Y.codecSet} videoRange:${Y.videoRange} hls.loadLevel:${E}`)),A&&(this.firstSelection=O),O}}return -1}set nextAutoLevel(e){let t=this.deriveNextAutoLevel(e);this._nextAutoLevel!==t&&(this.nextAutoLevelKey="",this._nextAutoLevel=t);}deriveNextAutoLevel(e){let{maxAutoLevel:t,minAutoLevel:i}=this.hls;return Math.min(Math.max(e,i),t)}},$g={search:function(s,e){let t=0,i=s.length-1,r=null,n=null;for(;t<=i;){r=(t+i)/2|0,n=s[r];let a=e(n);if(a>0)t=r+1;else if(a<0)i=r-1;else return n}return null}};function BT(s,e,t){if(e===null||!Array.isArray(s)||!s.length||!G(e))return null;let i=s[0].programDateTime;if(e<(i||0))return null;let r=s[s.length-1].endProgramDateTime;if(e>=(r||0))return null;for(let n=0;n<s.length;++n){let a=s[n];if(GT(e,t,a))return a}return null}function cs(s,e,t=0,i=0,r=.005){let n=null;if(s){n=e[1+s.sn-e[0].sn]||null;let o=s.endDTS-t;o>0&&o<15e-7&&(t+=15e-7),n&&s.level!==n.level&&n.end<=s.end&&(n=e[2+s.sn-e[0].sn]||null);}else t===0&&e[0].start===0&&(n=e[0]);if(n&&((!s||s.level===n.level)&&Im(t,i,n)===0||$T(n,s,Math.min(r,i))))return n;let a=$g.search(e,Im.bind(null,t,i));return a&&(a!==s||!n)?a:n}function $T(s,e,t){if(e&&e.start===0&&e.level<s.level&&(e.endPTS||0)>0){let i=e.tagList.reduce((r,n)=>(n[0]==="INF"&&(r+=parseFloat(n[1])),r),t);return s.start<=i}return false}function Im(s=0,e=0,t){if(t.start<=s&&t.start+t.duration>s)return 0;let i=Math.min(e,t.duration+(t.deltaPTS?t.deltaPTS:0));return t.start+t.duration-i<=s?1:t.start-i>s&&t.start?-1:0}function GT(s,e,t){let i=Math.min(e,t.duration+(t.deltaPTS?t.deltaPTS:0))*1e3;return (t.endProgramDateTime||0)-i>s}function Gg(s,e,t){if(s&&s.startCC<=e&&s.endCC>=e){let i=s.fragments,{fragmentHint:r}=s;r&&(i=i.concat(r));let n;return $g.search(i,a=>a.cc<e?1:a.cc>e?-1:(n=a,a.end<=t?1:a.start>t?-1:0)),n||null}return null}function Yo(s){switch(s.details){case x.FRAG_LOAD_TIMEOUT:case x.KEY_LOAD_TIMEOUT:case x.LEVEL_LOAD_TIMEOUT:case x.MANIFEST_LOAD_TIMEOUT:return true}return false}function Hg(s){return s.details.startsWith("key")}function Kg(s){return Hg(s)&&!!s.frag&&!s.frag.decryptdata}function Lm(s,e){let t=Yo(e);return s.default[`${t?"timeout":"error"}Retry`]}function Fu(s,e){let t=s.backoff==="linear"?1:Math.pow(2,e);return Math.min(t*s.retryDelayMs,s.maxRetryDelayMs)}function xm(s){return ve(ve({},s),{errorRetry:null,timeoutRetry:null})}function qo(s,e,t,i){if(!s)return false;let r=i?.code,n=e<s.maxNumRetry&&(HT(r)||!!t);return s.shouldRetry?s.shouldRetry(s,e,t,i,n):n}function HT(s){return yc(s)||!!s&&(s<400||s>499)}function yc(s){return s===0&&navigator.onLine===false}var ze={DoNothing:0,SendAlternateToPenaltyBox:2,RemoveAlternatePermanently:3,RetryRequest:5},yt={None:0,MoveAllAlternatesMatchingHost:1,MoveAllAlternatesMatchingHDCP:2,MoveAllAlternatesMatchingKey:4},Sc=class extends ht{constructor(e){super("error-controller",e.logger),this.hls=void 0,this.playlistError=0,this.hls=e,this.registerListeners();}registerListeners(){let e=this.hls;e.on(g.ERROR,this.onError,this),e.on(g.MANIFEST_LOADING,this.onManifestLoading,this),e.on(g.LEVEL_UPDATED,this.onLevelUpdated,this);}unregisterListeners(){let e=this.hls;e&&(e.off(g.ERROR,this.onError,this),e.off(g.ERROR,this.onErrorOut,this),e.off(g.MANIFEST_LOADING,this.onManifestLoading,this),e.off(g.LEVEL_UPDATED,this.onLevelUpdated,this));}destroy(){this.unregisterListeners(),this.hls=null;}startLoad(e){}stopLoad(){this.playlistError=0;}getVariantLevelIndex(e){return e?.type===W.MAIN?e.level:this.getVariantIndex()}getVariantIndex(){var e;let t=this.hls,i=t.currentLevel;return (e=t.loadLevelObj)!=null&&e.details||i===-1?t.loadLevel:i}variantHasKey(e,t){if(e){var i;if((i=e.details)!=null&&i.hasKey(t))return true;let r=e.audioGroups;if(r)return this.hls.allAudioTracks.filter(a=>r.indexOf(a.groupId)>=0).some(a=>{var o;return (o=a.details)==null?void 0:o.hasKey(t)})}return false}onManifestLoading(){this.playlistError=0;}onLevelUpdated(){this.playlistError=0;}onError(e,t){var i;if(t.fatal)return;let r=this.hls,n=t.context;switch(t.details){case x.FRAG_LOAD_ERROR:case x.FRAG_LOAD_TIMEOUT:case x.KEY_LOAD_ERROR:case x.KEY_LOAD_TIMEOUT:t.errorAction=this.getFragRetryOrSwitchAction(t);return;case x.FRAG_PARSING_ERROR:if((i=t.frag)!=null&&i.gap){t.errorAction=ir();return}case x.FRAG_GAP:case x.FRAG_DECRYPT_ERROR:{t.errorAction=this.getFragRetryOrSwitchAction(t),t.errorAction.action=ze.SendAlternateToPenaltyBox;return}case x.LEVEL_EMPTY_ERROR:case x.LEVEL_PARSING_ERROR:{var a;let l=t.parent===W.MAIN?t.level:r.loadLevel;t.details===x.LEVEL_EMPTY_ERROR&&((a=t.context)!=null&&(a=a.levelDetails)!=null&&a.live)?t.errorAction=this.getPlaylistRetryOrSwitchAction(t,l):(t.levelRetry=false,t.errorAction=this.getLevelSwitchAction(t,l));}return;case x.LEVEL_LOAD_ERROR:case x.LEVEL_LOAD_TIMEOUT:typeof n?.level=="number"&&(t.errorAction=this.getPlaylistRetryOrSwitchAction(t,n.level));return;case x.AUDIO_TRACK_LOAD_ERROR:case x.AUDIO_TRACK_LOAD_TIMEOUT:case x.SUBTITLE_LOAD_ERROR:case x.SUBTITLE_TRACK_LOAD_TIMEOUT:if(n){let l=r.loadLevelObj;if(l&&(n.type===ce.AUDIO_TRACK&&l.hasAudioGroup(n.groupId)||n.type===ce.SUBTITLE_TRACK&&l.hasSubtitleGroup(n.groupId))){t.errorAction=this.getPlaylistRetryOrSwitchAction(t,r.loadLevel),t.errorAction.action=ze.SendAlternateToPenaltyBox,t.errorAction.flags=yt.MoveAllAlternatesMatchingHost;return}}return;case x.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:t.errorAction={action:ze.SendAlternateToPenaltyBox,flags:yt.MoveAllAlternatesMatchingHDCP};return;case x.KEY_SYSTEM_SESSION_UPDATE_FAILED:case x.KEY_SYSTEM_STATUS_INTERNAL_ERROR:case x.KEY_SYSTEM_NO_SESSION:t.errorAction={action:ze.SendAlternateToPenaltyBox,flags:yt.MoveAllAlternatesMatchingKey};return;case x.BUFFER_ADD_CODEC_ERROR:case x.REMUX_ALLOC_ERROR:case x.BUFFER_APPEND_ERROR:if(!t.errorAction){var o;t.errorAction=this.getLevelSwitchAction(t,(o=t.level)!=null?o:r.loadLevel);}return;case x.INTERNAL_EXCEPTION:case x.BUFFER_APPENDING_ERROR:case x.BUFFER_FULL_ERROR:case x.LEVEL_SWITCH_ERROR:case x.BUFFER_STALLED_ERROR:case x.BUFFER_SEEK_OVER_HOLE:case x.BUFFER_NUDGE_ON_STALL:t.errorAction=ir();return}t.type===z.KEY_SYSTEM_ERROR&&(t.levelRetry=false,t.errorAction=ir());}getPlaylistRetryOrSwitchAction(e,t){let i=this.hls,r=Lm(i.config.playlistLoadPolicy,e),n=this.playlistError++;if(qo(r,n,Yo(e),e.response))return {action:ze.RetryRequest,flags:yt.None,retryConfig:r,retryCount:n};let o=this.getLevelSwitchAction(e,t);return r&&(o.retryConfig=r,o.retryCount=n),o}getFragRetryOrSwitchAction(e){let t=this.hls,i=this.getVariantLevelIndex(e.frag),r=t.levels[i],{fragLoadPolicy:n,keyLoadPolicy:a}=t.config,o=Lm(Hg(e)?a:n,e),l=t.levels.reduce((c,u)=>c+u.fragmentError,0);if(r&&(e.details!==x.FRAG_GAP&&r.fragmentError++,!Kg(e)&&qo(o,l,Yo(e),e.response)))return {action:ze.RetryRequest,flags:yt.None,retryConfig:o,retryCount:l};let d=this.getLevelSwitchAction(e,i);return o&&(d.retryConfig=o,d.retryCount=l),d}getLevelSwitchAction(e,t){let i=this.hls;t==null&&(t=i.loadLevel);let r=this.hls.levels[t];if(r){var n,a;let d=e.details;r.loadError++,d===x.BUFFER_APPEND_ERROR&&r.fragmentError++;let c=-1,{levels:u,loadLevel:h,minAutoLevel:f,maxAutoLevel:m}=i;!i.autoLevelEnabled&&!i.config.preserveManualLevelOnError&&(i.loadLevel=-1);let p=(n=e.frag)==null?void 0:n.type,v=(p===W.AUDIO&&d===x.FRAG_PARSING_ERROR||e.sourceBufferName==="audio"&&(d===x.BUFFER_ADD_CODEC_ERROR||d===x.BUFFER_APPEND_ERROR))&&u.some(({audioCodec:D})=>r.audioCodec!==D),S=e.sourceBufferName==="video"&&(d===x.BUFFER_ADD_CODEC_ERROR||d===x.BUFFER_APPEND_ERROR)&&u.some(({codecSet:D,audioCodec:I})=>r.codecSet!==D&&r.audioCodec===I),{type:A,groupId:b}=(a=e.context)!=null?a:{};for(let D=u.length;D--;){let I=(D+h)%u.length;if(I!==h&&I>=f&&I<=m&&u[I].loadError===0){var o,l;let k=u[I];if(d===x.FRAG_GAP&&p===W.MAIN&&e.frag){let R=u[I].details;if(R){let L=cs(e.frag,R.fragments,e.frag.start);if(L!=null&&L.gap)continue}}else {if(A===ce.AUDIO_TRACK&&k.hasAudioGroup(b)||A===ce.SUBTITLE_TRACK&&k.hasSubtitleGroup(b))continue;if(p===W.AUDIO&&(o=r.audioGroups)!=null&&o.some(R=>k.hasAudioGroup(R))||p===W.SUBTITLE&&(l=r.subtitleGroups)!=null&&l.some(R=>k.hasSubtitleGroup(R))||v&&r.audioCodec===k.audioCodec||S&&r.codecSet===k.codecSet||!v&&r.codecSet!==k.codecSet)continue}c=I;break}}if(c>-1&&i.loadLevel!==c)return e.levelRetry=true,this.playlistError=0,{action:ze.SendAlternateToPenaltyBox,flags:yt.None,nextAutoLevel:c}}return {action:ze.SendAlternateToPenaltyBox,flags:yt.MoveAllAlternatesMatchingHost}}onErrorOut(e,t){var i;switch((i=t.errorAction)==null?void 0:i.action){case ze.DoNothing:break;case ze.SendAlternateToPenaltyBox:this.sendAlternateToPenaltyBox(t),!t.errorAction.resolved&&t.details!==x.FRAG_GAP?t.fatal=true:/MediaSource readyState: ended/.test(t.error.message)&&(this.warn(`MediaSource ended after "${t.sourceBufferName}" sourceBuffer append error. Attempting to recover from media error.`),this.hls.recoverMediaError());break;}if(t.fatal){this.hls.stopLoad();return}}sendAlternateToPenaltyBox(e){let t=this.hls,i=e.errorAction;if(!i)return;let{flags:r}=i,n=i.nextAutoLevel;switch(r){case yt.None:this.switchLevel(e,n);break;case yt.MoveAllAlternatesMatchingHDCP:{let l=this.getVariantLevelIndex(e.frag),d=t.levels[l],c=d?.attrs["HDCP-LEVEL"];if(i.hdcpLevel=c,c==="NONE")this.warn("HDCP policy resticted output with HDCP-LEVEL=NONE");else if(c){t.maxHdcpLevel=vc[vc.indexOf(c)-1],i.resolved=true,this.warn(`Restricting playback to HDCP-LEVEL of "${t.maxHdcpLevel}" or lower`);break}}case yt.MoveAllAlternatesMatchingKey:{let l=e.decryptdata;if(l){let d=this.hls.levels,c=d.length;for(let h=c;h--;)if(this.variantHasKey(d[h],l)){var a,o;this.log(`Banned key found in level ${h} (${d[h].bitrate}bps) or audio group "${(a=d[h].audioGroups)==null?void 0:a.join(",")}" (${(o=e.frag)==null?void 0:o.type} fragment) ${rt(l.keyId||[])}`),d[h].fragmentError++,d[h].loadError++,this.log(`Removing level ${h} with key error (${e.error})`),this.hls.removeLevel(h);}let u=e.frag;if(this.hls.levels.length<c)i.resolved=true;else if(u&&u.type!==W.MAIN){let h=u.decryptdata;h&&!l.matches(h)&&(i.resolved=true);}}break}}i.resolved||this.switchLevel(e,n);}switchLevel(e,t){if(t!==void 0&&e.errorAction&&(this.warn(`switching to level ${t} after ${e.details}`),this.hls.nextAutoLevel=t,e.errorAction.resolved=true,this.hls.nextLoadLevel=this.hls.nextAutoLevel,e.details===x.BUFFER_ADD_CODEC_ERROR&&e.mimeType&&e.sourceBufferName!=="audiovideo")){let i=Ec(e.mimeType),r=this.hls.levels;for(let n=r.length;n--;)r[n][`${e.sourceBufferName}Codec`]===i&&(this.log(`Removing level ${n} for ${e.details} ("${i}" not supported)`),this.hls.removeLevel(n));}}};function ir(s){let e={action:ze.DoNothing,flags:yt.None};return s&&(e.resolved=true),e}var Ke={NOT_LOADED:"NOT_LOADED",APPENDING:"APPENDING",PARTIAL:"PARTIAL",OK:"OK"},Ac=class{constructor(e){this.activePartLists=Object.create(null),this.endListFragments=Object.create(null),this.fragments=Object.create(null),this.timeRanges=Object.create(null),this.bufferPadding=.2,this.hls=void 0,this.hasGaps=false,this.hls=e,this._registerListeners();}_registerListeners(){let{hls:e}=this;e&&(e.on(g.MANIFEST_LOADING,this.onManifestLoading,this),e.on(g.BUFFER_APPENDED,this.onBufferAppended,this),e.on(g.FRAG_BUFFERED,this.onFragBuffered,this),e.on(g.FRAG_LOADED,this.onFragLoaded,this));}_unregisterListeners(){let{hls:e}=this;e&&(e.off(g.MANIFEST_LOADING,this.onManifestLoading,this),e.off(g.BUFFER_APPENDED,this.onBufferAppended,this),e.off(g.FRAG_BUFFERED,this.onFragBuffered,this),e.off(g.FRAG_LOADED,this.onFragLoaded,this));}destroy(){this._unregisterListeners(),this.hls=this.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null;}getAppendedFrag(e,t){let i=this.activePartLists[t];if(i)for(let r=i.length;r--;){let n=i[r];if(!n)break;if(n.start<=e&&e<=n.end&&n.loaded)return n}return this.getBufferedFrag(e,t)}getBufferedFrag(e,t){return this.getFragAtPos(e,t,true)}getFragAtPos(e,t,i){let{fragments:r}=this,n=Object.keys(r);for(let a=n.length;a--;){let o=r[n[a]];if(o?.body.type===t&&(!i||o.buffered)){let l=o.body;if(l.start<=e&&e<=l.end)return l}}return null}detectEvictedFragments(e,t,i,r,n){this.timeRanges&&(this.timeRanges[e]=t);let a=r?.fragment.sn||-1;Object.keys(this.fragments).forEach(o=>{let l=this.fragments[o];if(!l||a>=l.body.sn)return;if(!l.buffered&&(!l.loaded||n)){l.body.type===i&&this.removeFragment(l.body);return}let d=l.range[e];if(d){if(d.time.length===0){this.removeFragment(l.body);return}d.time.some(c=>{let u=!this.isTimeBuffered(c.startPTS,c.endPTS,t);return u&&this.removeFragment(l.body),u});}});}detectPartialFragments(e){let t=this.timeRanges;if(!t||e.frag.sn==="initSegment")return;let i=e.frag,r=Qs(i),n=this.fragments[r];if(!n||n.buffered&&i.gap)return;let a=!i.relurl;Object.keys(t).forEach(o=>{let l=i.elementaryStreams[o];if(!l)return;let d=t[o],c=a||l.partial===true;n.range[o]=this.getBufferedTimes(i,e.part,c,d);}),n.loaded=null,Object.keys(n.range).length?(n.buffered=true,(n.body.endList=i.endList||n.body.endList)&&(this.endListFragments[n.body.type]=n),yo(n)||this.removeParts(i.sn-1,i.type)):this.removeFragment(n.body);}removeParts(e,t){let i=this.activePartLists[t];i&&(this.activePartLists[t]=Rm(i,r=>r.fragment.sn>=e));}fragBuffered(e,t){let i=Qs(e),r=this.fragments[i];!r&&t&&(r=this.fragments[i]={body:e,appendedPTS:null,loaded:null,buffered:false,range:Object.create(null)},e.gap&&(this.hasGaps=true)),r&&(r.loaded=null,r.buffered=true);}getBufferedTimes(e,t,i,r){let n={time:[],partial:i},a=e.start,o=e.end,l=e.minEndPTS||o,d=e.maxStartPTS||a;for(let c=0;c<r.length;c++){let u=r.start(c)-this.bufferPadding,h=r.end(c)+this.bufferPadding;if(d>=u&&l<=h){n.time.push({startPTS:Math.max(a,r.start(c)),endPTS:Math.min(o,r.end(c))});break}else if(a<h&&o>u){let f=Math.max(a,r.start(c)),m=Math.min(o,r.end(c));m>f&&(n.partial=true,n.time.push({startPTS:f,endPTS:m}));}else if(o<=u)break}return n}getPartialFragment(e){let t=null,i,r,n,a=0,{bufferPadding:o,fragments:l}=this;return Object.keys(l).forEach(d=>{let c=l[d];c&&yo(c)&&(r=c.body.start-o,n=c.body.end+o,e>=r&&e<=n&&(i=Math.min(e-r,n-e),a<=i&&(t=c.body,a=i)));}),t}isEndListAppended(e){let t=this.endListFragments[e];return t!==void 0&&(t.buffered||yo(t))}getState(e){let t=Qs(e),i=this.fragments[t];return i?i.buffered?yo(i)?Ke.PARTIAL:Ke.OK:Ke.APPENDING:Ke.NOT_LOADED}isTimeBuffered(e,t,i){let r,n;for(let a=0;a<i.length;a++){if(r=i.start(a)-this.bufferPadding,n=i.end(a)+this.bufferPadding,e>=r&&t<=n)return true;if(t<=r)return false}return false}onManifestLoading(){this.removeAllFragments();}onFragLoaded(e,t){if(t.frag.sn==="initSegment"||t.frag.bitrateTest)return;let i=t.frag,r=t.part?null:t,n=Qs(i);this.fragments[n]={body:i,appendedPTS:null,loaded:r,buffered:false,range:Object.create(null)};}onBufferAppended(e,t){let{frag:i,part:r,timeRanges:n,type:a}=t;if(i.sn==="initSegment")return;let o=i.type;if(r){let d=this.activePartLists[o];d||(this.activePartLists[o]=d=[]),d.push(r);}this.timeRanges=n;let l=n[a];this.detectEvictedFragments(a,l,o,r);}onFragBuffered(e,t){this.detectPartialFragments(t);}hasFragment(e){let t=Qs(e);return !!this.fragments[t]}hasFragments(e){let{fragments:t}=this,i=Object.keys(t);if(!e)return i.length>0;for(let r=i.length;r--;){let n=t[i[r]];if(n?.body.type===e)return true}return false}hasParts(e){var t;return !!((t=this.activePartLists[e])!=null&&t.length)}removeFragmentsInRange(e,t,i,r,n){r&&!this.hasGaps||Object.keys(this.fragments).forEach(a=>{let o=this.fragments[a];if(!o)return;let l=o.body;l.type!==i||r&&!l.gap||l.start<t&&l.end>e&&(o.buffered||n)&&this.removeFragment(l);});}removeFragment(e){let t=Qs(e);e.clearElementaryStreamInfo();let i=this.activePartLists[e.type];if(i){let r=e.sn;this.activePartLists[e.type]=Rm(i,n=>n.fragment.sn!==r);}delete this.fragments[t],e.endList&&delete this.endListFragments[e.type];}removeAllFragments(){var e;this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=false;let t=(e=this.hls)==null||(e=e.latestLevelDetails)==null?void 0:e.partList;t&&t.forEach(i=>i.clearElementaryStreamInfo());}};function yo(s){var e,t,i;return s.buffered&&!!(s.body.gap||(e=s.range.video)!=null&&e.partial||(t=s.range.audio)!=null&&t.partial||(i=s.range.audiovideo)!=null&&i.partial)}function Qs(s){return `${s.type}_${s.level}_${s.sn}`}function Rm(s,e){return s.filter(t=>{let i=e(t);return i||t.clearElementaryStreamInfo(),i})}var Ni={cbc:0,ctr:1},bc=class{constructor(e,t,i){this.subtle=void 0,this.aesIV=void 0,this.aesMode=void 0,this.subtle=e,this.aesIV=t,this.aesMode=i;}decrypt(e,t){switch(this.aesMode){case Ni.cbc:return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},t,e);case Ni.ctr:return this.subtle.decrypt({name:"AES-CTR",counter:this.aesIV,length:64},t,e);default:throw new Error(`[AESCrypto] invalid aes mode ${this.aesMode}`)}}};function KT(s){let e=s.byteLength,t=e&&new DataView(s.buffer).getUint8(e-1);return t?s.slice(0,e-t):s}var _c=class{constructor(){this.rcon=[0,1,2,4,8,16,32,64,128,27,54],this.subMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.invSubMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.sBox=new Uint32Array(256),this.invSBox=new Uint32Array(256),this.key=new Uint32Array(0),this.ksRows=0,this.keySize=0,this.keySchedule=void 0,this.invKeySchedule=void 0,this.initTable();}uint8ArrayToUint32Array_(e){let t=new DataView(e),i=new Uint32Array(4);for(let r=0;r<4;r++)i[r]=t.getUint32(r*4);return i}initTable(){let e=this.sBox,t=this.invSBox,i=this.subMix,r=i[0],n=i[1],a=i[2],o=i[3],l=this.invSubMix,d=l[0],c=l[1],u=l[2],h=l[3],f=new Uint32Array(256),m=0,p=0,E=0;for(E=0;E<256;E++)E<128?f[E]=E<<1:f[E]=E<<1^283;for(E=0;E<256;E++){let v=p^p<<1^p<<2^p<<3^p<<4;v=v>>>8^v&255^99,e[m]=v,t[v]=m;let T=f[m],S=f[T],A=f[S],b=f[v]*257^v*16843008;r[m]=b<<24|b>>>8,n[m]=b<<16|b>>>16,a[m]=b<<8|b>>>24,o[m]=b,b=A*16843009^S*65537^T*257^m*16843008,d[v]=b<<24|b>>>8,c[v]=b<<16|b>>>16,u[v]=b<<8|b>>>24,h[v]=b,m?(m=T^f[f[f[A^T]]],p^=f[f[p]]):m=p=1;}}expandKey(e){let t=this.uint8ArrayToUint32Array_(e),i=true,r=0;for(;r<t.length&&i;)i=t[r]===this.key[r],r++;if(i)return;this.key=t;let n=this.keySize=t.length;if(n!==4&&n!==6&&n!==8)throw new Error("Invalid aes key size="+n);let a=this.ksRows=(n+6+1)*4,o,l,d=this.keySchedule=new Uint32Array(a),c=this.invKeySchedule=new Uint32Array(a),u=this.sBox,h=this.rcon,f=this.invSubMix,m=f[0],p=f[1],E=f[2],v=f[3],T,S;for(o=0;o<a;o++){if(o<n){T=d[o]=t[o];continue}S=T,o%n===0?(S=S<<8|S>>>24,S=u[S>>>24]<<24|u[S>>>16&255]<<16|u[S>>>8&255]<<8|u[S&255],S^=h[o/n|0]<<24):n>6&&o%n===4&&(S=u[S>>>24]<<24|u[S>>>16&255]<<16|u[S>>>8&255]<<8|u[S&255]),d[o]=T=(d[o-n]^S)>>>0;}for(l=0;l<a;l++)o=a-l,l&3?S=d[o]:S=d[o-4],l<4||o<=4?c[l]=S:c[l]=m[u[S>>>24]]^p[u[S>>>16&255]]^E[u[S>>>8&255]]^v[u[S&255]],c[l]=c[l]>>>0;}networkToHostOrderSwap(e){return e<<24|(e&65280)<<8|(e&16711680)>>8|e>>>24}decrypt(e,t,i){let r=this.keySize+6,n=this.invKeySchedule,a=this.invSBox,o=this.invSubMix,l=o[0],d=o[1],c=o[2],u=o[3],h=this.uint8ArrayToUint32Array_(i),f=h[0],m=h[1],p=h[2],E=h[3],v=new Int32Array(e),T=new Int32Array(v.length),S,A,b,D,I,k,R,L,M,B,K,j,V,O,Y=this.networkToHostOrderSwap;for(;t<v.length;){for(M=Y(v[t]),B=Y(v[t+1]),K=Y(v[t+2]),j=Y(v[t+3]),I=M^n[0],k=j^n[1],R=K^n[2],L=B^n[3],V=4,O=1;O<r;O++)S=l[I>>>24]^d[k>>16&255]^c[R>>8&255]^u[L&255]^n[V],A=l[k>>>24]^d[R>>16&255]^c[L>>8&255]^u[I&255]^n[V+1],b=l[R>>>24]^d[L>>16&255]^c[I>>8&255]^u[k&255]^n[V+2],D=l[L>>>24]^d[I>>16&255]^c[k>>8&255]^u[R&255]^n[V+3],I=S,k=A,R=b,L=D,V=V+4;S=a[I>>>24]<<24^a[k>>16&255]<<16^a[R>>8&255]<<8^a[L&255]^n[V],A=a[k>>>24]<<24^a[R>>16&255]<<16^a[L>>8&255]<<8^a[I&255]^n[V+1],b=a[R>>>24]<<24^a[L>>16&255]<<16^a[I>>8&255]<<8^a[k&255]^n[V+2],D=a[L>>>24]<<24^a[I>>16&255]<<16^a[k>>8&255]<<8^a[R&255]^n[V+3],T[t]=Y(S^f),T[t+1]=Y(D^m),T[t+2]=Y(b^p),T[t+3]=Y(A^E),f=M,m=B,p=K,E=j,t=t+4;}return T.buffer}},Ic=class{constructor(e,t,i){this.subtle=void 0,this.key=void 0,this.aesMode=void 0,this.subtle=e,this.key=t,this.aesMode=i;}expandKey(){let e=VT(this.aesMode);return this.subtle.importKey("raw",this.key,{name:e},false,["encrypt","decrypt"])}};function VT(s){switch(s){case Ni.cbc:return "AES-CBC";case Ni.ctr:return "AES-CTR";default:throw new Error(`[FastAESKey] invalid aes mode ${s}`)}}var WT=16,En=class{constructor(e,{removePKCS7Padding:t=true}={}){if(this.logEnabled=true,this.removePKCS7Padding=void 0,this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null,this.useSoftware=void 0,this.enableSoftwareAES=void 0,this.enableSoftwareAES=e.enableSoftwareAES,this.removePKCS7Padding=t,t)try{let i=self.crypto;i&&(this.subtle=i.subtle||i.webkitSubtle);}catch{}this.useSoftware=!this.subtle;}destroy(){this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null;}isSync(){return this.useSoftware}flush(){let{currentResult:e,remainderData:t}=this;if(!e||t)return this.reset(),null;let i=new Uint8Array(e);return this.reset(),this.removePKCS7Padding?KT(i):i}reset(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&(this.softwareDecrypter=null);}decrypt(e,t,i,r){return this.useSoftware?new Promise((n,a)=>{let o=ArrayBuffer.isView(e)?e:new Uint8Array(e);this.softwareDecrypt(o,t,i,r);let l=this.flush();l?n(l.buffer):a(new Error("[softwareDecrypt] Failed to decrypt data"));}):this.webCryptoDecrypt(new Uint8Array(e),t,i,r)}softwareDecrypt(e,t,i,r){let{currentIV:n,currentResult:a,remainderData:o}=this;if(r!==Ni.cbc||t.byteLength!==16)return Te.warn("SoftwareDecrypt: can only handle AES-128-CBC"),null;this.logOnce("JS AES decrypt"),o&&(e=Dt(o,e),this.remainderData=null);let l=this.getValidChunk(e);if(!l.length)return null;n&&(i=n);let d=this.softwareDecrypter;d||(d=this.softwareDecrypter=new _c),d.expandKey(t);let c=a;return this.currentResult=d.decrypt(l.buffer,0,i),this.currentIV=l.slice(-16).buffer,c||null}webCryptoDecrypt(e,t,i,r){if(this.key!==t||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(e,t,i,r));this.key=t,this.fastAesKey=new Ic(this.subtle,t,r);}return this.fastAesKey.expandKey().then(n=>this.subtle?(this.logOnce("WebCrypto AES decrypt"),new bc(this.subtle,new Uint8Array(i),r).decrypt(e.buffer,n)):Promise.reject(new Error("web crypto not initialized"))).catch(n=>(Te.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${n.name}: ${n.message}`),this.onWebCryptoError(e,t,i,r)))}onWebCryptoError(e,t,i,r){let n=this.enableSoftwareAES;if(n){this.useSoftware=true,this.logEnabled=true,this.softwareDecrypt(e,t,i,r);let a=this.flush();if(a)return a.buffer}throw new Error("WebCrypto"+(n?" and softwareDecrypt":"")+": failed to decrypt data")}getValidChunk(e){let t=e,i=e.length-e.length%WT;return i!==e.length&&(t=e.slice(0,i),this.remainderData=e.slice(i)),t}logOnce(e){this.logEnabled&&(Te.log(`[decrypter]: ${e}`),this.logEnabled=false);}},km=Math.pow(2,17),Lc=class{constructor(e){this.config=void 0,this.loader=null,this.partLoadTimeout=-1,this.config=e;}destroy(){this.loader&&(this.loader.destroy(),this.loader=null);}abort(){this.loader&&this.loader.abort();}load(e,t){let i=e.url;if(!i)return Promise.reject(new Ht({type:z.NETWORK_ERROR,details:x.FRAG_LOAD_ERROR,fatal:false,frag:e,error:new Error(`Fragment does not have a ${i?"part list":"url"}`),networkDetails:null}));this.abort();let r=this.config,n=r.fLoader,a=r.loader;return new Promise((o,l)=>{if(this.loader&&this.loader.destroy(),e.gap)if(e.tagList.some(m=>m[0]==="GAP")){l(Cm(e));return}else e.gap=false;let d=this.loader=n?new n(r):new a(r),c=Dm(e);e.loader=d;let u=xm(r.fragLoadPolicy.default),h={loadPolicy:u,timeout:u.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:e.sn==="initSegment"?1/0:km};e.stats=d.stats;let f={onSuccess:(m,p,E,v)=>{this.resetLoader(e,d);let T=m.data;E.resetIV&&e.decryptdata&&(e.decryptdata.iv=new Uint8Array(T.slice(0,16)),T=T.slice(16)),o({frag:e,part:null,payload:T,networkDetails:v});},onError:(m,p,E,v)=>{this.resetLoader(e,d),l(new Ht({type:z.NETWORK_ERROR,details:x.FRAG_LOAD_ERROR,fatal:false,frag:e,response:ve({url:i,data:void 0},m),error:new Error(`HTTP Error ${m.code} ${m.text}`),networkDetails:E,stats:v}));},onAbort:(m,p,E)=>{this.resetLoader(e,d),l(new Ht({type:z.NETWORK_ERROR,details:x.INTERNAL_ABORTED,fatal:false,frag:e,error:new Error("Aborted"),networkDetails:E,stats:m}));},onTimeout:(m,p,E)=>{this.resetLoader(e,d),l(new Ht({type:z.NETWORK_ERROR,details:x.FRAG_LOAD_TIMEOUT,fatal:false,frag:e,error:new Error(`Timeout after ${h.timeout}ms`),networkDetails:E,stats:m}));}};t&&(f.onProgress=(m,p,E,v)=>t({frag:e,part:null,payload:E,networkDetails:v})),d.load(c,h,f);})}loadPart(e,t,i){this.abort();let r=this.config,n=r.fLoader,a=r.loader;return new Promise((o,l)=>{if(this.loader&&this.loader.destroy(),e.gap||t.gap){l(Cm(e,t));return}let d=this.loader=n?new n(r):new a(r),c=Dm(e,t);e.loader=d;let u=xm(r.fragLoadPolicy.default),h={loadPolicy:u,timeout:u.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:km};t.stats=d.stats,d.load(c,h,{onSuccess:(f,m,p,E)=>{this.resetLoader(e,d),this.updateStatsFromPart(e,t);let v={frag:e,part:t,payload:f.data,networkDetails:E};i(v),o(v);},onError:(f,m,p,E)=>{this.resetLoader(e,d),l(new Ht({type:z.NETWORK_ERROR,details:x.FRAG_LOAD_ERROR,fatal:false,frag:e,part:t,response:ve({url:c.url,data:void 0},f),error:new Error(`HTTP Error ${f.code} ${f.text}`),networkDetails:p,stats:E}));},onAbort:(f,m,p)=>{e.stats.aborted=t.stats.aborted,this.resetLoader(e,d),l(new Ht({type:z.NETWORK_ERROR,details:x.INTERNAL_ABORTED,fatal:false,frag:e,part:t,error:new Error("Aborted"),networkDetails:p,stats:f}));},onTimeout:(f,m,p)=>{this.resetLoader(e,d),l(new Ht({type:z.NETWORK_ERROR,details:x.FRAG_LOAD_TIMEOUT,fatal:false,frag:e,part:t,error:new Error(`Timeout after ${h.timeout}ms`),networkDetails:p,stats:f}));}});})}updateStatsFromPart(e,t){let i=e.stats,r=t.stats,n=r.total;if(i.loaded+=r.loaded,n){let l=Math.round(e.duration/t.duration),d=Math.min(Math.round(i.loaded/n),l),u=(l-d)*Math.round(i.loaded/d);i.total=i.loaded+u;}else i.total=Math.max(i.loaded,i.total);let a=i.loading,o=r.loading;a.start?a.first+=o.first-o.start:(a.start=o.start,a.first=o.first),a.end=o.end;}resetLoader(e,t){e.loader=null,this.loader===t&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),t.destroy();}};function Dm(s,e=null){let t=e||s,i={frag:s,part:e,responseType:"arraybuffer",url:t.url,headers:{},rangeStart:0,rangeEnd:0},r=t.byteRangeStartOffset,n=t.byteRangeEndOffset;if(G(r)&&G(n)){var a;let o=r,l=n;if(s.sn==="initSegment"&&YT((a=s.decryptdata)==null?void 0:a.method)){let d=n-r;d%16&&(l=n+(16-d%16)),r!==0&&(i.resetIV=true,o=r-16);}i.rangeStart=o,i.rangeEnd=l;}return i}function Cm(s,e){let t=new Error(`GAP ${s.gap?"tag":"attribute"} found`),i={type:z.MEDIA_ERROR,details:x.FRAG_GAP,fatal:false,frag:s,error:t,networkDetails:null};return e&&(i.part=e),(e||s).stats.aborted=true,new Ht(i)}function YT(s){return s==="AES-128"||s==="AES-256"}var Ht=class extends Error{constructor(e){super(e.error.message),this.data=void 0,this.data=e;}},jo=class extends ht{constructor(e,t){super(e,t),this._boundTick=void 0,this._tickTimer=null,this._tickInterval=null,this._tickCallCount=0,this._boundTick=this.tick.bind(this);}destroy(){this.onHandlerDestroying(),this.onHandlerDestroyed();}onHandlerDestroying(){this.clearNextTick(),this.clearInterval();}onHandlerDestroyed(){}hasInterval(){return !!this._tickInterval}hasNextTick(){return !!this._tickTimer}setInterval(e){return this._tickInterval?false:(this._tickCallCount=0,this._tickInterval=self.setInterval(this._boundTick,e),true)}clearInterval(){return this._tickInterval?(self.clearInterval(this._tickInterval),this._tickInterval=null,true):false}clearNextTick(){return this._tickTimer?(self.clearTimeout(this._tickTimer),this._tickTimer=null,true):false}tick(){this._tickCallCount++,this._tickCallCount===1&&(this.doTick(),this._tickCallCount>1&&this.tickImmediate(),this._tickCallCount=0);}tickImmediate(){this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0);}doTick(){}},vn=class{constructor(e,t,i,r=0,n=-1,a=false){this.level=void 0,this.sn=void 0,this.part=void 0,this.id=void 0,this.size=void 0,this.partial=void 0,this.transmuxing=So(),this.buffering={audio:So(),video:So(),audiovideo:So()},this.level=e,this.sn=t,this.id=i,this.size=r,this.part=n,this.partial=a;}};function So(){return {start:0,executeStart:0,executeEnd:0,end:0}}var Mm={length:0,start:()=>0,end:()=>0},re=class s{static isBuffered(e,t){if(e){let i=s.getBuffered(e);for(let r=i.length;r--;)if(t>=i.start(r)&&t<=i.end(r))return true}return false}static bufferedRanges(e){if(e){let t=s.getBuffered(e);return s.timeRangesToArray(t)}return []}static timeRangesToArray(e){let t=[];for(let i=0;i<e.length;i++)t.push({start:e.start(i),end:e.end(i)});return t}static bufferInfo(e,t,i){if(e){let r=s.bufferedRanges(e);if(r.length)return s.bufferedInfo(r,t,i)}return {len:0,start:t,end:t,bufferedIndex:-1}}static bufferedInfo(e,t,i){t=Math.max(0,t),e.length>1&&e.sort((c,u)=>c.start-u.start||u.end-c.end);let r=-1,n=[];if(i)for(let c=0;c<e.length;c++){t>=e[c].start&&t<=e[c].end&&(r=c);let u=n.length;if(u){let h=n[u-1].end;e[c].start-h<i?e[c].end>h&&(n[u-1].end=e[c].end):n.push(e[c]);}else n.push(e[c]);}else n=e;let a=0,o,l=t,d=t;for(let c=0;c<n.length;c++){let u=n[c].start,h=n[c].end;if(r===-1&&t>=u&&t<=h&&(r=c),t+i>=u&&t<h)l=u,d=h,a=d-t;else if(t+i<u){o=u;break}}return {len:a,start:l||0,end:d||0,nextStart:o,buffered:e,bufferedIndex:r}}static getBuffered(e){try{return e.buffered||Mm}catch(t){return Te.log("failed to get media.buffered",t),Mm}}},Vg=/\{\$([a-zA-Z0-9-_]+)\}/g;function Pm(s){return Vg.test(s)}function xc(s,e){if(s.variableList!==null||s.hasVariableRefs){let t=s.variableList;return e.replace(Vg,i=>{let r=i.substring(2,i.length-1),n=t?.[r];return n===void 0?(s.playlistParsingError||(s.playlistParsingError=new Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${r}"`)),i):n})}return e}function wm(s,e,t){let i=s.variableList;i||(s.variableList=i={});let r,n;if("QUERYPARAM"in e){r=e.QUERYPARAM;try{let a=new self.URL(t).searchParams;if(a.has(r))n=a.get(r);else throw new Error(`"${r}" does not match any query parameter in URI: "${t}"`)}catch(a){s.playlistParsingError||(s.playlistParsingError=new Error(`EXT-X-DEFINE QUERYPARAM: ${a.message}`));}}else r=e.NAME,n=e.VALUE;r in i?s.playlistParsingError||(s.playlistParsingError=new Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${r}"`)):i[r]=n||"";}function qT(s,e,t){let i=e.IMPORT;if(t&&i in t){let r=s.variableList;r||(s.variableList=r={}),r[i]=t[i];}else s.playlistParsingError||(s.playlistParsingError=new Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${i}"`));}var jT=/^(\d+)x(\d+)$/,Om=/(.+?)=(".*?"|.*?)(?:,|$)/g,Re=class s{constructor(e,t){typeof e=="string"&&(e=s.parseAttrList(e,t)),ye(this,e);}get clientAttrs(){return Object.keys(this).filter(e=>e.substring(0,2)==="X-")}decimalInteger(e){let t=parseInt(this[e],10);return t>Number.MAX_SAFE_INTEGER?1/0:t}hexadecimalInteger(e){if(this[e]){let t=(this[e]||"0x").slice(2);t=(t.length&1?"0":"")+t;let i=new Uint8Array(t.length/2);for(let r=0;r<t.length/2;r++)i[r]=parseInt(t.slice(r*2,r*2+2),16);return i}return null}hexadecimalIntegerAsNumber(e){let t=parseInt(this[e],16);return t>Number.MAX_SAFE_INTEGER?1/0:t}decimalFloatingPoint(e){return parseFloat(this[e])}optionalFloat(e,t){let i=this[e];return i?parseFloat(i):t}enumeratedString(e){return this[e]}enumeratedStringList(e,t){let i=this[e];return (i?i.split(/[ ,]+/):[]).reduce((r,n)=>(r[n.toLowerCase()]=true,r),t)}bool(e){return this[e]==="YES"}decimalResolution(e){let t=jT.exec(this[e]);if(t!==null)return {width:parseInt(t[1],10),height:parseInt(t[2],10)}}static parseAttrList(e,t){let i,r={},n='"';for(Om.lastIndex=0;(i=Om.exec(e))!==null;){let a=i[1].trim(),o=i[2],l=o.indexOf(n)===0&&o.lastIndexOf(n)===o.length-1,d=false;if(l)o=o.slice(1,-1);else switch(a){case "IV":case "SCTE35-CMD":case "SCTE35-IN":case "SCTE35-OUT":d=true;}if(t&&(l||d))o=xc(t,o);else if(!d&&!l)switch(a){case "CLOSED-CAPTIONS":if(o==="NONE")break;case "ALLOWED-CPC":case "CLASS":case "ASSOC-LANGUAGE":case "AUDIO":case "BYTERANGE":case "CHANNELS":case "CHARACTERISTICS":case "CODECS":case "DATA-ID":case "END-DATE":case "GROUP-ID":case "ID":case "IMPORT":case "INSTREAM-ID":case "KEYFORMAT":case "KEYFORMATVERSIONS":case "LANGUAGE":case "NAME":case "PATHWAY-ID":case "QUERYPARAM":case "RECENTLY-REMOVED-DATERANGES":case "SERVER-URI":case "STABLE-RENDITION-ID":case "STABLE-VARIANT-ID":case "START-DATE":case "SUBTITLES":case "SUPPLEMENTAL-CODECS":case "URI":case "VALUE":case "VIDEO":case "X-ASSET-LIST":case "X-ASSET-URI":Te.warn(`${e}: attribute ${a} is missing quotes`);}r[a]=o;}return r}},zT="com.apple.hls.interstitial";function QT(s){return s!=="ID"&&s!=="CLASS"&&s!=="CUE"&&s!=="START-DATE"&&s!=="DURATION"&&s!=="END-DATE"&&s!=="END-ON-NEXT"}function XT(s){return s==="SCTE35-OUT"||s==="SCTE35-IN"||s==="SCTE35-CMD"}var zo=class{constructor(e,t,i=0){var r;if(this.attr=void 0,this.tagAnchor=void 0,this.tagOrder=void 0,this._startDate=void 0,this._endDate=void 0,this._dateAtEnd=void 0,this._cue=void 0,this._badValueForSameId=void 0,this.tagAnchor=t?.tagAnchor||null,this.tagOrder=(r=t?.tagOrder)!=null?r:i,t){let n=t.attr;for(let a in n)if(Object.prototype.hasOwnProperty.call(e,a)&&e[a]!==n[a]){Te.warn(`DATERANGE tag attribute: "${a}" does not match for tags with ID: "${e.ID}"`),this._badValueForSameId=a;break}e=ye(new Re({}),n,e);}if(this.attr=e,t?(this._startDate=t._startDate,this._cue=t._cue,this._endDate=t._endDate,this._dateAtEnd=t._dateAtEnd):this._startDate=new Date(e["START-DATE"]),"END-DATE"in this.attr){let n=t?.endDate||new Date(this.attr["END-DATE"]);G(n.getTime())&&(this._endDate=n);}}get id(){return this.attr.ID}get class(){return this.attr.CLASS}get cue(){let e=this._cue;return e===void 0?this._cue=this.attr.enumeratedStringList(this.attr.CUE?"CUE":"X-CUE",{pre:false,post:false,once:false}):e}get startTime(){let{tagAnchor:e}=this;return e===null||e.programDateTime===null?(Te.warn(`Expected tagAnchor Fragment with PDT set for DateRange "${this.id}": ${e}`),NaN):e.start+(this.startDate.getTime()-e.programDateTime)/1e3}get startDate(){return this._startDate}get endDate(){let e=this._endDate||this._dateAtEnd;if(e)return e;let t=this.duration;return t!==null?this._dateAtEnd=new Date(this._startDate.getTime()+t*1e3):null}get duration(){if("DURATION"in this.attr){let e=this.attr.decimalFloatingPoint("DURATION");if(G(e))return e}else if(this._endDate)return (this._endDate.getTime()-this._startDate.getTime())/1e3;return null}get plannedDuration(){return "PLANNED-DURATION"in this.attr?this.attr.decimalFloatingPoint("PLANNED-DURATION"):null}get endOnNext(){return this.attr.bool("END-ON-NEXT")}get isInterstitial(){return this.class===zT}get isValid(){return !!this.id&&!this._badValueForSameId&&G(this.startDate.getTime())&&(this.duration===null||this.duration>=0)&&(!this.endOnNext||!!this.class)&&(!this.attr.CUE||!this.cue.pre&&!this.cue.post||this.cue.pre!==this.cue.post)&&(!this.isInterstitial||"X-ASSET-URI"in this.attr||"X-ASSET-LIST"in this.attr)}},ZT=10,Rc=class{constructor(e){this.PTSKnown=false,this.alignedSliding=false,this.averagetargetduration=void 0,this.endCC=0,this.endSN=0,this.fragments=void 0,this.fragmentHint=void 0,this.partList=null,this.dateRanges=void 0,this.dateRangeTagCount=0,this.live=true,this.requestScheduled=-1,this.ageHeader=0,this.advancedDateTime=void 0,this.updated=true,this.advanced=true,this.misses=0,this.startCC=0,this.startSN=0,this.startTimeOffset=null,this.targetduration=0,this.totalduration=0,this.type=null,this.url=void 0,this.m3u8="",this.version=null,this.canBlockReload=false,this.canSkipUntil=0,this.canSkipDateRanges=false,this.skippedSegments=0,this.recentlyRemovedDateranges=void 0,this.partHoldBack=0,this.holdBack=0,this.partTarget=0,this.preloadHint=void 0,this.renditionReports=void 0,this.tuneInGoal=0,this.deltaUpdateFailed=void 0,this.driftStartTime=0,this.driftEndTime=0,this.driftStart=0,this.driftEnd=0,this.encryptedFragments=void 0,this.playlistParsingError=null,this.variableList=null,this.hasVariableRefs=false,this.appliedTimelineOffset=void 0,this.fragments=[],this.encryptedFragments=[],this.dateRanges={},this.url=e;}reloaded(e){if(!e){this.advanced=true,this.updated=true;return}let t=this.lastPartSn-e.lastPartSn,i=this.lastPartIndex-e.lastPartIndex;this.updated=this.endSN!==e.endSN||!!i||!!t||!this.live,this.advanced=this.endSN>e.endSN||t>0||t===0&&i>0,this.updated||this.advanced?this.misses=Math.floor(e.misses*.6):this.misses=e.misses+1;}hasKey(e){return this.encryptedFragments.some(t=>{let i=t.decryptdata;return i||(t.setKeyFormat(e.keyFormat),i=t.decryptdata),!!i&&e.matches(i)})}get hasProgramDateTime(){return this.fragments.length?G(this.fragments[this.fragments.length-1].programDateTime):false}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||ZT}get drift(){let e=this.driftEndTime-this.driftStartTime;return e>0?(this.driftEnd-this.driftStart)*1e3/e:1}get edge(){return this.partEnd||this.fragmentEnd}get partEnd(){var e;return (e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].end:this.fragmentEnd}get fragmentEnd(){return this.fragments.length?this.fragments[this.fragments.length-1].end:0}get fragmentStart(){return this.fragments.length?this.fragments[0].start:0}get age(){return this.advancedDateTime?Math.max(Date.now()-this.advancedDateTime,0)/1e3:0}get lastPartIndex(){var e;return (e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].index:-1}get maxPartIndex(){let e=this.partList;if(e){let t=this.lastPartIndex;if(t!==-1){for(let i=e.length;i--;)if(e[i].index>t)return e[i].index;return t}}return 0}get lastPartSn(){var e;return (e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}get expired(){if(this.live&&this.age&&this.misses<3){let e=this.partEnd-this.fragmentStart;return this.age>Math.max(e,this.totalduration)+this.levelTargetDuration}return false}};function Qo(s,e){return s.length===e.length?!s.some((t,i)=>t!==e[i]):false}function Fm(s,e){return !s&&!e?true:!s||!e?false:Qo(s,e)}function sr(s){return s==="AES-128"||s==="AES-256"||s==="AES-256-CTR"}function Nu(s){switch(s){case "AES-128":case "AES-256":return Ni.cbc;case "AES-256-CTR":return Ni.ctr;default:throw new Error(`invalid full segment method ${s}`)}}function Uu(s){return Uint8Array.from(atob(s),e=>e.charCodeAt(0))}function kc(s){return Uint8Array.from(unescape(encodeURIComponent(s)),e=>e.charCodeAt(0))}function JT(s){let e=kc(s).subarray(0,16),t=new Uint8Array(16);return t.set(e,16-e.length),t}function Wg(s){let e=function(i,r,n){let a=i[r];i[r]=i[n],i[n]=a;};e(s,0,3),e(s,1,2),e(s,4,5),e(s,6,7);}function Yg(s){let e=s.split(":"),t=null;if(e[0]==="data"&&e.length===2){let i=e[1].split(";"),r=i[i.length-1].split(",");if(r.length===2){let n=r[0]==="base64",a=r[1];n?(i.splice(-1,1),t=Uu(a)):t=JT(a);}}return t}var Xo=typeof self<"u"?self:void 0,ke={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},Xe={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.streamingkeydelivery",PLAYREADY:"com.microsoft.playready",WIDEVINE:"urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed"};function Oo(s){switch(s){case Xe.FAIRPLAY:return ke.FAIRPLAY;case Xe.PLAYREADY:return ke.PLAYREADY;case Xe.WIDEVINE:return ke.WIDEVINE;case Xe.CLEARKEY:return ke.CLEARKEY}}function jd(s){switch(s){case ke.FAIRPLAY:return Xe.FAIRPLAY;case ke.PLAYREADY:return Xe.PLAYREADY;case ke.WIDEVINE:return Xe.WIDEVINE;case ke.CLEARKEY:return Xe.CLEARKEY}}function dn(s){let{drmSystems:e,widevineLicenseUrl:t}=s,i=e?[ke.FAIRPLAY,ke.WIDEVINE,ke.PLAYREADY,ke.CLEARKEY].filter(r=>!!e[r]):[];return !i[ke.WIDEVINE]&&t&&i.push(ke.WIDEVINE),i}var qg=function(s){return Xo!=null&&(s=Xo.navigator)!=null&&s.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null}();function ey(s,e,t,i){let r;switch(s){case ke.FAIRPLAY:r=["cenc","sinf"];break;case ke.WIDEVINE:case ke.PLAYREADY:r=["cenc"];break;case ke.CLEARKEY:r=["cenc","keyids"];break;default:throw new Error(`Unknown key-system: ${s}`)}return ty(r,e,t,i)}function ty(s,e,t,i){return [{initDataTypes:s,persistentState:i.persistentState||"optional",distinctiveIdentifier:i.distinctiveIdentifier||"optional",sessionTypes:i.sessionTypes||[i.sessionType||"temporary"],audioCapabilities:e.map(n=>({contentType:`audio/mp4; codecs=${n}`,robustness:i.audioRobustness||"",encryptionScheme:i.audioEncryptionScheme||null})),videoCapabilities:t.map(n=>({contentType:`video/mp4; codecs=${n}`,robustness:i.videoRobustness||"",encryptionScheme:i.videoEncryptionScheme||null}))}]}function iy(s){var e;return !!s&&(s.sessionType==="persistent-license"||!!((e=s.sessionTypes)!=null&&e.some(t=>t==="persistent-license")))}function jg(s){let e=new Uint16Array(s.buffer,s.byteOffset,s.byteLength/2),t=String.fromCharCode.apply(null,Array.from(e)),i=t.substring(t.indexOf("<"),t.length),a=new DOMParser().parseFromString(i,"text/xml").getElementsByTagName("KID")[0];if(a){let o=a.childNodes[0]?a.childNodes[0].nodeValue:a.getAttribute("VALUE");if(o){let l=Uu(o).subarray(0,16);return Wg(l),l}}return null}var Ao={},Tn=class s{static clearKeyUriToKeyIdMap(){Ao={};}static setKeyIdForUri(e,t){Ao[e]=t;}constructor(e,t,i,r=[1],n=null,a){this.uri=void 0,this.method=void 0,this.keyFormat=void 0,this.keyFormatVersions=void 0,this.encrypted=void 0,this.isCommonEncryption=void 0,this.iv=null,this.key=null,this.keyId=null,this.pssh=null,this.method=e,this.uri=t,this.keyFormat=i,this.keyFormatVersions=r,this.iv=n,this.encrypted=e?e!=="NONE":false,this.isCommonEncryption=this.encrypted&&!sr(e),a!=null&&a.startsWith("0x")&&(this.keyId=new Uint8Array(Ig(a)));}matches(e){return e.uri===this.uri&&e.method===this.method&&e.encrypted===this.encrypted&&e.keyFormat===this.keyFormat&&Qo(e.keyFormatVersions,this.keyFormatVersions)&&Fm(e.iv,this.iv)&&Fm(e.keyId,this.keyId)}isSupported(){if(this.method){if(sr(this.method)||this.method==="NONE")return true;if(this.keyFormat==="identity")return this.method==="SAMPLE-AES";switch(this.keyFormat){case Xe.FAIRPLAY:case Xe.WIDEVINE:case Xe.PLAYREADY:case Xe.CLEARKEY:return ["SAMPLE-AES","SAMPLE-AES-CENC","SAMPLE-AES-CTR"].indexOf(this.method)!==-1}}return false}getDecryptData(e,t){if(!this.encrypted||!this.uri)return null;if(sr(this.method)){let n=this.iv;return n||(typeof e!="number"&&(Te.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),e=0),n=ry(e)),new s(this.method,this.uri,"identity",this.keyFormatVersions,n)}if(this.keyId){let n=Ao[this.uri];if(n&&!Qo(this.keyId,n)&&s.setKeyIdForUri(this.uri,this.keyId),this.pssh)return this}let i=Yg(this.uri);if(i)switch(this.keyFormat){case Xe.WIDEVINE:if(this.pssh=i,!this.keyId){let n=gT(i.buffer);if(n.length){var r;let a=n[0];this.keyId=(r=a.kids)!=null&&r.length?a.kids[0]:null;}}this.keyId||(this.keyId=Nm(t));break;case Xe.PLAYREADY:{let n=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=mT(n,null,i),this.keyId=jg(i);break}default:{let n=i.subarray(0,16);if(n.length!==16){let a=new Uint8Array(16);a.set(n,16-n.length),n=a;}this.keyId=n;break}}if(!this.keyId||this.keyId.byteLength!==16){let n;n=sy(t),n||(n=Nm(t),n||(n=Ao[this.uri])),n&&(this.keyId=n,s.setKeyIdForUri(this.uri,n));}return this}};function sy(s){let e=s?.[Xe.WIDEVINE];return e?e.keyId:null}function Nm(s){let e=s?.[Xe.PLAYREADY];if(e){let t=Yg(e.uri);if(t)return jg(t)}return null}function ry(s){let e=new Uint8Array(16);for(let t=12;t<16;t++)e[t]=s>>8*(15-t)&255;return e}var Um=/#EXT-X-STREAM-INF:([^\r\n]*)(?:[\r\n](?:#[^\r\n]*)?)*([^\r\n]+)|#EXT-X-(SESSION-DATA|SESSION-KEY|DEFINE|CONTENT-STEERING|START):([^\r\n]*)[\r\n]+/g,Bm=/#EXT-X-MEDIA:(.*)/g,ny=/^#EXT(?:INF|-X-TARGETDURATION):/m,zd=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#.*/.source].join("|"),"g"),ay=new RegExp([/#EXT-X-(PROGRAM-DATE-TIME|BYTERANGE|DATERANGE|DEFINE|KEY|MAP|PART|PART-INF|PLAYLIST-TYPE|PRELOAD-HINT|RENDITION-REPORT|SERVER-CONTROL|SKIP|START):(.+)/.source,/#EXT-X-(BITRATE|DISCONTINUITY-SEQUENCE|MEDIA-SEQUENCE|TARGETDURATION|VERSION): *(\d+)/.source,/#EXT-X-(DISCONTINUITY|ENDLIST|GAP|INDEPENDENT-SEGMENTS)/.source,/(#)([^:]*):(.*)/.source,/(#)(.*)(?:.*)\r?\n?/.source].join("|")),as=class s{static findGroup(e,t){for(let i=0;i<e.length;i++){let r=e[i];if(r.id===t)return r}}static resolve(e,t){return Mu.buildAbsoluteURL(t,e,{alwaysNormalize:true})}static isMediaPlaylist(e){return ny.test(e)}static parseMasterPlaylist(e,t){let i=Pm(e),r={contentSteering:null,levels:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:i},n=[];if(Um.lastIndex=0,!e.startsWith("#EXTM3U"))return r.playlistParsingError=new Error("no EXTM3U delimiter"),r;let a;for(;(a=Um.exec(e))!=null;)if(a[1]){var o;let d=new Re(a[1],r),c=xc(r,a[2]),u={attrs:d,bitrate:d.decimalInteger("BANDWIDTH")||d.decimalInteger("AVERAGE-BANDWIDTH"),name:d.NAME,url:s.resolve(c,t)},h=d.decimalResolution("RESOLUTION");h&&(u.width=h.width,u.height=h.height),Hm(d.CODECS,u);let f=d["SUPPLEMENTAL-CODECS"];f&&(u.supplemental={},Hm(f,u.supplemental)),(o=u.unknownCodecs)!=null&&o.length||n.push(u),r.levels.push(u);}else if(a[3]){let d=a[3],c=a[4];switch(d){case "SESSION-DATA":{let u=new Re(c,r),h=u["DATA-ID"];h&&(r.sessionData===null&&(r.sessionData={}),r.sessionData[h]=u);break}case "SESSION-KEY":{let u=$m(c,t,r);u.encrypted&&u.isSupported()?(r.sessionKeys===null&&(r.sessionKeys=[]),r.sessionKeys.push(u)):Te.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${c}"`);break}case "DEFINE":{{let u=new Re(c,r);wm(r,u,t);}break}case "CONTENT-STEERING":{let u=new Re(c,r);r.contentSteering={uri:s.resolve(u["SERVER-URI"],t),pathwayId:u["PATHWAY-ID"]||"."};break}case "START":{r.startTimeOffset=Gm(c);break}}}let l=n.length>0&&n.length<r.levels.length;return r.levels=l?n:r.levels,r.levels.length===0&&(r.playlistParsingError=new Error("no levels found in manifest")),r}static parseMasterPlaylistMedia(e,t,i){let r,n={},a=i.levels,o={AUDIO:a.map(d=>({id:d.attrs.AUDIO,audioCodec:d.audioCodec})),SUBTITLES:a.map(d=>({id:d.attrs.SUBTITLES,textCodec:d.textCodec})),"CLOSED-CAPTIONS":[]},l=0;for(Bm.lastIndex=0;(r=Bm.exec(e))!==null;){let d=new Re(r[1],i),c=d.TYPE;if(c){let u=o[c],h=n[c]||[];n[c]=h;let f=d.LANGUAGE,m=d["ASSOC-LANGUAGE"],p=d.CHANNELS,E=d.CHARACTERISTICS,v=d["INSTREAM-ID"],T={attrs:d,bitrate:0,id:l++,groupId:d["GROUP-ID"]||"",name:d.NAME||f||"",type:c,default:d.bool("DEFAULT"),autoselect:d.bool("AUTOSELECT"),forced:d.bool("FORCED"),lang:f,url:d.URI?s.resolve(d.URI,t):""};if(m&&(T.assocLang=m),p&&(T.channels=p),E&&(T.characteristics=E),v&&(T.instreamId=v),u!=null&&u.length){let S=s.findGroup(u,T.groupId)||u[0];Km(T,S,"audioCodec"),Km(T,S,"textCodec");}h.push(T);}}return n}static parseLevelPlaylist(e,t,i,r,n,a){var o;let l={url:t},d=new Rc(t),c=d.fragments,u=[],h=null,f=0,m=0,p=0,E=0,v=0,T=null,S=new cn(r,l),A,b,D,I=-1,k=false,R=null,L;if(zd.lastIndex=0,d.m3u8=e,d.hasVariableRefs=Pm(e),((o=zd.exec(e))==null?void 0:o[0])!=="#EXTM3U")return d.playlistParsingError=new Error("Missing format identifier #EXTM3U"),d;for(;(A=zd.exec(e))!==null;){k&&(k=false,S=new cn(r,l),S.playlistOffset=p,S.setStart(p),S.sn=f,S.cc=E,v&&(S.bitrate=v),S.level=i,h&&(S.initSegment=h,h.rawProgramDateTime&&(S.rawProgramDateTime=h.rawProgramDateTime,h.rawProgramDateTime=null),R&&(S.setByteRange(R),R=null)));let j=A[1];if(j){S.duration=parseFloat(j);let V=(" "+A[2]).slice(1);S.title=V||null,S.tagList.push(V?["INF",j,V]:["INF",j]);}else if(A[3]){if(G(S.duration)){S.playlistOffset=p,S.setStart(p),D&&Wm(S,D,d),S.sn=f,S.level=i,S.cc=E,c.push(S);let V=(" "+A[3]).slice(1);S.relurl=xc(d,V),Dc(S,T,u),T=S,p+=S.duration,f++,m=0,k=true;}}else {if(A=A[0].match(ay),!A){Te.warn("No matches on slow regex match for level playlist!");continue}for(b=1;b<A.length&&A[b]===void 0;b++);let V=(" "+A[b]).slice(1),O=(" "+A[b+1]).slice(1),Y=A[b+2]?(" "+A[b+2]).slice(1):null;switch(V){case "BYTERANGE":T?S.setByteRange(O,T):S.setByteRange(O);break;case "PROGRAM-DATE-TIME":S.rawProgramDateTime=O,S.tagList.push(["PROGRAM-DATE-TIME",O]),I===-1&&(I=c.length);break;case "PLAYLIST-TYPE":d.type&&Ei(d,V,A),d.type=O.toUpperCase();break;case "MEDIA-SEQUENCE":d.startSN!==0?Ei(d,V,A):c.length>0&&Ym(d,V,A),f=d.startSN=parseInt(O);break;case "SKIP":{d.skippedSegments&&Ei(d,V,A);let $=new Re(O,d),q=$.decimalInteger("SKIPPED-SEGMENTS");if(G(q)){d.skippedSegments+=q;for(let N=q;N--;)c.push(null);f+=q;}let Q=$.enumeratedString("RECENTLY-REMOVED-DATERANGES");Q&&(d.recentlyRemovedDateranges=(d.recentlyRemovedDateranges||[]).concat(Q.split(" ")));break}case "TARGETDURATION":d.targetduration!==0&&Ei(d,V,A),d.targetduration=Math.max(parseInt(O),1);break;case "VERSION":d.version!==null&&Ei(d,V,A),d.version=parseInt(O);break;case "INDEPENDENT-SEGMENTS":break;case "ENDLIST":d.live||Ei(d,V,A),d.live=false;break;case "#":(O||Y)&&S.tagList.push(Y?[O,Y]:[O]);break;case "DISCONTINUITY":E++,S.tagList.push(["DIS"]);break;case "GAP":S.gap=true,S.tagList.push([V]);break;case "BITRATE":S.tagList.push([V,O]),v=parseInt(O)*1e3,G(v)?S.bitrate=v:v=0;break;case "DATERANGE":{let $=new Re(O,d),q=new zo($,d.dateRanges[$.ID],d.dateRangeTagCount);d.dateRangeTagCount++,q.isValid||d.skippedSegments?d.dateRanges[q.id]=q:Te.warn(`Ignoring invalid DATERANGE tag: "${O}"`),S.tagList.push(["EXT-X-DATERANGE",O]);break}case "DEFINE":{{let $=new Re(O,d);"IMPORT"in $?qT(d,$,a):wm(d,$,t);}break}case "DISCONTINUITY-SEQUENCE":d.startCC!==0?Ei(d,V,A):c.length>0&&Ym(d,V,A),d.startCC=E=parseInt(O);break;case "KEY":{let $=$m(O,t,d);if($.isSupported()){if($.method==="NONE"){D=void 0;break}D||(D={});let q=D[$.keyFormat];q!=null&&q.matches($)||(q&&(D=ye({},D)),D[$.keyFormat]=$);}else Te.warn(`[Keys] Ignoring unsupported EXT-X-KEY tag: "${O}"`);break}case "START":d.startTimeOffset=Gm(O);break;case "MAP":{let $=new Re(O,d);if(S.duration){let q=new cn(r,l);Vm(q,$,i,D),h=q,S.initSegment=h,h.rawProgramDateTime&&!S.rawProgramDateTime&&(S.rawProgramDateTime=h.rawProgramDateTime);}else {let q=S.byteRangeEndOffset;if(q){let Q=S.byteRangeStartOffset;R=`${q-Q}@${Q}`;}else R=null;Vm(S,$,i,D),h=S,k=true;}h.cc=E;break}case "SERVER-CONTROL":{L&&Ei(d,V,A),L=new Re(O),d.canBlockReload=L.bool("CAN-BLOCK-RELOAD"),d.canSkipUntil=L.optionalFloat("CAN-SKIP-UNTIL",0),d.canSkipDateRanges=d.canSkipUntil>0&&L.bool("CAN-SKIP-DATERANGES"),d.partHoldBack=L.optionalFloat("PART-HOLD-BACK",0),d.holdBack=L.optionalFloat("HOLD-BACK",0);break}case "PART-INF":{d.partTarget&&Ei(d,V,A);let $=new Re(O);d.partTarget=$.decimalFloatingPoint("PART-TARGET");break}case "PART":{let $=d.partList;$||($=d.partList=[]);let q=m>0?$[$.length-1]:void 0,Q=m++,N=new Re(O,d),U=new pc(N,S,l,Q,q);$.push(U),S.duration+=U.duration;break}case "PRELOAD-HINT":{let $=new Re(O,d);d.preloadHint=$;break}case "RENDITION-REPORT":{let $=new Re(O,d);d.renditionReports=d.renditionReports||[],d.renditionReports.push($);break}default:Te.warn(`line parsed but not handled: ${A}`);break}}}T&&!T.relurl?(c.pop(),p-=T.duration,d.partList&&(d.fragmentHint=T)):d.partList&&(Dc(S,T,u),S.cc=E,d.fragmentHint=S,D&&Wm(S,D,d)),d.targetduration||(d.playlistParsingError=new Error("Missing Target Duration"));let M=c.length,B=c[0],K=c[M-1];if(p+=d.skippedSegments*d.targetduration,p>0&&M&&K){d.averagetargetduration=p/M;let j=K.sn;d.endSN=j!=="initSegment"?j:0,d.live||(K.endList=true),I>0&&(ly(c,I),B&&u.unshift(B));}return d.fragmentHint&&(p+=d.fragmentHint.duration),d.totalduration=p,u.length&&d.dateRangeTagCount&&B&&zg(u,d),d.endCC=E,d}};function zg(s,e){let t=s.length;if(!t)if(e.hasProgramDateTime){let o=e.fragments[e.fragments.length-1];s.push(o),t++;}else return;let i=s[t-1],r=e.live?1/0:e.totalduration,n=Object.keys(e.dateRanges);for(let o=n.length;o--;){let l=e.dateRanges[n[o]],d=l.startDate.getTime();l.tagAnchor=i.ref;for(let c=t;c--;){var a;if(((a=s[c])==null?void 0:a.sn)<e.startSN)break;let u=oy(e,d,s,c,r);if(u!==-1){l.tagAnchor=e.fragments[u].ref;break}}}}function oy(s,e,t,i,r){let n=t[i];if(n){let o=n.programDateTime;if(e>=o||i===0){var a;let l=(((a=t[i+1])==null?void 0:a.start)||r)-n.start;if(e<=o+l*1e3){let d=t[i].sn-s.startSN;if(d<0)return -1;let c=s.fragments;if(c.length>t.length){let h=(t[i+1]||c[c.length-1]).sn-s.startSN;for(let f=h;f>d;f--){let m=c[f].programDateTime;if(e>=m&&e<m+c[f].duration*1e3)return f}}return d}}}return -1}function $m(s,e,t){var i,r;let n=new Re(s,t),a=(i=n.METHOD)!=null?i:"",o=n.URI,l=n.hexadecimalInteger("IV"),d=n.KEYFORMATVERSIONS,c=(r=n.KEYFORMAT)!=null?r:"identity";o&&n.IV&&!l&&Te.error(`Invalid IV: ${n.IV}`);let u=o?as.resolve(o,e):"",h=(d||"1").split("/").map(Number).filter(Number.isFinite);return new Tn(a,u,c,h,l,n.KEYID)}function Gm(s){let t=new Re(s).decimalFloatingPoint("TIME-OFFSET");return G(t)?t:null}function Hm(s,e){let t=(s||"").split(/[ ,]+/).filter(i=>i);["video","audio","text"].forEach(i=>{let r=t.filter(n=>wu(n,i));r.length&&(e[`${i}Codec`]=r.map(n=>n.split("/")[0]).join(","),t=t.filter(n=>r.indexOf(n)===-1));}),e.unknownCodecs=t;}function Km(s,e,t){let i=e[t];i&&(s[t]=i);}function ly(s,e){let t=s[e];for(let i=e;i--;){let r=s[i];if(!r)return;r.programDateTime=t.programDateTime-r.duration*1e3,t=r;}}function Dc(s,e,t){s.rawProgramDateTime?t.push(s):e!=null&&e.programDateTime&&(s.programDateTime=e.endProgramDateTime);}function Vm(s,e,t,i){s.relurl=e.URI,e.BYTERANGE&&s.setByteRange(e.BYTERANGE),s.level=t,s.sn="initSegment",i&&(s.levelkeys=i),s.initSegment=null;}function Wm(s,e,t){s.levelkeys=e;let{encryptedFragments:i}=t;(!i.length||i[i.length-1].levelkeys!==e)&&Object.keys(e).some(r=>e[r].isCommonEncryption)&&i.push(s);}function Ei(s,e,t){s.playlistParsingError=new Error(`#EXT-X-${e} must not appear more than once (${t[0]})`);}function Ym(s,e,t){s.playlistParsingError=new Error(`#EXT-X-${e} must appear before the first Media Segment (${t[0]})`);}function Qd(s,e){let t=e.startPTS;if(G(t)){let i=0,r;e.sn>s.sn?(i=t-s.start,r=s):(i=s.start-t,r=e),r.duration!==i&&r.setDuration(i);}else e.sn>s.sn?s.cc===e.cc&&s.minEndPTS?e.setStart(s.start+(s.minEndPTS-s.start)):e.setStart(s.start+s.duration):e.setStart(Math.max(s.start-e.duration,0));}function Qg(s,e,t,i,r,n,a){i-t<=0&&(a.warn("Fragment should have a positive duration",e),i=t+e.duration,n=r+e.duration);let l=t,d=i,c=e.startPTS,u=e.endPTS;if(G(c)){let v=Math.abs(c-t);s&&v>s.totalduration?a.warn(`media timestamps and playlist times differ by ${v}s for level ${e.level} ${s.url}`):G(e.deltaPTS)?e.deltaPTS=Math.max(v,e.deltaPTS):e.deltaPTS=v,l=Math.max(t,c),t=Math.min(t,c),r=e.startDTS!==void 0?Math.min(r,e.startDTS):r,d=Math.min(i,u),i=Math.max(i,u),n=e.endDTS!==void 0?Math.max(n,e.endDTS):n;}let h=t-e.start;e.start!==0&&e.setStart(t),e.setDuration(i-e.start),e.startPTS=t,e.maxStartPTS=l,e.startDTS=r,e.endPTS=i,e.minEndPTS=d,e.endDTS=n;let f=e.sn;if(!s||f<s.startSN||f>s.endSN)return 0;let m,p=f-s.startSN,E=s.fragments;for(E[p]=e,m=p;m>0;m--)Qd(E[m],E[m-1]);for(m=p;m<E.length-1;m++)Qd(E[m],E[m+1]);return s.fragmentHint&&Qd(E[E.length-1],s.fragmentHint),s.PTSKnown=s.alignedSliding=true,h}function dy(s,e,t){if(s===e)return;let i=null,r=s.fragments;for(let c=r.length-1;c>=0;c--){let u=r[c].initSegment;if(u){i=u;break}}s.fragmentHint&&delete s.fragmentHint.endPTS;let n;hy(s,e,(c,u,h,f)=>{if((!e.startCC||e.skippedSegments)&&u.cc!==c.cc){let m=c.cc-u.cc;for(let p=h;p<f.length;p++)f[p].cc+=m;e.endCC=f[f.length-1].cc;}G(c.startPTS)&&G(c.endPTS)&&(u.setStart(u.startPTS=c.startPTS),u.startDTS=c.startDTS,u.maxStartPTS=c.maxStartPTS,u.endPTS=c.endPTS,u.endDTS=c.endDTS,u.minEndPTS=c.minEndPTS,u.setDuration(c.endPTS-c.startPTS),u.duration&&(n=u),e.PTSKnown=e.alignedSliding=true),c.hasStreams&&(u.elementaryStreams=c.elementaryStreams),u.loader=c.loader,c.hasStats&&(u.stats=c.stats),c.initSegment&&(u.initSegment=c.initSegment,i=c.initSegment);});let a=e.fragments,o=e.fragmentHint?a.concat(e.fragmentHint):a;if(i&&o.forEach(c=>{var u;c&&(!c.initSegment||c.initSegment.relurl===((u=i)==null?void 0:u.relurl))&&(c.initSegment=i);}),e.skippedSegments){if(e.deltaUpdateFailed=a.some(c=>!c),e.deltaUpdateFailed){t.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let c=e.skippedSegments;c--;)a.shift();e.startSN=a[0].sn;}else {e.canSkipDateRanges&&(e.dateRanges=cy(s.dateRanges,e,t));let c=s.fragments.filter(u=>u.rawProgramDateTime);if(s.hasProgramDateTime&&!e.hasProgramDateTime)for(let u=1;u<o.length;u++)o[u].programDateTime===null&&Dc(o[u],o[u-1],c);zg(c,e);}e.endCC=a[a.length-1].cc;}if(!e.startCC){var l;let c=Jg(s,e.startSN-1);e.startCC=(l=c?.cc)!=null?l:a[0].cc;}uy(s.partList,e.partList,(c,u)=>{u.elementaryStreams=c.elementaryStreams,u.stats=c.stats;}),n?Qg(e,n,n.startPTS,n.endPTS,n.startDTS,n.endDTS,t):Xg(s,e),a.length&&(e.totalduration=e.edge-a[0].start),e.driftStartTime=s.driftStartTime,e.driftStart=s.driftStart;let d=e.advancedDateTime;if(e.advanced&&d){let c=e.edge;e.driftStart||(e.driftStartTime=d,e.driftStart=c),e.driftEndTime=d,e.driftEnd=c;}else e.driftEndTime=s.driftEndTime,e.driftEnd=s.driftEnd,e.advancedDateTime=s.advancedDateTime;e.requestScheduled===-1&&(e.requestScheduled=s.requestScheduled);}function cy(s,e,t){let{dateRanges:i,recentlyRemovedDateranges:r}=e,n=ye({},s);r&&r.forEach(l=>{delete n[l];});let o=Object.keys(n).length;return o?(Object.keys(i).forEach(l=>{let d=n[l],c=new zo(i[l].attr,d);c.isValid?(n[l]=c,d||(c.tagOrder+=o)):t.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${Ae(i[l].attr)}"`);}),n):i}function uy(s,e,t){if(s&&e){let i=0;for(let r=0,n=s.length;r<=n;r++){let a=s[r],o=e[r+i];a&&o&&a.index===o.index&&a.fragment.sn===o.fragment.sn?t(a,o):i--;}}}function hy(s,e,t){let i=e.skippedSegments,r=Math.max(s.startSN,e.startSN)-e.startSN,n=(s.fragmentHint?1:0)+(i?e.endSN:Math.min(s.endSN,e.endSN))-e.startSN,a=e.startSN-s.startSN,o=e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments,l=s.fragmentHint?s.fragments.concat(s.fragmentHint):s.fragments;for(let d=r;d<=n;d++){let c=l[a+d],u=o[d];if(i&&!u&&c&&(u=e.fragments[d]=c),c&&u){t(c,u,d,o);let h=c.relurl,f=u.relurl;if(h&&fy(h,f)){e.playlistParsingError=qm(`media sequence mismatch ${u.sn}:`,s,e,c,u);return}else if(c.cc!==u.cc){e.playlistParsingError=qm(`discontinuity sequence mismatch (${c.cc}!=${u.cc})`,s,e,c,u);return}}}}function qm(s,e,t,i,r){return new Error(`${s} ${r.url}
1360
1360
  Playlist starting @${e.startSN}
1361
1361
  ${e.m3u8}
1362
1362
 
1363
1363
  Playlist starting @${t.startSN}
1364
- ${t.m3u8}`)}function Qg(s,e,t=true){let i=e.startSN+e.skippedSegments-s.startSN,r=s.fragments,n=i>=0,a=0;if(n&&i<r.length)a=r[i].start;else if(n&&e.startSN===s.endSN+1)a=s.fragmentEnd;else if(n&&t)a=s.fragmentStart+i*e.levelTargetDuration;else if(!e.skippedSegments&&e.fragmentStart===0)a=s.fragmentStart;else return;Cc(e,a);}function Cc(s,e){if(e){let t=s.fragments;for(let i=s.skippedSegments;i<t.length;i++)t[i].addStart(e);s.fragmentHint&&s.fragmentHint.addStart(e);}}function Xg(s,e=1/0){let t=1e3*s.targetduration;if(s.updated){let i=s.fragments;if(i.length&&t*4>e){let n=i[i.length-1].duration*1e3;n<t&&(t=n);}}else t/=2;return Math.round(t)}function Zg(s,e,t){if(!s)return null;let i=s.fragments[e-s.startSN];return i||(i=s.fragmentHint,i&&i.sn===e)?i:e<s.startSN&&t&&t.sn===e?t:null}function qm(s,e,t){return s?Jg(s.partList,e,t):null}function Jg(s,e,t){if(s)for(let i=s.length;i--;){let r=s[i];if(r.index===t&&r.fragment.sn===e)return r}return null}function ep(s){s.forEach((e,t)=>{var i;(i=e.details)==null||i.fragments.forEach(r=>{r.level=t,r.initSegment&&(r.initSegment.level=t);});});}function hy(s,e){return s!==e&&e?jm(s)!==jm(e):false}function jm(s){return s.replace(/\?[^?]*$/,"")}function un(s,e){for(let i=0,r=s.length;i<r;i++){var t;if(((t=s[i])==null?void 0:t.cc)===e)return s[i]}return null}function fy(s,e){return !!(s&&e.startCC<s.endCC&&e.endCC>s.startCC)}function zm(s,e){let t=s.start+e;s.startPTS=t,s.setStart(t),s.endPTS=t+s.duration;}function tp(s,e){let t=e.fragments;for(let i=0,r=t.length;i<r;i++)zm(t[i],s);e.fragmentHint&&zm(e.fragmentHint,s),e.alignedSliding=true;}function my(s,e){s&&(ip(e,s),e.alignedSliding||Zo(e,s),!e.alignedSliding&&!e.skippedSegments&&Qg(s,e,false));}function ip(s,e){if(!fy(e,s))return;let t=Math.min(e.endCC,s.endCC),i=un(e.fragments,t),r=un(s.fragments,t);if(!i||!r)return;Te.log(`Aligning playlist at start of dicontinuity sequence ${t}`);let n=i.start-r.start;tp(n,s);}function Zo(s,e){if(!s.hasProgramDateTime||!e.hasProgramDateTime)return;let t=s.fragments,i=e.fragments;if(!t.length||!i.length)return;let r,n,a=Math.min(e.endCC,s.endCC);e.startCC<a&&s.startCC<a&&(r=un(i,a),n=un(t,a)),(!r||!n)&&(r=i[Math.floor(i.length/2)],n=un(t,r.cc)||t[Math.floor(t.length/2)]);let o=r.programDateTime,l=n.programDateTime;if(!o||!l)return;let d=(l-o)/1e3-(n.start-r.start);tp(d,s);}function nt(s,e,t){ut(s,e,t),s.addEventListener(e,t);}function ut(s,e,t){s.removeEventListener(e,t);}var gy={toString:function(s){let e="",t=s.length;for(let i=0;i<t;i++)e+=`[${s.start(i).toFixed(3)}-${s.end(i).toFixed(3)}]`;return e}},C={STOPPED:"STOPPED",IDLE:"IDLE",KEY_LOADING:"KEY_LOADING",FRAG_LOADING:"FRAG_LOADING",FRAG_LOADING_WAITING_RETRY:"FRAG_LOADING_WAITING_RETRY",WAITING_TRACK:"WAITING_TRACK",PARSING:"PARSING",PARSED:"PARSED",ENDED:"ENDED",ERROR:"ERROR",WAITING_INIT_PTS:"WAITING_INIT_PTS",WAITING_LEVEL:"WAITING_LEVEL"},yn=class extends jo{constructor(e,t,i,r,n){super(r,e.logger),this.hls=void 0,this.fragPrevious=null,this.fragCurrent=null,this.fragmentTracker=void 0,this.transmuxer=null,this._state=C.STOPPED,this.playlistType=void 0,this.media=null,this.mediaBuffer=null,this.config=void 0,this.bitrateTest=false,this.lastCurrentTime=0,this.nextLoadPosition=0,this.startPosition=0,this.startTimeOffset=null,this.retryDate=0,this.levels=null,this.fragmentLoader=void 0,this.keyLoader=void 0,this.levelLastLoaded=null,this.startFragRequested=false,this.decrypter=void 0,this.initPTS=[],this.buffering=true,this.loadingParts=false,this.loopSn=void 0,this.onMediaSeeking=()=>{let{config:a,fragCurrent:o,media:l,mediaBuffer:d,state:c}=this,u=l?l.currentTime:0,h=re.bufferInfo(d||l,u,a.maxBufferHole),f=!h.len;if(this.log(`Media seeking to ${G(u)?u.toFixed(3):u}, state: ${c}, ${f?"out of":"in"} buffer`),this.state===C.ENDED)this.resetLoadingState();else if(o){let m=a.maxFragLookUpTolerance,p=o.start-m,E=o.start+o.duration+m;if(f||E<h.start||p>h.end){let v=u>E;(u<p||v)&&(v&&o.loader&&(this.log(`Cancelling fragment load for seek (sn: ${o.sn})`),o.abortRequests(),this.resetLoadingState()),this.fragPrevious=null);}}if(l){this.fragmentTracker.removeFragmentsInRange(u,1/0,this.playlistType,true);let m=this.lastCurrentTime;if(u>m&&(this.lastCurrentTime=u),!this.loadingParts){let p=Math.max(h.end,u),E=this.shouldLoadParts(this.getLevelDetails(),p);E&&(this.log(`LL-Part loading ON after seeking to ${u.toFixed(2)} with buffer @${p.toFixed(2)}`),this.loadingParts=E);}}this.hls.hasEnoughToStart||(this.log(`Setting ${f?"startPosition":"nextLoadPosition"} to ${u} for seek without enough to start`),this.nextLoadPosition=u,f&&(this.startPosition=u)),f&&this.state===C.IDLE&&this.tickImmediate();},this.onMediaEnded=()=>{this.log("setting startPosition to 0 because media ended"),this.startPosition=this.lastCurrentTime=0;},this.playlistType=n,this.hls=e,this.fragmentLoader=new Lc(e.config),this.keyLoader=i,this.fragmentTracker=t,this.config=e.config,this.decrypter=new En(e.config);}registerListeners(){let{hls:e}=this;e.on(g.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(g.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(g.MANIFEST_LOADING,this.onManifestLoading,this),e.on(g.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(g.ERROR,this.onError,this);}unregisterListeners(){let{hls:e}=this;e.off(g.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(g.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(g.MANIFEST_LOADING,this.onManifestLoading,this),e.off(g.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(g.ERROR,this.onError,this);}doTick(){this.onTickEnd();}onTickEnd(){}startLoad(e){}stopLoad(){if(this.state===C.STOPPED)return;this.fragmentLoader.abort(),this.keyLoader.abort(this.playlistType);let e=this.fragCurrent;e!=null&&e.loader&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.resetTransmuxer(),this.fragCurrent=null,this.fragPrevious=null,this.clearInterval(),this.clearNextTick(),this.state=C.STOPPED;}get startPositionValue(){let{nextLoadPosition:e,startPosition:t}=this;return t===-1&&e?e:t}get bufferingEnabled(){return this.buffering}pauseBuffering(){this.buffering=false;}resumeBuffering(){this.buffering=true;}get inFlightFrag(){return {frag:this.fragCurrent,state:this.state}}_streamEnded(e,t){if(t.live||!this.media)return false;let i=e.end||0,r=this.config.timelineOffset||0;if(i<=r)return false;let n=e.buffered;this.config.maxBufferHole&&n&&n.length>1&&(e=re.bufferedInfo(n,e.start,0));let a=e.nextStart;if(a&&a>r&&a<t.edge||this.media.currentTime<e.start)return false;let l=t.partList;if(l!=null&&l.length){let c=l[l.length-1];return re.isBuffered(this.media,c.start+c.duration/2)}let d=t.fragments[t.fragments.length-1].type;return this.fragmentTracker.isEndListAppended(d)}getLevelDetails(){if(this.levels&&this.levelLastLoaded!==null)return this.levelLastLoaded.details}get timelineOffset(){let e=this.config.timelineOffset;if(e){var t;return ((t=this.getLevelDetails())==null?void 0:t.appliedTimelineOffset)||e}return 0}onMediaAttached(e,t){let i=this.media=this.mediaBuffer=t.media;nt(i,"seeking",this.onMediaSeeking),nt(i,"ended",this.onMediaEnded);let r=this.config;this.levels&&r.autoStartLoad&&this.state===C.STOPPED&&this.startLoad(r.startPosition);}onMediaDetaching(e,t){let i=!!t.transferMedia,r=this.media;if(r!==null){if(r.ended&&(this.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0),ut(r,"seeking",this.onMediaSeeking),ut(r,"ended",this.onMediaEnded),this.keyLoader&&!i&&this.keyLoader.detach(),this.media=this.mediaBuffer=null,this.loopSn=void 0,i){this.resetLoadingState(),this.resetTransmuxer();return}this.loadingParts=false,this.fragmentTracker.removeAllFragments(),this.stopLoad();}}onManifestLoading(){this.initPTS=[],this.levels=this.levelLastLoaded=this.fragCurrent=null,this.lastCurrentTime=this.startPosition=0,this.startFragRequested=false;}onError(e,t){}onManifestLoaded(e,t){this.startTimeOffset=t.startTimeOffset;}onHandlerDestroying(){this.stopLoad(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),super.onHandlerDestroying(),this.hls=this.onMediaSeeking=this.onMediaEnded=null;}onHandlerDestroyed(){this.state=C.STOPPED,this.fragmentLoader&&this.fragmentLoader.destroy(),this.keyLoader&&this.keyLoader.destroy(),this.decrypter&&this.decrypter.destroy(),this.hls=this.log=this.warn=this.decrypter=this.keyLoader=this.fragmentLoader=this.fragmentTracker=null,super.onHandlerDestroyed();}loadFragment(e,t,i){this.startFragRequested=true,this._loadFragForPlayback(e,t,i);}_loadFragForPlayback(e,t,i){let r=n=>{let a=n.frag;if(this.fragContextChanged(a)){this.warn(`${a.type} sn: ${a.sn}${n.part?" part: "+n.part.index:""} of ${this.fragInfo(a,false,n.part)}) was dropped during download.`),this.fragmentTracker.removeFragment(a);return}a.stats.chunkCount++,this._handleFragmentLoadProgress(n);};this._doFragLoad(e,t,i,r).then(n=>{if(!n)return;let a=this.state,o=n.frag;if(this.fragContextChanged(o)){(a===C.FRAG_LOADING||!this.fragCurrent&&a===C.PARSING)&&(this.fragmentTracker.removeFragment(o),this.state=C.IDLE);return}"payload"in n&&(this.log(`Loaded ${o.type} sn: ${o.sn} of ${this.playlistLabel()} ${o.level}`),this.hls.trigger(g.FRAG_LOADED,n)),this._handleFragmentLoadComplete(n);}).catch(n=>{this.state===C.STOPPED||this.state===C.ERROR||(this.warn(`Frag error: ${n?.message||n}`),this.resetFragmentLoading(e));});}clearTrackerIfNeeded(e){var t;let{fragmentTracker:i}=this;if(i.getState(e)===Ke.APPENDING){let n=e.type,a=this.getFwdBufferInfo(this.mediaBuffer,n),o=Math.max(e.duration,a?a.len:this.config.maxBufferLength),l=this.backtrackFragment;((l?e.sn-l.sn:0)===1||this.reduceMaxBufferLength(o,e.duration))&&i.removeFragment(e);}else ((t=this.mediaBuffer)==null?void 0:t.buffered.length)===0?i.removeAllFragments():i.hasParts(e.type)&&(i.detectPartialFragments({frag:e,part:null,stats:e.stats,id:e.type}),i.getState(e)===Ke.PARTIAL&&i.removeFragment(e));}checkLiveUpdate(e){if(e.updated&&!e.live){let t=e.fragments[e.fragments.length-1];this.fragmentTracker.detectPartialFragments({frag:t,part:null,stats:t.stats,id:t.type});}e.fragments[0]||(e.deltaUpdateFailed=true);}waitForLive(e){let t=e.details;return t?.live&&t.type!=="EVENT"&&(this.levelLastLoaded!==e||t.expired)}flushMainBuffer(e,t,i=null){if(!(e-t))return;let r={startOffset:e,endOffset:t,type:i};this.hls.trigger(g.BUFFER_FLUSHING,r);}_loadInitSegment(e,t){this._doFragLoad(e,t).then(i=>{let r=i?.frag;if(!r||this.fragContextChanged(r)||!this.levels)throw new Error("init load aborted");return i}).then(i=>{let{hls:r}=this,{frag:n,payload:a}=i,o=n.decryptdata;if(a&&a.byteLength>0&&o!=null&&o.key&&o.iv&&sr(o.method)){let l=self.performance.now();return this.decrypter.decrypt(new Uint8Array(a),o.key.buffer,o.iv.buffer,Nu(o.method)).catch(d=>{throw r.trigger(g.ERROR,{type:z.MEDIA_ERROR,details:x.FRAG_DECRYPT_ERROR,fatal:false,error:d,reason:d.message,frag:n}),d}).then(d=>{let c=self.performance.now();return r.trigger(g.FRAG_DECRYPTED,{frag:n,payload:d,stats:{tstart:l,tdecrypt:c}}),i.payload=d,this.completeInitSegmentLoad(i)})}return this.completeInitSegmentLoad(i)}).catch(i=>{this.state===C.STOPPED||this.state===C.ERROR||(this.warn(i),this.resetFragmentLoading(e));});}completeInitSegmentLoad(e){let{levels:t}=this;if(!t)throw new Error("init load aborted, missing levels");let i=e.frag.stats;this.state!==C.STOPPED&&(this.state=C.IDLE),e.frag.data=new Uint8Array(e.payload),i.parsing.start=i.buffering.start=self.performance.now(),i.parsing.end=i.buffering.end=self.performance.now(),this.tick();}unhandledEncryptionError(e,t){var i,r;let n=e.tracks;if(n&&!t.encrypted&&((i=n.audio)!=null&&i.encrypted||(r=n.video)!=null&&r.encrypted)&&(!this.config.emeEnabled||!this.keyLoader.emeController)){let a=this.media,o=new Error(`Encrypted track with no key in ${this.fragInfo(t)} (media ${a?"attached mediaKeys: "+a.mediaKeys:"detached"})`);return this.warn(o.message),!a||a.mediaKeys?false:(this.hls.trigger(g.ERROR,{type:z.KEY_SYSTEM_ERROR,details:x.KEY_SYSTEM_NO_KEYS,fatal:false,error:o,frag:t}),this.resetTransmuxer(),true)}return false}fragContextChanged(e){let{fragCurrent:t}=this;return !e||!t||e.sn!==t.sn||e.level!==t.level}fragBufferedComplete(e,t){let i=this.mediaBuffer?this.mediaBuffer:this.media;if(this.log(`Buffered ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.fragInfo(e,false,t)} > buffer:${i?gy.toString(re.getBuffered(i)):"(detached)"})`),Ue(e)){var r;if(e.type!==W.SUBTITLE){let a=e.elementaryStreams;if(!Object.keys(a).some(o=>!!a[o])){this.state=C.IDLE;return}}let n=(r=this.levels)==null?void 0:r[e.level];n!=null&&n.fragmentError&&(this.log(`Resetting level fragment error count of ${n.fragmentError} on frag buffered`),n.fragmentError=0);}this.state=C.IDLE;}_handleFragmentLoadComplete(e){let{transmuxer:t}=this;if(!t)return;let{frag:i,part:r,partsLoaded:n}=e,a=!n||n.length===0||n.some(l=>!l),o=new vn(i.level,i.sn,i.stats.chunkCount+1,0,r?r.index:-1,!a);t.flush(o);}_handleFragmentLoadProgress(e){}_doFragLoad(e,t,i=null,r){var n;this.fragCurrent=e;let a=t.details;if(!this.levels||!a)throw new Error(`frag load aborted, missing level${a?"":" detail"}s`);let o=null;if(e.encrypted&&!((n=e.decryptdata)!=null&&n.key)){if(this.log(`Loading key for ${e.sn} of [${a.startSN}-${a.endSN}], ${this.playlistLabel()} ${e.level}`),this.state=C.KEY_LOADING,this.fragCurrent=e,o=this.keyLoader.load(e).then(h=>{if(!this.fragContextChanged(h.frag))return this.hls.trigger(g.KEY_LOADED,h),this.state===C.KEY_LOADING&&(this.state=C.IDLE),h}),this.hls.trigger(g.KEY_LOADING,{frag:e}),this.fragCurrent===null)return this.log("context changed in KEY_LOADING"),Promise.resolve(null)}else e.encrypted||(o=this.keyLoader.loadClear(e,a.encryptedFragments,this.startFragRequested),o&&this.log("[eme] blocking frag load until media-keys acquired"));let l=this.fragPrevious;if(Ue(e)&&(!l||e.sn!==l.sn)){let h=this.shouldLoadParts(t.details,e.end);h!==this.loadingParts&&(this.log(`LL-Part loading ${h?"ON":"OFF"} loading sn ${l?.sn}->${e.sn}`),this.loadingParts=h);}if(i=Math.max(e.start,i||0),this.loadingParts&&Ue(e)){let h=a.partList;if(h&&r){i>a.fragmentEnd&&a.fragmentHint&&(e=a.fragmentHint);let f=this.getNextPart(h,e,i);if(f>-1){let m=h[f];e=this.fragCurrent=m.fragment,this.log(`Loading ${e.type} sn: ${e.sn} part: ${m.index} (${f}/${h.length-1}) of ${this.fragInfo(e,false,m)}) cc: ${e.cc} [${a.startSN}-${a.endSN}], target: ${parseFloat(i.toFixed(3))}`),this.nextLoadPosition=m.start+m.duration,this.state=C.FRAG_LOADING;let p;return o?p=o.then(E=>!E||this.fragContextChanged(E.frag)?null:this.doFragPartsLoad(e,m,t,r)).catch(E=>this.handleFragLoadError(E)):p=this.doFragPartsLoad(e,m,t,r).catch(E=>this.handleFragLoadError(E)),this.hls.trigger(g.FRAG_LOADING,{frag:e,part:m,targetBufferTime:i}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):p}else if(!e.url||this.loadedEndOfParts(h,i))return Promise.resolve(null)}}if(Ue(e)&&this.loadingParts){var d;this.log(`LL-Part loading OFF after next part miss @${i.toFixed(2)} Check buffer at sn: ${e.sn} loaded parts: ${(d=a.partList)==null?void 0:d.filter(h=>h.loaded).map(h=>`[${h.start}-${h.end}]`)}`),this.loadingParts=false;}else if(!e.url)return Promise.resolve(null);this.log(`Loading ${e.type} sn: ${e.sn} of ${this.fragInfo(e,false)}) cc: ${e.cc} ${"["+a.startSN+"-"+a.endSN+"]"}, target: ${parseFloat(i.toFixed(3))}`),G(e.sn)&&!this.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),this.state=C.FRAG_LOADING;let c=this.config.progressive,u;return c&&o?u=o.then(h=>!h||this.fragContextChanged(h.frag)?null:this.fragmentLoader.load(e,r)).catch(h=>this.handleFragLoadError(h)):u=Promise.all([this.fragmentLoader.load(e,c?r:void 0),o]).then(([h])=>(!c&&r&&r(h),h)).catch(h=>this.handleFragLoadError(h)),this.hls.trigger(g.FRAG_LOADING,{frag:e,targetBufferTime:i}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):u}doFragPartsLoad(e,t,i,r){return new Promise((n,a)=>{var o;let l=[],d=(o=i.details)==null?void 0:o.partList,c=u=>{this.fragmentLoader.loadPart(e,u,r).then(h=>{l[u.index]=h;let f=h.part;this.hls.trigger(g.FRAG_LOADED,h);let m=qm(i.details,e.sn,u.index+1)||Jg(d,e.sn,u.index+1);if(m)c(m);else return n({frag:e,part:f,partsLoaded:l})}).catch(a);};c(t);})}handleFragLoadError(e){if("data"in e){let t=e.data;t.frag&&t.details===x.INTERNAL_ABORTED?this.handleFragLoadAborted(t.frag,t.part):t.frag&&t.type===z.KEY_SYSTEM_ERROR?(t.frag.abortRequests(),this.resetStartWhenNotLoaded(),this.resetFragmentLoading(t.frag)):this.hls.trigger(g.ERROR,t);}else this.hls.trigger(g.ERROR,{type:z.OTHER_ERROR,details:x.INTERNAL_EXCEPTION,err:e,error:e,fatal:true});return null}_handleTransmuxerFlush(e){let t=this.getCurrentContext(e);if(!t||this.state!==C.PARSING){!this.fragCurrent&&this.state!==C.STOPPED&&this.state!==C.ERROR&&(this.state=C.IDLE);return}let{frag:i,part:r,level:n}=t,a=self.performance.now();i.stats.parsing.end=a,r&&(r.stats.parsing.end=a);let o=this.getLevelDetails(),d=o&&i.sn>o.endSN||this.shouldLoadParts(o,i.end);d!==this.loadingParts&&(this.log(`LL-Part loading ${d?"ON":"OFF"} after parsing segment ending @${i.end.toFixed(2)}`),this.loadingParts=d),this.updateLevelTiming(i,r,n,e.partial);}shouldLoadParts(e,t){if(this.config.lowLatencyMode){if(!e)return this.loadingParts;if(e.partList){var i;let n=e.partList[0];if(n.fragment.type===W.SUBTITLE)return false;let a=n.end+(((i=e.fragmentHint)==null?void 0:i.duration)||0);if(t>=a){var r;if((this.hls.hasEnoughToStart?((r=this.media)==null?void 0:r.currentTime)||this.lastCurrentTime:this.getLoadPosition())>n.start-n.fragment.duration)return true}}}return false}getCurrentContext(e){let{levels:t,fragCurrent:i}=this,{level:r,sn:n,part:a}=e;if(!(t!=null&&t[r]))return this.warn(`Levels object was unset while buffering fragment ${n} of ${this.playlistLabel()} ${r}. The current chunk will not be buffered.`),null;let o=t[r],l=o.details,d=a>-1?qm(l,n,a):null,c=d?d.fragment:Zg(l,n,i);return c?(i&&i!==c&&(c.stats=i.stats),{frag:c,part:d,level:o}):null}bufferFragmentData(e,t,i,r,n){if(this.state!==C.PARSING)return;let{data1:a,data2:o}=e,l=a;if(o&&(l=Dt(a,o)),!l.length)return;let d=this.initPTS[t.cc],c=d?-d.baseTime/d.timescale:void 0,u={type:e.type,frag:t,part:i,chunkMeta:r,offset:c,parent:t.type,data:l};if(this.hls.trigger(g.BUFFER_APPENDING,u),e.dropped&&e.independent&&!i){if(n)return;this.flushBufferGap(t);}}flushBufferGap(e){let t=this.media;if(!t)return;if(!re.isBuffered(t,t.currentTime)){this.flushMainBuffer(0,e.start);return}let i=t.currentTime,r=re.bufferInfo(t,i,0),n=e.duration,a=Math.min(this.config.maxFragLookUpTolerance*2,n*.25),o=Math.max(Math.min(e.start-a,r.end-a),i+a);e.start-o>a&&this.flushMainBuffer(o,e.start);}getFwdBufferInfo(e,t){var i;let r=this.getLoadPosition();if(!G(r))return null;let a=this.lastCurrentTime>r||(i=this.media)!=null&&i.paused?0:this.config.maxBufferHole;return this.getFwdBufferInfoAtPos(e,r,t,a)}getFwdBufferInfoAtPos(e,t,i,r){let n=re.bufferInfo(e,t,r);if(n.len===0&&n.nextStart!==void 0){let a=this.fragmentTracker.getBufferedFrag(t,i);if(a&&(n.nextStart<=a.end||a.gap)){let o=Math.max(Math.min(n.nextStart,a.end)-t,r);return re.bufferInfo(e,t,o)}}return n}getMaxBufferLength(e){let{config:t}=this,i;return e?i=Math.max(8*t.maxBufferSize/e,t.maxBufferLength):i=t.maxBufferLength,Math.min(i,t.maxMaxBufferLength)}reduceMaxBufferLength(e,t){let i=this.config,r=Math.max(Math.min(e-t,i.maxBufferLength),t),n=Math.max(e-t*3,i.maxMaxBufferLength/2,r);return n>=r?(i.maxMaxBufferLength=n,this.warn(`Reduce max buffer length to ${n}s`),true):false}getAppendedFrag(e,t=W.MAIN){let i=this.fragmentTracker?this.fragmentTracker.getAppendedFrag(e,t):null;return i&&"fragment"in i?i.fragment:i}getNextFragment(e,t){let i=t.fragments,r=i.length;if(!r)return null;let{config:n}=this,a=i[0].start,o=n.lowLatencyMode&&!!t.partList,l=null;if(t.live){let u=n.initialLiveManifestSize;if(r<u)return this.warn(`Not enough fragments to start playback (have: ${r}, need: ${u})`),null;if(!t.PTSKnown&&!this.startFragRequested&&this.startPosition===-1||e<a){var d;o&&!this.loadingParts&&(this.log("LL-Part loading ON for initial live fragment"),this.loadingParts=true),l=this.getInitialLiveFragment(t);let h=this.hls.startPosition,f=this.hls.liveSyncPosition,m=l?(h!==-1&&h>=a?h:f)||l.start:e;this.log(`Setting startPosition to ${m} to match start frag at live edge. mainStart: ${h} liveSyncPosition: ${f} frag.start: ${(d=l)==null?void 0:d.start}`),this.startPosition=this.nextLoadPosition=m;}}else e<=a&&(l=i[0]);if(!l){let u=this.loadingParts?t.partEnd:t.fragmentEnd;l=this.getFragmentAtPosition(e,u,t);}let c=this.filterReplacedPrimary(l,t);if(!c&&l){let u=l.sn-t.startSN;c=this.filterReplacedPrimary(i[u+1]||null,t);}return this.mapToInitFragWhenRequired(c)}isLoopLoading(e,t){let i=this.fragmentTracker.getState(e);return (i===Ke.OK||i===Ke.PARTIAL&&!!e.gap)&&this.nextLoadPosition>t}getNextFragmentLoopLoading(e,t,i,r,n){let a=null;if(e.gap&&(a=this.getNextFragment(this.nextLoadPosition,t),a&&!a.gap&&i.nextStart)){let o=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,i.nextStart,r,0);if(o!==null&&i.len+o.len>=n){let l=a.sn;return this.loopSn!==l&&(this.log(`buffer full after gaps in "${r}" playlist starting at sn: ${l}`),this.loopSn=l),null}}return this.loopSn=void 0,a}get primaryPrefetch(){if(Qm(this.config)){var e;if((e=this.hls.interstitialsManager)==null||(e=e.playingItem)==null?void 0:e.event)return true}return false}filterReplacedPrimary(e,t){if(!e)return e;if(Qm(this.config)&&e.type!==W.SUBTITLE){let i=this.hls.interstitialsManager,r=i?.bufferingItem;if(r){let a=r.event;if(a){if(a.appendInPlace||Math.abs(e.start-r.start)>1||r.start===0)return null}else if(e.end<=r.start&&t?.live===false||e.start>r.end&&r.nextEvent&&(r.nextEvent.appendInPlace||e.start-r.end>1))return null}let n=i?.playerQueue;if(n)for(let a=n.length;a--;){let o=n[a].interstitial;if(o.appendInPlace&&e.start>=o.startTime&&e.end<=o.resumeTime)return null}}return e}mapToInitFragWhenRequired(e){return e!=null&&e.initSegment&&!e.initSegment.data&&!this.bitrateTest?e.initSegment:e}getNextPart(e,t,i){let r=-1,n=false,a=true;for(let o=0,l=e.length;o<l;o++){let d=e[o];if(a=a&&!d.independent,r>-1&&i<d.start)break;let c=d.loaded;c?r=-1:(n||(d.independent||a)&&d.fragment===t)&&(d.fragment!==t&&this.warn(`Need buffer at ${i} but next unloaded part starts at ${d.start}`),r=o),n=c;}return r}loadedEndOfParts(e,t){let i;for(let r=e.length;r--;){if(i=e[r],!i.loaded)return false;if(t>i.start)return true}return false}getInitialLiveFragment(e){let t=e.fragments,i=this.fragPrevious,r=null;if(i){if(e.hasProgramDateTime&&(this.log(`Live playlist, switching playlist, load frag with same PDT: ${i.programDateTime}`),r=UT(t,i.endProgramDateTime,this.config.maxFragLookUpTolerance)),!r){let n=i.sn+1;if(n>=e.startSN&&n<=e.endSN){let a=t[n-e.startSN];i.cc===a.cc&&(r=a,this.log(`Live playlist, switching playlist, load frag with next SN: ${r.sn}`));}r||(r=$g(e,i.cc,i.end),r&&this.log(`Live playlist, switching playlist, load frag with same CC: ${r.sn}`));}}else {let n=this.hls.liveSyncPosition;n!==null&&(r=this.getFragmentAtPosition(n,this.bitrateTest?e.fragmentEnd:e.edge,e));}return r}getFragmentAtPosition(e,t,i){let{config:r}=this,{fragPrevious:n}=this,{fragments:a,endSN:o}=i,{fragmentHint:l}=i,{maxFragLookUpTolerance:d}=r,c=i.partList,u=!!(this.loadingParts&&c!=null&&c.length&&l);u&&!this.bitrateTest&&c[c.length-1].fragment.sn===l.sn&&(a=a.concat(l),o=l.sn);let h;if(e<t){var f;let p=e<this.lastCurrentTime||e>t-d||(f=this.media)!=null&&f.paused||!this.startFragRequested?0:d;h=cs(n,a,e,p);}else h=a[a.length-1];if(h){let m=h.sn-i.startSN,p=this.fragmentTracker.getState(h);if((p===Ke.OK||p===Ke.PARTIAL&&h.gap)&&(n=h),n&&h.sn===n.sn&&(!u||c[0].fragment.sn>h.sn||!i.live)&&h.level===n.level){let v=a[m+1];h.sn<o&&this.fragmentTracker.getState(v)!==Ke.OK?h=v:h=null;}}return h}alignPlaylists(e,t,i){let r=e.fragments.length;if(!r)return this.warn("No fragments in live playlist"),0;let n=e.fragmentStart,a=!t,o=e.alignedSliding&&G(n);if(a||!o&&!n){my(i,e);let l=e.fragmentStart;return this.log(`Live playlist sliding: ${l.toFixed(2)} start-sn: ${t?t.startSN:"na"}->${e.startSN} fragments: ${r}`),l}return n}waitForCdnTuneIn(e){return e.live&&e.canBlockReload&&e.partTarget&&e.tuneInGoal>Math.max(e.partHoldBack,e.partTarget*3)}setStartPosition(e,t){let i=this.startPosition;i<t&&(i=-1);let r=this.timelineOffset;if(i===-1){let n=this.startTimeOffset!==null,a=n?this.startTimeOffset:e.startTimeOffset;a!==null&&G(a)?(i=t+a,a<0&&(i+=e.edge),i=Math.min(Math.max(t,i),t+e.totalduration),this.log(`Setting startPosition to ${i} for start time offset ${a} found in ${n?"multivariant":"media"} playlist`),this.startPosition=i):e.live?(i=this.hls.liveSyncPosition||t,this.log(`Setting startPosition to -1 to start at live edge ${i}`),this.startPosition=-1):(this.log("setting startPosition to 0 by default"),this.startPosition=i=0),this.lastCurrentTime=i+r;}this.nextLoadPosition=i+r;}getLoadPosition(){var e;let{media:t}=this,i=0;return (e=this.hls)!=null&&e.hasEnoughToStart&&t?i=t.currentTime:this.nextLoadPosition>=0&&(i=this.nextLoadPosition),i}handleFragLoadAborted(e,t){this.transmuxer&&e.type===this.playlistType&&Ue(e)&&e.stats.aborted&&(this.log(`Fragment ${e.sn}${t?" part "+t.index:""} of ${this.playlistLabel()} ${e.level} was aborted`),this.resetFragmentLoading(e));}resetFragmentLoading(e){(!this.fragCurrent||!this.fragContextChanged(e)&&this.state!==C.FRAG_LOADING_WAITING_RETRY)&&(this.state=C.IDLE);}onFragmentOrKeyLoadError(e,t){var i;if(t.chunkMeta&&!t.frag){let v=this.getCurrentContext(t.chunkMeta);v&&(t.frag=v.frag);}let r=t.frag;if(!r||r.type!==e||!this.levels)return;if(this.fragContextChanged(r)){var n;this.warn(`Frag load error must match current frag to retry ${r.url} > ${(n=this.fragCurrent)==null?void 0:n.url}`);return}let a=t.details===x.FRAG_GAP;a&&this.fragmentTracker.fragBuffered(r,true);let o=t.errorAction;if(!o){this.state=C.ERROR;return}let{action:l,flags:d,retryCount:c=0,retryConfig:u}=o,h=!!u,f=h&&l===ze.RetryRequest,m=h&&!o.resolved&&d===yt.MoveAllAlternatesMatchingHost,p=(i=this.hls.latestLevelDetails)==null?void 0:i.live;if(!f&&m&&Ue(r)&&!r.endList&&p&&!Hg(t))this.resetFragmentErrors(e),this.treatAsGap(r),o.resolved=true;else if((f||m)&&c<u.maxNumRetry){var E;let v=yc((E=t.response)==null?void 0:E.code),T=Fu(u,c);if(this.resetStartWhenNotLoaded(),this.retryDate=self.performance.now()+T,this.state=C.FRAG_LOADING_WAITING_RETRY,o.resolved=true,v){this.log("Waiting for connection (offline)"),this.retryDate=1/0,t.reason="offline";return}this.warn(`Fragment ${r.sn} of ${e} ${r.level} errored with ${t.details}, retrying loading ${c+1}/${u.maxNumRetry} in ${T}ms`);}else if(u)if(this.resetFragmentErrors(e),c<u.maxNumRetry)!a&&l!==ze.RemoveAlternatePermanently&&(o.resolved=true);else {this.warn(`${t.details} reached or exceeded max retry (${c})`);return}else l===ze.SendAlternateToPenaltyBox?this.state=C.WAITING_LEVEL:this.state=C.ERROR;this.tickImmediate();}checkRetryDate(){let e=self.performance.now(),t=this.retryDate,i=t===1/0;(!t||e>=t||i&&!yc(0))&&(i&&this.log("Connection restored (online)"),this.resetStartWhenNotLoaded(),this.state=C.IDLE);}reduceLengthAndFlushBuffer(e){if(this.state===C.PARSING||this.state===C.PARSED){let t=e.frag,i=e.parent,r=this.getFwdBufferInfo(this.mediaBuffer,i),n=r&&r.len>.5;n&&this.reduceMaxBufferLength(r.len,t?.duration||10);let a=!n;return a&&this.warn(`Buffer full error while media.currentTime (${this.getLoadPosition()}) is not buffered, flush ${i} buffer`),t&&(this.fragmentTracker.removeFragment(t),this.nextLoadPosition=t.start),this.resetLoadingState(),a}return false}resetFragmentErrors(e){e===W.AUDIO&&(this.fragCurrent=null),this.hls.hasEnoughToStart||(this.startFragRequested=false),this.state!==C.STOPPED&&(this.state=C.IDLE);}afterBufferFlushed(e,t,i){if(!e)return;let r=re.getBuffered(e);this.fragmentTracker.detectEvictedFragments(t,r,i),this.state===C.ENDED&&this.resetLoadingState();}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state!==C.STOPPED&&(this.state=C.IDLE);}resetStartWhenNotLoaded(){if(!this.hls.hasEnoughToStart){this.startFragRequested=false;let e=this.levelLastLoaded,t=e?e.details:null;t!=null&&t.live?(this.log("resetting startPosition for live start"),this.startPosition=-1,this.setStartPosition(t,t.fragmentStart),this.resetLoadingState()):this.nextLoadPosition=this.startPosition;}}resetWhenMissingContext(e){this.log(`Loading context changed while buffering sn ${e.sn} of ${this.playlistLabel()} ${e.level===-1?"<removed>":e.level}. This chunk will not be buffered.`),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(),this.resetLoadingState();}removeUnbufferedFrags(e=0){this.fragmentTracker.removeFragmentsInRange(e,1/0,this.playlistType,false,true);}updateLevelTiming(e,t,i,r){let n=i.details;if(!n){this.warn("level.details undefined");return}if(!Object.keys(e.elementaryStreams).reduce((l,d)=>{let c=e.elementaryStreams[d];if(c){let u=c.endPTS-c.startPTS;if(u<=0)return this.warn(`Could not parse fragment ${e.sn} ${d} duration reliably (${u})`),l||false;let h=r?0:zg(n,e,c.startPTS,c.endPTS,c.startDTS,c.endDTS,this);return this.hls.trigger(g.LEVEL_PTS_UPDATED,{details:n,level:i,drift:h,type:d,frag:e,start:c.startPTS,end:c.endPTS}),true}return l},false)){var o;if(i.fragmentError===0&&this.treatAsGap(e,i),((o=this.transmuxer)==null?void 0:o.error)===null){let l=new Error(`Found no media in fragment ${e.sn} of ${this.playlistLabel()} ${e.level} resetting transmuxer to fallback to playlist timing`);if(this.warn(l.message),this.hls.trigger(g.ERROR,{type:z.MEDIA_ERROR,details:x.FRAG_PARSING_ERROR,fatal:false,error:l,frag:e,reason:`Found no media in msn ${e.sn} of ${this.playlistLabel()} "${i.url}"`}),!this.hls)return;this.resetTransmuxer();}}this.state=C.PARSED,this.log(`Parsed ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.fragInfo(e,false,t)})`),this.hls.trigger(g.FRAG_PARSED,{frag:e,part:t});}playlistLabel(){return this.playlistType===W.MAIN?"level":"track"}fragInfo(e,t=true,i){var r,n;return `${this.playlistLabel()} ${e.level} (${i?"part":"frag"}:[${((r=t&&!i?e.startPTS:(i||e).start)!=null?r:NaN).toFixed(3)}-${((n=t&&!i?e.endPTS:(i||e).end)!=null?n:NaN).toFixed(3)}]${i&&e.type==="main"?"INDEPENDENT="+(i.independent?"YES":"NO"):""}`}treatAsGap(e,t){t&&t.fragmentError++,e.gap=true,this.fragmentTracker.removeFragment(e),this.fragmentTracker.fragBuffered(e,true);}resetTransmuxer(){var e;(e=this.transmuxer)==null||e.reset();}recoverWorkerError(e){e.event==="demuxerWorker"&&(this.fragmentTracker.removeAllFragments(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),this.resetStartWhenNotLoaded(),this.resetLoadingState());}set state(e){let t=this._state;t!==e&&(this._state=e,this.log(`${t}->${e}`));}get state(){return this._state}};function Qm(s){return !!s.interstitialsController&&s.enableInterstitialPlayback!==false}var Jo=class{constructor(){this.chunks=[],this.dataLength=0;}push(e){this.chunks.push(e),this.dataLength+=e.length;}flush(){let{chunks:e,dataLength:t}=this,i;if(e.length)e.length===1?i=e[0]:i=py(e,t);else return new Uint8Array(0);return this.reset(),i}reset(){this.chunks.length=0,this.dataLength=0;}};function py(s,e){let t=new Uint8Array(e),i=0;for(let r=0;r<s.length;r++){let n=s[r];t.set(n,i),i+=n.length;}return t}var Xd={exports:{}},Xm;function Ey(){return Xm||(Xm=1,function(s){var e=Object.prototype.hasOwnProperty,t="~";function i(){}Object.create&&(i.prototype=Object.create(null),new i().__proto__||(t=false));function r(l,d,c){this.fn=l,this.context=d,this.once=c||false;}function n(l,d,c,u,h){if(typeof c!="function")throw new TypeError("The listener must be a function");var f=new r(c,u||l,h),m=t?t+d:d;return l._events[m]?l._events[m].fn?l._events[m]=[l._events[m],f]:l._events[m].push(f):(l._events[m]=f,l._eventsCount++),l}function a(l,d){--l._eventsCount===0?l._events=new i:delete l._events[d];}function o(){this._events=new i,this._eventsCount=0;}o.prototype.eventNames=function(){var d=[],c,u;if(this._eventsCount===0)return d;for(u in c=this._events)e.call(c,u)&&d.push(t?u.slice(1):u);return Object.getOwnPropertySymbols?d.concat(Object.getOwnPropertySymbols(c)):d},o.prototype.listeners=function(d){var c=t?t+d:d,u=this._events[c];if(!u)return [];if(u.fn)return [u.fn];for(var h=0,f=u.length,m=new Array(f);h<f;h++)m[h]=u[h].fn;return m},o.prototype.listenerCount=function(d){var c=t?t+d:d,u=this._events[c];return u?u.fn?1:u.length:0},o.prototype.emit=function(d,c,u,h,f,m){var p=t?t+d:d;if(!this._events[p])return false;var E=this._events[p],v=arguments.length,T,S;if(E.fn){switch(E.once&&this.removeListener(d,E.fn,void 0,true),v){case 1:return E.fn.call(E.context),true;case 2:return E.fn.call(E.context,c),true;case 3:return E.fn.call(E.context,c,u),true;case 4:return E.fn.call(E.context,c,u,h),true;case 5:return E.fn.call(E.context,c,u,h,f),true;case 6:return E.fn.call(E.context,c,u,h,f,m),true}for(S=1,T=new Array(v-1);S<v;S++)T[S-1]=arguments[S];E.fn.apply(E.context,T);}else {var A=E.length,b;for(S=0;S<A;S++)switch(E[S].once&&this.removeListener(d,E[S].fn,void 0,true),v){case 1:E[S].fn.call(E[S].context);break;case 2:E[S].fn.call(E[S].context,c);break;case 3:E[S].fn.call(E[S].context,c,u);break;case 4:E[S].fn.call(E[S].context,c,u,h);break;default:if(!T)for(b=1,T=new Array(v-1);b<v;b++)T[b-1]=arguments[b];E[S].fn.apply(E[S].context,T);}}return true},o.prototype.on=function(d,c,u){return n(this,d,c,u,false)},o.prototype.once=function(d,c,u){return n(this,d,c,u,true)},o.prototype.removeListener=function(d,c,u,h){var f=t?t+d:d;if(!this._events[f])return this;if(!c)return a(this,f),this;var m=this._events[f];if(m.fn)m.fn===c&&(!h||m.once)&&(!u||m.context===u)&&a(this,f);else {for(var p=0,E=[],v=m.length;p<v;p++)(m[p].fn!==c||h&&!m[p].once||u&&m[p].context!==u)&&E.push(m[p]);E.length?this._events[f]=E.length===1?E[0]:E:a(this,f);}return this},o.prototype.removeAllListeners=function(d){var c;return d?(c=t?t+d:d,this._events[c]&&a(this,c)):(this._events=new i,this._eventsCount=0),this},o.prototype.off=o.prototype.removeListener,o.prototype.addListener=o.prototype.on,o.prefixed=t,o.EventEmitter=o,s.exports=o;}(Xd)),Xd.exports}var vy=Ey(),Bu=Zv(vy),Sn="1.6.13",or={};function Ty(){return typeof __HLS_WORKER_BUNDLE__=="function"}function yy(){let s=or[Sn];if(s)return s.clientCount++,s;let e=new self.Blob([`var exports={};var module={exports:exports};function define(f){f()};define.amd=true;(${__HLS_WORKER_BUNDLE__.toString()})(true);`],{type:"text/javascript"}),t=self.URL.createObjectURL(e),r={worker:new self.Worker(t),objectURL:t,clientCount:1};return or[Sn]=r,r}function Sy(s){let e=or[s];if(e)return e.clientCount++,e;let t=new self.URL(s,self.location.href).href,r={worker:new self.Worker(t),scriptURL:t,clientCount:1};return or[s]=r,r}function Ay(s){let e=or[s||Sn];if(e&&e.clientCount--===1){let{worker:i,objectURL:r}=e;delete or[s||Sn],r&&self.URL.revokeObjectURL(r),i.terminate();}}function sp(s,e){return e+10<=s.length&&s[e]===51&&s[e+1]===68&&s[e+2]===73&&s[e+3]<255&&s[e+4]<255&&s[e+6]<128&&s[e+7]<128&&s[e+8]<128&&s[e+9]<128}function $u(s,e){return e+10<=s.length&&s[e]===73&&s[e+1]===68&&s[e+2]===51&&s[e+3]<255&&s[e+4]<255&&s[e+6]<128&&s[e+7]<128&&s[e+8]<128&&s[e+9]<128}function fl(s,e){let t=0;return t=(s[e]&127)<<21,t|=(s[e+1]&127)<<14,t|=(s[e+2]&127)<<7,t|=s[e+3]&127,t}function An(s,e){let t=e,i=0;for(;$u(s,e);){i+=10;let r=fl(s,e+6);i+=r,sp(s,e+10)&&(i+=10),e+=i;}if(i>0)return s.subarray(t,t+i)}function by(s,e,t,i){let r=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],n=e[t+2],a=n>>2&15;if(a>12){let f=new Error(`invalid ADTS sampling index:${a}`);s.emit(g.ERROR,g.ERROR,{type:z.MEDIA_ERROR,details:x.FRAG_PARSING_ERROR,fatal:true,error:f,reason:f.message});return}let o=(n>>6&3)+1,l=e[t+3]>>6&3|(n&1)<<2,d="mp4a.40."+o,c=r[a],u=a;(o===5||o===29)&&(u-=3);let h=[o<<3|(u&14)>>1,(u&1)<<7|l<<3];return Te.log(`manifest codec:${i}, parsed codec:${d}, channels:${l}, rate:${c} (ADTS object type:${o} sampling index:${a})`),{config:h,samplerate:c,channelCount:l,codec:d,parsedCodec:d,manifestCodec:i}}function rp(s,e){return s[e]===255&&(s[e+1]&246)===240}function np(s,e){return s[e+1]&1?7:9}function Gu(s,e){return (s[e+3]&3)<<11|s[e+4]<<3|(s[e+5]&224)>>>5}function _y(s,e){return e+5<s.length}function el(s,e){return e+1<s.length&&rp(s,e)}function Iy(s,e){return _y(s,e)&&rp(s,e)&&Gu(s,e)<=s.length-e}function Ly(s,e){if(el(s,e)){let t=np(s,e);if(e+t>=s.length)return false;let i=Gu(s,e);if(i<=t)return false;let r=e+i;return r===s.length||el(s,r)}return false}function ap(s,e,t,i,r){if(!s.samplerate){let n=by(e,t,i,r);if(!n)return;ye(s,n);}}function op(s){return 1024*9e4/s}function xy(s,e){let t=np(s,e);if(e+t<=s.length){let i=Gu(s,e)-t;if(i>0)return {headerLength:t,frameLength:i}}}function lp(s,e,t,i,r){let n=op(s.samplerate),a=i+r*n,o=xy(e,t),l;if(o){let{frameLength:u,headerLength:h}=o,f=h+u,m=Math.max(0,t+f-e.length);m?(l=new Uint8Array(f-h),l.set(e.subarray(t+h,e.length),0)):l=e.subarray(t+h,t+f);let p={unit:l,pts:a};return m||s.samples.push(p),{sample:p,length:f,missing:m}}let d=e.length-t;return l=new Uint8Array(d),l.set(e.subarray(t,e.length),0),{sample:{unit:l,pts:a},length:d,missing:-1}}function Ry(s,e){return $u(s,e)&&fl(s,e+6)+10<=s.length-e}function ky(s){return s instanceof ArrayBuffer?s:s.byteOffset==0&&s.byteLength==s.buffer.byteLength?s.buffer:new Uint8Array(s).buffer}function Zd(s,e=0,t=1/0){return Dy(s,e,t,Uint8Array)}function Dy(s,e,t,i){let r=Cy(s),n=1;"BYTES_PER_ELEMENT"in i&&(n=i.BYTES_PER_ELEMENT);let a=My(s)?s.byteOffset:0,o=(a+s.byteLength)/n,l=(a+e)/n,d=Math.floor(Math.max(0,Math.min(l,o))),c=Math.floor(Math.min(d+Math.max(t,0),o));return new i(r,d,c-d)}function Cy(s){return s instanceof ArrayBuffer?s:s.buffer}function My(s){return s&&s.buffer instanceof ArrayBuffer&&s.byteLength!==void 0&&s.byteOffset!==void 0}function Py(s){let e={key:s.type,description:"",data:"",mimeType:null,pictureType:null},t=3;if(s.size<2)return;if(s.data[0]!==t){console.log("Ignore frame with unrecognized character encoding");return}let i=s.data.subarray(1).indexOf(0);if(i===-1)return;let r=bt(Zd(s.data,1,i)),n=s.data[2+i],a=s.data.subarray(3+i).indexOf(0);if(a===-1)return;let o=bt(Zd(s.data,3+i,a)),l;return r==="-->"?l=bt(Zd(s.data,4+i+a)):l=ky(s.data.subarray(4+i+a)),e.mimeType=r,e.pictureType=n,e.description=o,e.data=l,e}function wy(s){if(s.size<2)return;let e=bt(s.data,true),t=new Uint8Array(s.data.subarray(e.length+1));return {key:s.type,info:e,data:t.buffer}}function Oy(s){if(s.size<2)return;if(s.type==="TXXX"){let t=1,i=bt(s.data.subarray(t),true);t+=i.length+1;let r=bt(s.data.subarray(t));return {key:s.type,info:i,data:r}}let e=bt(s.data.subarray(1));return {key:s.type,info:"",data:e}}function Fy(s){if(s.type==="WXXX"){if(s.size<2)return;let t=1,i=bt(s.data.subarray(t),true);t+=i.length+1;let r=bt(s.data.subarray(t));return {key:s.type,info:i,data:r}}let e=bt(s.data);return {key:s.type,info:"",data:e}}function Ny(s){return s.type==="PRIV"?wy(s):s.type[0]==="W"?Fy(s):s.type==="APIC"?Py(s):Oy(s)}function Uy(s){let e=String.fromCharCode(s[0],s[1],s[2],s[3]),t=fl(s,4),i=10;return {type:e,size:t,data:s.subarray(i,i+t)}}var bo=10,By=10;function dp(s){let e=0,t=[];for(;$u(s,e);){let i=fl(s,e+6);s[e+5]>>6&1&&(e+=bo),e+=bo;let r=e+i;for(;e+By<r;){let n=Uy(s.subarray(e)),a=Ny(n);a&&t.push(a),e+=n.size+bo;}sp(s,e)&&(e+=bo);}return t}function cp(s){return s&&s.key==="PRIV"&&s.info==="com.apple.streaming.transportStreamTimestamp"}function $y(s){if(s.data.byteLength===8){let e=new Uint8Array(s.data),t=e[3]&1,i=(e[4]<<23)+(e[5]<<15)+(e[6]<<7)+e[7];return i/=45,t&&(i+=4772185884e-2),Math.round(i)}}function Hu(s){let e=dp(s);for(let t=0;t<e.length;t++){let i=e[t];if(cp(i))return $y(i)}}var At=function(s){return s.audioId3="org.id3",s.dateRange="com.apple.quicktime.HLS",s.emsg="https://aomedia.org/emsg/ID3",s.misbklv="urn:misb:KLV:bin:1910.1",s}({});function li(s="",e=9e4){return {type:s,id:-1,pid:-1,inputTimeScale:e,sequenceNumber:-1,samples:[],dropped:0}}var bn=class{constructor(){this._audioTrack=void 0,this._id3Track=void 0,this.frameIndex=0,this.cachedData=null,this.basePTS=null,this.initPTS=null,this.lastPTS=null;}resetInitSegment(e,t,i,r){this._id3Track={type:"id3",id:3,pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0};}resetTimeStamp(e){this.initPTS=e,this.resetContiguity();}resetContiguity(){this.basePTS=null,this.lastPTS=null,this.frameIndex=0;}canParse(e,t){return false}appendFrame(e,t,i){}demux(e,t){this.cachedData&&(e=Dt(this.cachedData,e),this.cachedData=null);let i=An(e,0),r=i?i.length:0,n,a=this._audioTrack,o=this._id3Track,l=i?Hu(i):void 0,d=e.length;for((this.basePTS===null||this.frameIndex===0&&G(l))&&(this.basePTS=Gy(l,t,this.initPTS),this.lastPTS=this.basePTS),this.lastPTS===null&&(this.lastPTS=this.basePTS),i&&i.length>0&&o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:i,type:At.audioId3,duration:Number.POSITIVE_INFINITY});r<d;){if(this.canParse(e,r)){let c=this.appendFrame(a,e,r);c?(this.frameIndex++,this.lastPTS=c.sample.pts,r+=c.length,n=r):r=d;}else Ry(e,r)?(i=An(e,r),o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:i,type:At.audioId3,duration:Number.POSITIVE_INFINITY}),r+=i.length,n=r):r++;if(r===d&&n!==d){let c=e.slice(n);this.cachedData?this.cachedData=Dt(this.cachedData,c):this.cachedData=c;}}return {audioTrack:a,videoTrack:li(),id3Track:o,textTrack:li()}}demuxSampleAes(e,t,i){return Promise.reject(new Error(`[${this}] This demuxer does not support Sample-AES decryption`))}flush(e){let t=this.cachedData;return t&&(this.cachedData=null,this.demux(t,0)),{audioTrack:this._audioTrack,videoTrack:li(),id3Track:this._id3Track,textTrack:li()}}destroy(){this.cachedData=null,this._audioTrack=this._id3Track=void 0;}},Gy=(s,e,t)=>{if(G(s))return s*90;let i=t?t.baseTime*9e4/t.timescale:0;return e*9e4+i},_o=null,Hy=[32,64,96,128,160,192,224,256,288,320,352,384,416,448,32,48,56,64,80,96,112,128,160,192,224,256,320,384,32,40,48,56,64,80,96,112,128,160,192,224,256,320,32,48,56,64,80,96,112,128,144,160,176,192,224,256,8,16,24,32,40,48,56,64,80,96,112,128,144,160],Ky=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],Vy=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],Wy=[0,1,1,4];function up(s,e,t,i,r){if(t+24>e.length)return;let n=hp(e,t);if(n&&t+n.frameLength<=e.length){let a=n.samplesPerFrame*9e4/n.sampleRate,o=i+r*a,l={unit:e.subarray(t,t+n.frameLength),pts:o,dts:o};return s.config=[],s.channelCount=n.channelCount,s.samplerate=n.sampleRate,s.samples.push(l),{sample:l,length:n.frameLength,missing:0}}}function hp(s,e){let t=s[e+1]>>3&3,i=s[e+1]>>1&3,r=s[e+2]>>4&15,n=s[e+2]>>2&3;if(t!==1&&r!==0&&r!==15&&n!==3){let a=s[e+2]>>1&1,o=s[e+3]>>6,l=t===3?3-i:i===3?3:4,d=Hy[l*14+r-1]*1e3,u=Ky[(t===3?0:t===2?1:2)*3+n],h=o===3?1:2,f=Vy[t][i],m=Wy[i],p=f*8*m,E=Math.floor(f*d/u+a)*m;if(_o===null){let S=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);_o=S?parseInt(S[1]):0;}return !!_o&&_o<=87&&i===2&&d>=224e3&&o===0&&(s[e+3]=s[e+3]|128),{sampleRate:u,channelCount:h,frameLength:E,samplesPerFrame:p}}}function Ku(s,e){return s[e]===255&&(s[e+1]&224)===224&&(s[e+1]&6)!==0}function fp(s,e){return e+1<s.length&&Ku(s,e)}function Yy(s,e){return Ku(s,e)&&4<=s.length-e}function mp(s,e){if(e+1<s.length&&Ku(s,e)){let i=hp(s,e),r=4;i!=null&&i.frameLength&&(r=i.frameLength);let n=e+r;return n===s.length||fp(s,n)}return false}var Mc=class extends bn{constructor(e,t){super(),this.observer=void 0,this.config=void 0,this.observer=e,this.config=t;}resetInitSegment(e,t,i,r){super.resetInitSegment(e,t,i,r),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:t,duration:r,inputTimeScale:9e4,dropped:0};}static probe(e,t){if(!e)return false;let i=An(e,0),r=i?.length||0;if(mp(e,r))return false;for(let n=e.length;r<n;r++)if(Ly(e,r))return t.log("ADTS sync word found !"),true;return false}canParse(e,t){return Iy(e,t)}appendFrame(e,t,i){ap(e,this.observer,t,i,e.manifestCodec);let r=lp(e,t,i,this.basePTS,this.frameIndex);if(r&&r.missing===0)return r}},gp=(s,e)=>{let t=0,i=5;e+=i;let r=new Uint32Array(1),n=new Uint32Array(1),a=new Uint8Array(1);for(;i>0;){a[0]=s[e];let o=Math.min(i,8),l=8-o;n[0]=4278190080>>>24+l<<l,r[0]=(a[0]&n[0])>>l,t=t?t<<o|r[0]:r[0],e+=1,i-=o;}return t},Pc=class extends bn{constructor(e){super(),this.observer=void 0,this.observer=e;}resetInitSegment(e,t,i,r){super.resetInitSegment(e,t,i,r),this._audioTrack={container:"audio/ac-3",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"ac3",samples:[],manifestCodec:t,duration:r,inputTimeScale:9e4,dropped:0};}canParse(e,t){return t+64<e.length}appendFrame(e,t,i){let r=pp(e,t,i,this.basePTS,this.frameIndex);if(r!==-1)return {sample:e.samples[e.samples.length-1],length:r,missing:0}}static probe(e){if(!e)return false;let t=An(e,0);if(!t)return false;let i=t.length;return e[i]===11&&e[i+1]===119&&Hu(t)!==void 0&&gp(e,i)<16}};function pp(s,e,t,i,r){if(t+8>e.length||e[t]!==11||e[t+1]!==119)return -1;let n=e[t+4]>>6;if(n>=3)return -1;let o=[48e3,44100,32e3][n],l=e[t+4]&63,c=[64,69,96,64,70,96,80,87,120,80,88,120,96,104,144,96,105,144,112,121,168,112,122,168,128,139,192,128,140,192,160,174,240,160,175,240,192,208,288,192,209,288,224,243,336,224,244,336,256,278,384,256,279,384,320,348,480,320,349,480,384,417,576,384,418,576,448,487,672,448,488,672,512,557,768,512,558,768,640,696,960,640,697,960,768,835,1152,768,836,1152,896,975,1344,896,976,1344,1024,1114,1536,1024,1115,1536,1152,1253,1728,1152,1254,1728,1280,1393,1920,1280,1394,1920][l*3+n]*2;if(t+c>e.length)return -1;let u=e[t+6]>>5,h=0;u===2?h+=2:(u&1&&u!==1&&(h+=2),u&4&&(h+=2));let f=(e[t+6]<<8|e[t+7])>>12-h&1,p=[2,1,2,3,3,4,4,5][u]+f,E=e[t+5]>>3,v=e[t+5]&7,T=new Uint8Array([n<<6|E<<1|v>>2,(v&3)<<6|u<<3|f<<2|l>>4,l<<4&224]),S=1536/o*9e4,A=i+r*S,b=e.subarray(t,t+c);return s.config=T,s.channelCount=p,s.samplerate=o,s.samples.push({unit:b,pts:A}),c}var wc=class extends bn{resetInitSegment(e,t,i,r){super.resetInitSegment(e,t,i,r),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:t,duration:r,inputTimeScale:9e4,dropped:0};}static probe(e){if(!e)return false;let t=An(e,0),i=t?.length||0;if(t&&e[i]===11&&e[i+1]===119&&Hu(t)!==void 0&&gp(e,i)<=16)return false;for(let r=e.length;i<r;i++)if(mp(e,i))return Te.log("MPEG Audio sync word found !"),true;return false}canParse(e,t){return Yy(e,t)}appendFrame(e,t,i){if(this.basePTS!==null)return up(e,t,i,this.basePTS,this.frameIndex)}},qy=/\/emsg[-/]ID3/i,Oc=class{constructor(e,t){this.remainderData=null,this.timeOffset=0,this.config=void 0,this.videoTrack=void 0,this.audioTrack=void 0,this.id3Track=void 0,this.txtTrack=void 0,this.config=t;}resetTimeStamp(){}resetInitSegment(e,t,i,r){let n=this.videoTrack=li("video",1),a=this.audioTrack=li("audio",1),o=this.txtTrack=li("text",1);if(this.id3Track=li("id3",1),this.timeOffset=0,!(e!=null&&e.byteLength))return;let l=kg(e);if(l.video){let{id:d,timescale:c,codec:u,supplemental:h}=l.video;n.id=d,n.timescale=o.timescale=c,n.codec=u,n.supplemental=h;}if(l.audio){let{id:d,timescale:c,codec:u}=l.audio;a.id=d,a.timescale=c,a.codec=u;}o.id=Lg.text,n.sampleDuration=0,n.duration=a.duration=r;}resetContiguity(){this.remainderData=null;}static probe(e){return iT(e)}demux(e,t){this.timeOffset=t;let i=e,r=this.videoTrack,n=this.txtTrack;if(this.config.progressive){this.remainderData&&(i=Dt(this.remainderData,e));let o=dT(i);this.remainderData=o.remainder,r.samples=o.valid||new Uint8Array;}else r.samples=i;let a=this.extractID3Track(r,t);return n.samples=pm(t,r),{videoTrack:r,audioTrack:this.audioTrack,id3Track:a,textTrack:this.txtTrack}}flush(){let e=this.timeOffset,t=this.videoTrack,i=this.txtTrack;t.samples=this.remainderData||new Uint8Array,this.remainderData=null;let r=this.extractID3Track(t,this.timeOffset);return i.samples=pm(e,t),{videoTrack:t,audioTrack:li(),id3Track:r,textTrack:li()}}extractID3Track(e,t){let i=this.id3Track;if(e.samples.length){let r=le(e.samples,["emsg"]);r&&r.forEach(n=>{let a=uT(n);if(qy.test(a.schemeIdUri)){let o=Zm(a,t),l=a.eventDuration===4294967295?Number.POSITIVE_INFINITY:a.eventDuration/a.timeScale;l<=.001&&(l=Number.POSITIVE_INFINITY);let d=a.payload;i.samples.push({data:d,len:d.byteLength,dts:o,pts:o,type:At.emsg,duration:l});}else if(this.config.enableEmsgKLVMetadata&&a.schemeIdUri.startsWith("urn:misb:KLV:bin:1910.1")){let o=Zm(a,t);i.samples.push({data:a.payload,len:a.payload.byteLength,dts:o,pts:o,type:At.misbklv,duration:Number.POSITIVE_INFINITY});}});}return i}demuxSampleAes(e,t,i){return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"))}destroy(){this.config=null,this.remainderData=null,this.videoTrack=this.audioTrack=this.id3Track=this.txtTrack=void 0;}};function Zm(s,e){return G(s.presentationTime)?s.presentationTime/s.timeScale:e+s.presentationTimeDelta/s.timeScale}var Fc=class{constructor(e,t,i){this.keyData=void 0,this.decrypter=void 0,this.keyData=i,this.decrypter=new En(t,{removePKCS7Padding:false});}decryptBuffer(e){return this.decrypter.decrypt(e,this.keyData.key.buffer,this.keyData.iv.buffer,Ni.cbc)}decryptAacSample(e,t,i){let r=e[t].unit;if(r.length<=16)return;let n=r.subarray(16,r.length-r.length%16),a=n.buffer.slice(n.byteOffset,n.byteOffset+n.length);this.decryptBuffer(a).then(o=>{let l=new Uint8Array(o);r.set(l,16),this.decrypter.isSync()||this.decryptAacSamples(e,t+1,i);}).catch(i);}decryptAacSamples(e,t,i){for(;;t++){if(t>=e.length){i();return}if(!(e[t].unit.length<32)&&(this.decryptAacSample(e,t,i),!this.decrypter.isSync()))return}}getAvcEncryptedData(e){let t=Math.floor((e.length-48)/160)*16+16,i=new Int8Array(t),r=0;for(let n=32;n<e.length-16;n+=160,r+=16)i.set(e.subarray(n,n+16),r);return i}getAvcDecryptedUnit(e,t){let i=new Uint8Array(t),r=0;for(let n=32;n<e.length-16;n+=160,r+=16)e.set(i.subarray(r,r+16),n);return e}decryptAvcSample(e,t,i,r,n){let a=Mg(n.data),o=this.getAvcEncryptedData(a);this.decryptBuffer(o.buffer).then(l=>{n.data=this.getAvcDecryptedUnit(a,l),this.decrypter.isSync()||this.decryptAvcSamples(e,t,i+1,r);}).catch(r);}decryptAvcSamples(e,t,i,r){if(e instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;t++,i=0){if(t>=e.length){r();return}let n=e[t].units;for(;!(i>=n.length);i++){let a=n[i];if(!(a.data.length<=48||a.type!==1&&a.type!==5)&&(this.decryptAvcSample(e,t,i,r,a),!this.decrypter.isSync()))return}}}},tl=class{constructor(){this.VideoSample=null;}createVideoSample(e,t,i){return {key:e,frame:false,pts:t,dts:i,units:[],length:0}}getLastNalUnit(e){var t;let i=this.VideoSample,r;if((!i||i.units.length===0)&&(i=e[e.length-1]),(t=i)!=null&&t.units){let n=i.units;r=n[n.length-1];}return r}pushAccessUnit(e,t){if(e.units.length&&e.frame){if(e.pts===void 0){let i=t.samples,r=i.length;if(r){let n=i[r-1];e.pts=n.pts,e.dts=n.dts;}else {t.dropped++;return}}t.samples.push(e);}}parseNALu(e,t,i){let r=t.byteLength,n=e.naluState||0,a=n,o=[],l=0,d,c,u,h=-1,f=0;for(n===-1&&(h=0,f=this.getNALuType(t,0),n=0,l=1);l<r;){if(d=t[l++],!n){n=d?0:1;continue}if(n===1){n=d?0:2;continue}if(!d)n=3;else if(d===1){if(c=l-n-1,h>=0){let m={data:t.subarray(h,c),type:f};o.push(m);}else {let m=this.getLastNalUnit(e.samples);m&&(a&&l<=4-a&&m.state&&(m.data=m.data.subarray(0,m.data.byteLength-a)),c>0&&(m.data=Dt(m.data,t.subarray(0,c)),m.state=0));}l<r?(u=this.getNALuType(t,l),h=l,f=u,n=0):n=-1;}else n=0;}if(h>=0&&n>=0){let m={data:t.subarray(h,r),type:f,state:n};o.push(m);}if(o.length===0){let m=this.getLastNalUnit(e.samples);m&&(m.data=Dt(m.data,t));}return e.naluState=n,o}},ls=class{constructor(e){this.data=void 0,this.bytesAvailable=void 0,this.word=void 0,this.bitsAvailable=void 0,this.data=e,this.bytesAvailable=e.byteLength,this.word=0,this.bitsAvailable=0;}loadWord(){let e=this.data,t=this.bytesAvailable,i=e.byteLength-t,r=new Uint8Array(4),n=Math.min(4,t);if(n===0)throw new Error("no bytes available");r.set(e.subarray(i,i+n)),this.word=new DataView(r.buffer).getUint32(0),this.bitsAvailable=n*8,this.bytesAvailable-=n;}skipBits(e){let t;e=Math.min(e,this.bytesAvailable*8+this.bitsAvailable),this.bitsAvailable>e?(this.word<<=e,this.bitsAvailable-=e):(e-=this.bitsAvailable,t=e>>3,e-=t<<3,this.bytesAvailable-=t,this.loadWord(),this.word<<=e,this.bitsAvailable-=e);}readBits(e){let t=Math.min(this.bitsAvailable,e),i=this.word>>>32-t;if(e>32&&Te.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=t,this.bitsAvailable>0)this.word<<=t;else if(this.bytesAvailable>0)this.loadWord();else throw new Error("no bits available");return t=e-t,t>0&&this.bitsAvailable?i<<t|this.readBits(t):i}skipLZ(){let e;for(e=0;e<this.bitsAvailable;++e)if((this.word&2147483648>>>e)!==0)return this.word<<=e,this.bitsAvailable-=e,e;return this.loadWord(),e+this.skipLZ()}skipUEG(){this.skipBits(1+this.skipLZ());}skipEG(){this.skipBits(1+this.skipLZ());}readUEG(){let e=this.skipLZ();return this.readBits(e+1)-1}readEG(){let e=this.readUEG();return 1&e?1+e>>>1:-1*(e>>>1)}readBoolean(){return this.readBits(1)===1}readUByte(){return this.readBits(8)}readUShort(){return this.readBits(16)}readUInt(){return this.readBits(32)}},Nc=class extends tl{parsePES(e,t,i,r){let n=this.parseNALu(e,i.data,r),a=this.VideoSample,o,l=false;i.data=null,a&&n.length&&!e.audFound&&(this.pushAccessUnit(a,e),a=this.VideoSample=this.createVideoSample(false,i.pts,i.dts)),n.forEach(d=>{var c,u;switch(d.type){case 1:{let p=false;o=true;let E=d.data;if(l&&E.length>4){let v=this.readSliceType(E);(v===2||v===4||v===7||v===9)&&(p=true);}if(p){var h;(h=a)!=null&&h.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null);}a||(a=this.VideoSample=this.createVideoSample(true,i.pts,i.dts)),a.frame=true,a.key=p;break}case 5:o=true,(c=a)!=null&&c.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null),a||(a=this.VideoSample=this.createVideoSample(true,i.pts,i.dts)),a.key=true,a.frame=true;break;case 6:{o=true,Pu(d.data,1,i.pts,t.samples);break}case 7:{var f,m;o=true,l=true;let p=d.data,E=this.readSPS(p);if(!e.sps||e.width!==E.width||e.height!==E.height||((f=e.pixelRatio)==null?void 0:f[0])!==E.pixelRatio[0]||((m=e.pixelRatio)==null?void 0:m[1])!==E.pixelRatio[1]){e.width=E.width,e.height=E.height,e.pixelRatio=E.pixelRatio,e.sps=[p];let v=p.subarray(1,4),T="avc1.";for(let S=0;S<3;S++){let A=v[S].toString(16);A.length<2&&(A="0"+A),T+=A;}e.codec=T;}break}case 8:o=true,e.pps=[d.data];break;case 9:o=true,e.audFound=true,(u=a)!=null&&u.frame&&(this.pushAccessUnit(a,e),a=null),a||(a=this.VideoSample=this.createVideoSample(false,i.pts,i.dts));break;case 12:o=true;break;default:o=false;break}a&&o&&a.units.push(d);}),r&&a&&(this.pushAccessUnit(a,e),this.VideoSample=null);}getNALuType(e,t){return e[t]&31}readSliceType(e){let t=new ls(e);return t.readUByte(),t.readUEG(),t.readUEG()}skipScalingList(e,t){let i=8,r=8,n;for(let a=0;a<e;a++)r!==0&&(n=t.readEG(),r=(i+n+256)%256),i=r===0?i:r;}readSPS(e){let t=new ls(e),i=0,r=0,n=0,a=0,o,l,d,c=t.readUByte.bind(t),u=t.readBits.bind(t),h=t.readUEG.bind(t),f=t.readBoolean.bind(t),m=t.skipBits.bind(t),p=t.skipEG.bind(t),E=t.skipUEG.bind(t),v=this.skipScalingList.bind(this);c();let T=c();if(u(5),m(3),c(),E(),T===100||T===110||T===122||T===244||T===44||T===83||T===86||T===118||T===128){let k=h();if(k===3&&m(1),E(),E(),m(1),f())for(l=k!==3?8:12,d=0;d<l;d++)f()&&(d<6?v(16,t):v(64,t));}E();let S=h();if(S===0)h();else if(S===1)for(m(1),p(),p(),o=h(),d=0;d<o;d++)p();E(),m(1);let A=h(),b=h(),D=u(1);D===0&&m(1),m(1),f()&&(i=h(),r=h(),n=h(),a=h());let I=[1,1];if(f()&&f())switch(c()){case 1:I=[1,1];break;case 2:I=[12,11];break;case 3:I=[10,11];break;case 4:I=[16,11];break;case 5:I=[40,33];break;case 6:I=[24,11];break;case 7:I=[20,11];break;case 8:I=[32,11];break;case 9:I=[80,33];break;case 10:I=[18,11];break;case 11:I=[15,11];break;case 12:I=[64,33];break;case 13:I=[160,99];break;case 14:I=[4,3];break;case 15:I=[3,2];break;case 16:I=[2,1];break;case 255:{I=[c()<<8|c(),c()<<8|c()];break}}return {width:Math.ceil((A+1)*16-i*2-r*2),height:(2-D)*(b+1)*16-(D?2:4)*(n+a),pixelRatio:I}}},Uc=class extends tl{constructor(...e){super(...e),this.initVPS=null;}parsePES(e,t,i,r){let n=this.parseNALu(e,i.data,r),a=this.VideoSample,o,l=false;i.data=null,a&&n.length&&!e.audFound&&(this.pushAccessUnit(a,e),a=this.VideoSample=this.createVideoSample(false,i.pts,i.dts)),n.forEach(d=>{var c,u;switch(d.type){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:a||(a=this.VideoSample=this.createVideoSample(false,i.pts,i.dts)),a.frame=true,o=true;break;case 16:case 17:case 18:case 21:if(o=true,l){var h;(h=a)!=null&&h.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null);}a||(a=this.VideoSample=this.createVideoSample(true,i.pts,i.dts)),a.key=true,a.frame=true;break;case 19:case 20:o=true,(c=a)!=null&&c.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null),a||(a=this.VideoSample=this.createVideoSample(true,i.pts,i.dts)),a.key=true,a.frame=true;break;case 39:o=true,Pu(d.data,2,i.pts,t.samples);break;case 32:o=true,e.vps||(typeof e.params!="object"&&(e.params={}),e.params=ye(e.params,this.readVPS(d.data)),this.initVPS=d.data),e.vps=[d.data];break;case 33:if(o=true,l=true,e.vps!==void 0&&e.vps[0]!==this.initVPS&&e.sps!==void 0&&!this.matchSPS(e.sps[0],d.data)&&(this.initVPS=e.vps[0],e.sps=e.pps=void 0),!e.sps){let f=this.readSPS(d.data);e.width=f.width,e.height=f.height,e.pixelRatio=f.pixelRatio,e.codec=f.codecString,e.sps=[],typeof e.params!="object"&&(e.params={});for(let m in f.params)e.params[m]=f.params[m];}this.pushParameterSet(e.sps,d.data,e.vps),a||(a=this.VideoSample=this.createVideoSample(true,i.pts,i.dts)),a.key=true;break;case 34:if(o=true,typeof e.params=="object"){if(!e.pps){e.pps=[];let f=this.readPPS(d.data);for(let m in f)e.params[m]=f[m];}this.pushParameterSet(e.pps,d.data,e.vps);}break;case 35:o=true,e.audFound=true,(u=a)!=null&&u.frame&&(this.pushAccessUnit(a,e),a=null),a||(a=this.VideoSample=this.createVideoSample(false,i.pts,i.dts));break;default:o=false;break}a&&o&&a.units.push(d);}),r&&a&&(this.pushAccessUnit(a,e),this.VideoSample=null);}pushParameterSet(e,t,i){(i&&i[0]===this.initVPS||!i&&!e.length)&&e.push(t);}getNALuType(e,t){return (e[t]&126)>>>1}ebsp2rbsp(e){let t=new Uint8Array(e.byteLength),i=0;for(let r=0;r<e.byteLength;r++)r>=2&&e[r]===3&&e[r-1]===0&&e[r-2]===0||(t[i]=e[r],i++);return new Uint8Array(t.buffer,0,i)}pushAccessUnit(e,t){super.pushAccessUnit(e,t),this.initVPS&&(this.initVPS=null);}readVPS(e){let t=new ls(e);t.readUByte(),t.readUByte(),t.readBits(4),t.skipBits(2),t.readBits(6);let i=t.readBits(3),r=t.readBoolean();return {numTemporalLayers:i+1,temporalIdNested:r}}readSPS(e){let t=new ls(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.readBits(4);let i=t.readBits(3);t.readBoolean();let r=t.readBits(2),n=t.readBoolean(),a=t.readBits(5),o=t.readUByte(),l=t.readUByte(),d=t.readUByte(),c=t.readUByte(),u=t.readUByte(),h=t.readUByte(),f=t.readUByte(),m=t.readUByte(),p=t.readUByte(),E=t.readUByte(),v=t.readUByte(),T=[],S=[];for(let he=0;he<i;he++)T.push(t.readBoolean()),S.push(t.readBoolean());if(i>0)for(let he=i;he<8;he++)t.readBits(2);for(let he=0;he<i;he++)T[he]&&(t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte()),S[he]&&t.readUByte();t.readUEG();let A=t.readUEG();A==3&&t.skipBits(1);let b=t.readUEG(),D=t.readUEG(),I=t.readBoolean(),k=0,R=0,L=0,M=0;I&&(k+=t.readUEG(),R+=t.readUEG(),L+=t.readUEG(),M+=t.readUEG());let B=t.readUEG(),H=t.readUEG(),j=t.readUEG(),K=t.readBoolean();for(let he=K?0:i;he<=i;he++)t.skipUEG(),t.skipUEG(),t.skipUEG();if(t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.readBoolean()&&t.readBoolean())for(let $e=0;$e<4;$e++)for(let it=0;it<($e===3?2:6);it++)if(!t.readBoolean())t.readUEG();else {let _t=Math.min(64,1<<4+($e<<1));$e>1&&t.readEG();for(let fe=0;fe<_t;fe++)t.readEG();}t.readBoolean(),t.readBoolean(),t.readBoolean()&&(t.readUByte(),t.skipUEG(),t.skipUEG(),t.readBoolean());let $=t.readUEG(),q=0;for(let he=0;he<$;he++){let $e=false;if(he!==0&&($e=t.readBoolean()),$e){he===$&&t.readUEG(),t.readBoolean(),t.readUEG();let it=0;for(let Vt=0;Vt<=q;Vt++){let _t=t.readBoolean(),fe=false;_t||(fe=t.readBoolean()),(_t||fe)&&it++;}q=it;}else {let it=t.readUEG(),Vt=t.readUEG();q=it+Vt;for(let _t=0;_t<it;_t++)t.readUEG(),t.readBoolean();for(let _t=0;_t<Vt;_t++)t.readUEG(),t.readBoolean();}}if(t.readBoolean()){let he=t.readUEG();for(let $e=0;$e<he;$e++){for(let it=0;it<j+4;it++)t.readBits(1);t.readBits(1);}}let N=0,U=1,te=1,ge=true,ie=1,de=0;t.readBoolean(),t.readBoolean();let Be=false;if(t.readBoolean()){if(t.readBoolean()){let mt=t.readUByte(),kn=[1,12,10,16,40,24,20,32,80,18,15,64,160,4,3,2],fs=[1,11,11,11,33,11,11,11,33,11,11,33,99,3,2,1];mt>0&&mt<16?(U=kn[mt-1],te=fs[mt-1]):mt===255&&(U=t.readBits(16),te=t.readBits(16));}if(t.readBoolean()&&t.readBoolean(),t.readBoolean()&&(t.readBits(3),t.readBoolean(),t.readBoolean()&&(t.readUByte(),t.readUByte(),t.readUByte())),t.readBoolean()&&(t.readUEG(),t.readUEG()),t.readBoolean(),t.readBoolean(),t.readBoolean(),Be=t.readBoolean(),Be&&(t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG()),t.readBoolean()&&(ie=t.readBits(32),de=t.readBits(32),t.readBoolean()&&t.readUEG(),t.readBoolean())){let fs=t.readBoolean(),Dn=t.readBoolean(),Ui=false;(fs||Dn)&&(Ui=t.readBoolean(),Ui&&(t.readUByte(),t.readBits(5),t.readBoolean(),t.readBits(5)),t.readBits(4),t.readBits(4),Ui&&t.readBits(4),t.readBits(5),t.readBits(5),t.readBits(5));for(let Cn=0;Cn<=i;Cn++){ge=t.readBoolean();let Tl=ge||t.readBoolean(),Mn=false;Tl?t.readEG():Mn=t.readBoolean();let Ze=Mn?1:t.readUEG()+1;if(fs)for(let Ie=0;Ie<Ze;Ie++)t.readUEG(),t.readUEG(),Ui&&(t.readUEG(),t.readUEG()),t.skipBits(1);if(Dn)for(let Ie=0;Ie<Ze;Ie++)t.readUEG(),t.readUEG(),Ui&&(t.readUEG(),t.readUEG()),t.skipBits(1);}}t.readBoolean()&&(t.readBoolean(),t.readBoolean(),t.readBoolean(),N=t.readUEG());}let tt=b,ft=D;if(I){let he=1,$e=1;A===1?he=$e=2:A==2&&(he=2),tt=b-he*R-he*k,ft=D-$e*M-$e*L;}let Kt=r?["A","B","C"][r]:"",Si=o<<24|l<<16|d<<8|c,us=0;for(let he=0;he<32;he++)us=(us|(Si>>he&1)<<31-he)>>>0;let hs=us.toString(16);return a===1&&hs==="2"&&(hs="6"),{codecString:`hvc1.${Kt}${a}.${hs}.${n?"H":"L"}${v}.B0`,params:{general_tier_flag:n,general_profile_idc:a,general_profile_space:r,general_profile_compatibility_flags:[o,l,d,c],general_constraint_indicator_flags:[u,h,f,m,p,E],general_level_idc:v,bit_depth:B+8,bit_depth_luma_minus8:B,bit_depth_chroma_minus8:H,min_spatial_segmentation_idc:N,chroma_format_idc:A,frame_rate:{fixed:ge,fps:de/ie}},width:tt,height:ft,pixelRatio:[U,te]}}readPPS(e){let t=new ls(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.skipUEG(),t.skipUEG(),t.skipBits(2),t.skipBits(3),t.skipBits(2),t.skipUEG(),t.skipUEG(),t.skipEG(),t.skipBits(2),t.readBoolean()&&t.skipUEG(),t.skipEG(),t.skipEG(),t.skipBits(4);let r=t.readBoolean(),n=t.readBoolean(),a=1;return n&&r?a=0:n?a=3:r&&(a=2),{parallelismType:a}}matchSPS(e,t){return String.fromCharCode.apply(null,e).substr(3)===String.fromCharCode.apply(null,t).substr(3)}},je=188,Bc=class s{constructor(e,t,i,r){this.logger=void 0,this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.sampleAes=null,this.pmtParsed=false,this.audioCodec=void 0,this.videoCodec=void 0,this._pmtId=-1,this._videoTrack=void 0,this._audioTrack=void 0,this._id3Track=void 0,this._txtTrack=void 0,this.aacOverFlow=null,this.remainderData=null,this.videoParser=void 0,this.observer=e,this.config=t,this.typeSupported=i,this.logger=r,this.videoParser=null;}static probe(e,t){let i=s.syncOffset(e);return i>0&&t.warn(`MPEG2-TS detected but first sync word found @ offset ${i}`),i!==-1}static syncOffset(e){let t=e.length,i=Math.min(je*5,t-je)+1,r=0;for(;r<i;){let n=false,a=-1,o=0;for(let l=r;l<t;l+=je)if(e[l]===71&&(t-l===je||e[l+je]===71)){if(o++,a===-1&&(a=l,a!==0&&(i=Math.min(a+je*99,e.length-je)+1)),n||(n=$c(e,l)===0),n&&o>1&&(a===0&&o>2||l+je>i))return a}else {if(o)return -1;break}r++;}return -1}static createTrack(e,t){return {container:e==="video"||e==="audio"?"video/mp2t":void 0,type:e,id:Lg[e],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:e==="audio"?t:void 0}}resetInitSegment(e,t,i,r){this.pmtParsed=false,this._pmtId=-1,this._videoTrack=s.createTrack("video"),this._videoTrack.duration=r,this._audioTrack=s.createTrack("audio",r),this._id3Track=s.createTrack("id3"),this._txtTrack=s.createTrack("text"),this._audioTrack.segmentCodec="aac",this.videoParser=null,this.aacOverFlow=null,this.remainderData=null,this.audioCodec=t,this.videoCodec=i;}resetTimeStamp(){}resetContiguity(){let{_audioTrack:e,_videoTrack:t,_id3Track:i}=this;e&&(e.pesData=null),t&&(t.pesData=null),i&&(i.pesData=null),this.aacOverFlow=null,this.remainderData=null;}demux(e,t,i=false,r=false){i||(this.sampleAes=null);let n,a=this._videoTrack,o=this._audioTrack,l=this._id3Track,d=this._txtTrack,c=a.pid,u=a.pesData,h=o.pid,f=l.pid,m=o.pesData,p=l.pesData,E=null,v=this.pmtParsed,T=this._pmtId,S=e.length;if(this.remainderData&&(e=Dt(this.remainderData,e),S=e.length,this.remainderData=null),S<je&&!r)return this.remainderData=e,{audioTrack:o,videoTrack:a,id3Track:l,textTrack:d};let A=Math.max(0,s.syncOffset(e));S-=(S-A)%je,S<e.byteLength&&!r&&(this.remainderData=new Uint8Array(e.buffer,S,e.buffer.byteLength-S));let b=0;for(let I=A;I<S;I+=je)if(e[I]===71){let k=!!(e[I+1]&64),R=$c(e,I),L=(e[I+3]&48)>>4,M;if(L>1){if(M=I+5+e[I+4],M===I+je)continue}else M=I+4;switch(R){case c:k&&(u&&(n=Xs(u,this.logger))&&(this.readyVideoParser(a.segmentCodec),this.videoParser!==null&&this.videoParser.parsePES(a,d,n,false)),u={data:[],size:0}),u&&(u.data.push(e.subarray(M,I+je)),u.size+=I+je-M);break;case h:if(k){if(m&&(n=Xs(m,this.logger)))switch(o.segmentCodec){case "aac":this.parseAACPES(o,n);break;case "mp3":this.parseMPEGPES(o,n);break;case "ac3":this.parseAC3PES(o,n);break}m={data:[],size:0};}m&&(m.data.push(e.subarray(M,I+je)),m.size+=I+je-M);break;case f:k&&(p&&(n=Xs(p,this.logger))&&this.parseID3PES(l,n),p={data:[],size:0}),p&&(p.data.push(e.subarray(M,I+je)),p.size+=I+je-M);break;case 0:k&&(M+=e[M]+1),T=this._pmtId=jy(e,M);break;case T:{k&&(M+=e[M]+1);let B=zy(e,M,this.typeSupported,i,this.observer,this.logger);c=B.videoPid,c>0&&(a.pid=c,a.segmentCodec=B.segmentVideoCodec),h=B.audioPid,h>0&&(o.pid=h,o.segmentCodec=B.segmentAudioCodec),f=B.id3Pid,f>0&&(l.pid=f),E!==null&&!v&&(this.logger.warn(`MPEG-TS PMT found at ${I} after unknown PID '${E}'. Backtracking to sync byte @${A} to parse all TS packets.`),E=null,I=A-188),v=this.pmtParsed=true;break}case 17:case 8191:break;default:E=R;break}}else b++;b>0&&Gc(this.observer,new Error(`Found ${b} TS packet/s that do not start with 0x47`),void 0,this.logger),a.pesData=u,o.pesData=m,l.pesData=p;let D={audioTrack:o,videoTrack:a,id3Track:l,textTrack:d};return r&&this.extractRemainingSamples(D),D}flush(){let{remainderData:e}=this;this.remainderData=null;let t;return e?t=this.demux(e,-1,false,true):t={videoTrack:this._videoTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(t),this.sampleAes?this.decrypt(t,this.sampleAes):t}extractRemainingSamples(e){let{audioTrack:t,videoTrack:i,id3Track:r,textTrack:n}=e,a=i.pesData,o=t.pesData,l=r.pesData,d;if(a&&(d=Xs(a,this.logger))?(this.readyVideoParser(i.segmentCodec),this.videoParser!==null&&(this.videoParser.parsePES(i,n,d,true),i.pesData=null)):i.pesData=a,o&&(d=Xs(o,this.logger))){switch(t.segmentCodec){case "aac":this.parseAACPES(t,d);break;case "mp3":this.parseMPEGPES(t,d);break;case "ac3":this.parseAC3PES(t,d);break}t.pesData=null;}else o!=null&&o.size&&this.logger.log("last AAC PES packet truncated,might overlap between fragments"),t.pesData=o;l&&(d=Xs(l,this.logger))?(this.parseID3PES(r,d),r.pesData=null):r.pesData=l;}demuxSampleAes(e,t,i){let r=this.demux(e,i,true,!this.config.progressive),n=this.sampleAes=new Fc(this.observer,this.config,t);return this.decrypt(r,n)}readyVideoParser(e){this.videoParser===null&&(e==="avc"?this.videoParser=new Nc:e==="hevc"&&(this.videoParser=new Uc));}decrypt(e,t){return new Promise(i=>{let{audioTrack:r,videoTrack:n}=e;r.samples&&r.segmentCodec==="aac"?t.decryptAacSamples(r.samples,0,()=>{n.samples?t.decryptAvcSamples(n.samples,0,0,()=>{i(e);}):i(e);}):n.samples&&t.decryptAvcSamples(n.samples,0,0,()=>{i(e);});})}destroy(){this.observer&&this.observer.removeAllListeners(),this.config=this.logger=this.observer=null,this.aacOverFlow=this.videoParser=this.remainderData=this.sampleAes=null,this._videoTrack=this._audioTrack=this._id3Track=this._txtTrack=void 0;}parseAACPES(e,t){let i=0,r=this.aacOverFlow,n=t.data;if(r){this.aacOverFlow=null;let u=r.missing,h=r.sample.unit.byteLength;if(u===-1)n=Dt(r.sample.unit,n);else {let f=h-u;r.sample.unit.set(n.subarray(0,u),f),e.samples.push(r.sample),i=r.missing;}}let a,o;for(a=i,o=n.length;a<o-1&&!el(n,a);a++);if(a!==i){let u,h=a<o-1;if(h?u=`AAC PES did not start with ADTS header,offset:${a}`:u="No ADTS header found in AAC PES",Gc(this.observer,new Error(u),h,this.logger),!h)return}ap(e,this.observer,n,a,this.audioCodec);let l;if(t.pts!==void 0)l=t.pts;else if(r){let u=op(e.samplerate);l=r.sample.pts+u;}else {this.logger.warn("[tsdemuxer]: AAC PES unknown PTS");return}let d=0,c;for(;a<o;)if(c=lp(e,n,a,l,d),a+=c.length,c.missing){this.aacOverFlow=c;break}else for(d++;a<o-1&&!el(n,a);a++);}parseMPEGPES(e,t){let i=t.data,r=i.length,n=0,a=0,o=t.pts;if(o===void 0){this.logger.warn("[tsdemuxer]: MPEG PES unknown PTS");return}for(;a<r;)if(fp(i,a)){let l=up(e,i,a,o,n);if(l)a+=l.length,n++;else break}else a++;}parseAC3PES(e,t){{let i=t.data,r=t.pts;if(r===void 0){this.logger.warn("[tsdemuxer]: AC3 PES unknown PTS");return}let n=i.length,a=0,o=0,l;for(;o<n&&(l=pp(e,i,o,r,a++))>0;)o+=l;}}parseID3PES(e,t){if(t.pts===void 0){this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS");return}let i=ye({},t,{type:this._videoTrack?At.emsg:At.audioId3,duration:Number.POSITIVE_INFINITY});e.samples.push(i);}};function $c(s,e){return ((s[e+1]&31)<<8)+s[e+2]}function jy(s,e){return (s[e+10]&31)<<8|s[e+11]}function zy(s,e,t,i,r,n){let a={audioPid:-1,videoPid:-1,id3Pid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},o=(s[e+1]&15)<<8|s[e+2],l=e+3+o-4,d=(s[e+10]&15)<<8|s[e+11];for(e+=12+d;e<l;){let c=$c(s,e),u=(s[e+3]&15)<<8|s[e+4];switch(s[e]){case 207:if(!i){Jd("ADTS AAC",n);break}case 15:a.audioPid===-1&&(a.audioPid=c);break;case 21:a.id3Pid===-1&&(a.id3Pid=c);break;case 219:if(!i){Jd("H.264",n);break}case 27:a.videoPid===-1&&(a.videoPid=c);break;case 3:case 4:!t.mpeg&&!t.mp3?n.log("MPEG audio found, not supported in this browser"):a.audioPid===-1&&(a.audioPid=c,a.segmentAudioCodec="mp3");break;case 193:if(!i){Jd("AC-3",n);break}case 129:t.ac3?a.audioPid===-1&&(a.audioPid=c,a.segmentAudioCodec="ac3"):n.log("AC-3 audio found, not supported in this browser");break;case 6:if(a.audioPid===-1&&u>0){let h=e+5,f=u;for(;f>2;){switch(s[h]){case 106:t.ac3!==true?n.log("AC-3 audio found, not supported in this browser for now"):(a.audioPid=c,a.segmentAudioCodec="ac3");break}let p=s[h+1]+2;h+=p,f-=p;}}break;case 194:case 135:return Gc(r,new Error("Unsupported EC-3 in M2TS found"),void 0,n),a;case 36:a.videoPid===-1&&(a.videoPid=c,a.segmentVideoCodec="hevc",n.log("HEVC in M2TS found"));break}e+=u+5;}return a}function Gc(s,e,t,i){i.warn(`parsing error: ${e.message}`),s.emit(g.ERROR,g.ERROR,{type:z.MEDIA_ERROR,details:x.FRAG_PARSING_ERROR,fatal:false,levelRetry:t,error:e,reason:e.message});}function Jd(s,e){e.log(`${s} with AES-128-CBC encryption found in unencrypted stream`);}function Xs(s,e){let t=0,i,r,n,a,o,l=s.data;if(!s||s.size===0)return null;for(;l[0].length<19&&l.length>1;)l[0]=Dt(l[0],l[1]),l.splice(1,1);if(i=l[0],(i[0]<<16)+(i[1]<<8)+i[2]===1){if(r=(i[4]<<8)+i[5],r&&r>s.size-6)return null;let c=i[7];c&192&&(a=(i[9]&14)*536870912+(i[10]&255)*4194304+(i[11]&254)*16384+(i[12]&255)*128+(i[13]&254)/2,c&64?(o=(i[14]&14)*536870912+(i[15]&255)*4194304+(i[16]&254)*16384+(i[17]&255)*128+(i[18]&254)/2,a-o>60*9e4&&(e.warn(`${Math.round((a-o)/9e4)}s delta between PTS and DTS, align them`),a=o)):o=a),n=i[8];let u=n+9;if(s.size<=u)return null;s.size-=u;let h=new Uint8Array(s.size);for(let f=0,m=l.length;f<m;f++){i=l[f];let p=i.byteLength;if(u)if(u>p){u-=p;continue}else i=i.subarray(u),p-=u,u=0;h.set(i,t),t+=p;}return r&&(r-=n+3),{data:h,pts:a,dts:o,len:r}}return null}var Hc=class{static getSilentFrame(e,t){switch(e){case "mp4a.40.2":if(t===1)return new Uint8Array([0,200,0,128,35,128]);if(t===2)return new Uint8Array([33,0,73,144,2,25,0,35,128]);if(t===3)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,142]);if(t===4)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,128,44,128,8,2,56]);if(t===5)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,56]);if(t===6)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,0,178,0,32,8,224]);break;default:if(t===1)return new Uint8Array([1,64,34,128,163,78,230,128,186,8,0,0,0,28,6,241,193,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(t===2)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(t===3)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);break}}},Mi=Math.pow(2,32)-1,Ve=class s{static init(){s.types={avc1:[],avcC:[],hvc1:[],hvcC:[],btrt:[],dinf:[],dref:[],esds:[],ftyp:[],hdlr:[],mdat:[],mdhd:[],mdia:[],mfhd:[],minf:[],moof:[],moov:[],mp4a:[],".mp3":[],dac3:[],"ac-3":[],mvex:[],mvhd:[],pasp:[],sdtp:[],stbl:[],stco:[],stsc:[],stsd:[],stsz:[],stts:[],tfdt:[],tfhd:[],traf:[],trak:[],trun:[],trex:[],tkhd:[],vmhd:[],smhd:[]};let e;for(e in s.types)s.types.hasOwnProperty(e)&&(s.types[e]=[e.charCodeAt(0),e.charCodeAt(1),e.charCodeAt(2),e.charCodeAt(3)]);let t=new Uint8Array([0,0,0,0,0,0,0,0,118,105,100,101,0,0,0,0,0,0,0,0,0,0,0,0,86,105,100,101,111,72,97,110,100,108,101,114,0]),i=new Uint8Array([0,0,0,0,0,0,0,0,115,111,117,110,0,0,0,0,0,0,0,0,0,0,0,0,83,111,117,110,100,72,97,110,100,108,101,114,0]);s.HDLR_TYPES={video:t,audio:i};let r=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1]),n=new Uint8Array([0,0,0,0,0,0,0,0]);s.STTS=s.STSC=s.STCO=n,s.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),s.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),s.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),s.STSD=new Uint8Array([0,0,0,0,0,0,0,1]);let a=new Uint8Array([105,115,111,109]),o=new Uint8Array([97,118,99,49]),l=new Uint8Array([0,0,0,1]);s.FTYP=s.box(s.types.ftyp,a,l,a,o),s.DINF=s.box(s.types.dinf,s.box(s.types.dref,r));}static box(e,...t){let i=8,r=t.length,n=r;for(;r--;)i+=t[r].byteLength;let a=new Uint8Array(i);for(a[0]=i>>24&255,a[1]=i>>16&255,a[2]=i>>8&255,a[3]=i&255,a.set(e,4),r=0,i=8;r<n;r++)a.set(t[r],i),i+=t[r].byteLength;return a}static hdlr(e){return s.box(s.types.hdlr,s.HDLR_TYPES[e])}static mdat(e){return s.box(s.types.mdat,e)}static mdhd(e,t){t*=e;let i=Math.floor(t/(Mi+1)),r=Math.floor(t%(Mi+1));return s.box(s.types.mdhd,new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,e&255,i>>24,i>>16&255,i>>8&255,i&255,r>>24,r>>16&255,r>>8&255,r&255,85,196,0,0]))}static mdia(e){return s.box(s.types.mdia,s.mdhd(e.timescale||0,e.duration||0),s.hdlr(e.type),s.minf(e))}static mfhd(e){return s.box(s.types.mfhd,new Uint8Array([0,0,0,0,e>>24,e>>16&255,e>>8&255,e&255]))}static minf(e){return e.type==="audio"?s.box(s.types.minf,s.box(s.types.smhd,s.SMHD),s.DINF,s.stbl(e)):s.box(s.types.minf,s.box(s.types.vmhd,s.VMHD),s.DINF,s.stbl(e))}static moof(e,t,i){return s.box(s.types.moof,s.mfhd(e),s.traf(i,t))}static moov(e){let t=e.length,i=[];for(;t--;)i[t]=s.trak(e[t]);return s.box.apply(null,[s.types.moov,s.mvhd(e[0].timescale||0,e[0].duration||0)].concat(i).concat(s.mvex(e)))}static mvex(e){let t=e.length,i=[];for(;t--;)i[t]=s.trex(e[t]);return s.box.apply(null,[s.types.mvex,...i])}static mvhd(e,t){t*=e;let i=Math.floor(t/(Mi+1)),r=Math.floor(t%(Mi+1)),n=new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,e&255,i>>24,i>>16&255,i>>8&255,i&255,r>>24,r>>16&255,r>>8&255,r&255,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255]);return s.box(s.types.mvhd,n)}static sdtp(e){let t=e.samples||[],i=new Uint8Array(4+t.length),r,n;for(r=0;r<t.length;r++)n=t[r].flags,i[r+4]=n.dependsOn<<4|n.isDependedOn<<2|n.hasRedundancy;return s.box(s.types.sdtp,i)}static stbl(e){return s.box(s.types.stbl,s.stsd(e),s.box(s.types.stts,s.STTS),s.box(s.types.stsc,s.STSC),s.box(s.types.stsz,s.STSZ),s.box(s.types.stco,s.STCO))}static avc1(e){let t=[],i=[],r,n,a;for(r=0;r<e.sps.length;r++)n=e.sps[r],a=n.byteLength,t.push(a>>>8&255),t.push(a&255),t=t.concat(Array.prototype.slice.call(n));for(r=0;r<e.pps.length;r++)n=e.pps[r],a=n.byteLength,i.push(a>>>8&255),i.push(a&255),i=i.concat(Array.prototype.slice.call(n));let o=s.box(s.types.avcC,new Uint8Array([1,t[3],t[4],t[5],255,224|e.sps.length].concat(t).concat([e.pps.length]).concat(i))),l=e.width,d=e.height,c=e.pixelRatio[0],u=e.pixelRatio[1];return s.box(s.types.avc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,l>>8&255,l&255,d>>8&255,d&255,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),o,s.box(s.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),s.box(s.types.pasp,new Uint8Array([c>>24,c>>16&255,c>>8&255,c&255,u>>24,u>>16&255,u>>8&255,u&255])))}static esds(e){let t=e.config;return new Uint8Array([0,0,0,0,3,25,0,1,0,4,17,64,21,0,0,0,0,0,0,0,0,0,0,0,5,2,...t,6,1,2])}static audioStsd(e){let t=e.samplerate||0;return new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,e.channelCount||0,0,16,0,0,0,0,t>>8&255,t&255,0,0])}static mp4a(e){return s.box(s.types.mp4a,s.audioStsd(e),s.box(s.types.esds,s.esds(e)))}static mp3(e){return s.box(s.types[".mp3"],s.audioStsd(e))}static ac3(e){return s.box(s.types["ac-3"],s.audioStsd(e),s.box(s.types.dac3,e.config))}static stsd(e){let{segmentCodec:t}=e;if(e.type==="audio"){if(t==="aac")return s.box(s.types.stsd,s.STSD,s.mp4a(e));if(t==="ac3"&&e.config)return s.box(s.types.stsd,s.STSD,s.ac3(e));if(t==="mp3"&&e.codec==="mp3")return s.box(s.types.stsd,s.STSD,s.mp3(e))}else if(e.pps&&e.sps){if(t==="avc")return s.box(s.types.stsd,s.STSD,s.avc1(e));if(t==="hevc"&&e.vps)return s.box(s.types.stsd,s.STSD,s.hvc1(e))}else throw new Error("video track missing pps or sps");throw new Error(`unsupported ${e.type} segment codec (${t}/${e.codec})`)}static tkhd(e){let t=e.id,i=(e.duration||0)*(e.timescale||0),r=e.width||0,n=e.height||0,a=Math.floor(i/(Mi+1)),o=Math.floor(i%(Mi+1));return s.box(s.types.tkhd,new Uint8Array([1,0,0,7,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,t&255,0,0,0,0,a>>24,a>>16&255,a>>8&255,a&255,o>>24,o>>16&255,o>>8&255,o&255,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,r>>8&255,r&255,0,0,n>>8&255,n&255,0,0]))}static traf(e,t){let i=s.sdtp(e),r=e.id,n=Math.floor(t/(Mi+1)),a=Math.floor(t%(Mi+1));return s.box(s.types.traf,s.box(s.types.tfhd,new Uint8Array([0,0,0,0,r>>24,r>>16&255,r>>8&255,r&255])),s.box(s.types.tfdt,new Uint8Array([1,0,0,0,n>>24,n>>16&255,n>>8&255,n&255,a>>24,a>>16&255,a>>8&255,a&255])),s.trun(e,i.length+16+20+8+16+8+8),i)}static trak(e){return e.duration=e.duration||4294967295,s.box(s.types.trak,s.tkhd(e),s.mdia(e))}static trex(e){let t=e.id;return s.box(s.types.trex,new Uint8Array([0,0,0,0,t>>24,t>>16&255,t>>8&255,t&255,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))}static trun(e,t){let i=e.samples||[],r=i.length,n=12+16*r,a=new Uint8Array(n),o,l,d,c,u,h;for(t+=8+n,a.set([e.type==="video"?1:0,0,15,1,r>>>24&255,r>>>16&255,r>>>8&255,r&255,t>>>24&255,t>>>16&255,t>>>8&255,t&255],0),o=0;o<r;o++)l=i[o],d=l.duration,c=l.size,u=l.flags,h=l.cts,a.set([d>>>24&255,d>>>16&255,d>>>8&255,d&255,c>>>24&255,c>>>16&255,c>>>8&255,c&255,u.isLeading<<2|u.dependsOn,u.isDependedOn<<6|u.hasRedundancy<<4|u.paddingValue<<1|u.isNonSync,u.degradPrio&61440,u.degradPrio&15,h>>>24&255,h>>>16&255,h>>>8&255,h&255],12+16*o);return s.box(s.types.trun,a)}static initSegment(e){s.types||s.init();let t=s.moov(e);return Dt(s.FTYP,t)}static hvc1(e){let t=e.params,i=[e.vps,e.sps,e.pps],r=4,n=new Uint8Array([1,t.general_profile_space<<6|(t.general_tier_flag?32:0)|t.general_profile_idc,t.general_profile_compatibility_flags[0],t.general_profile_compatibility_flags[1],t.general_profile_compatibility_flags[2],t.general_profile_compatibility_flags[3],t.general_constraint_indicator_flags[0],t.general_constraint_indicator_flags[1],t.general_constraint_indicator_flags[2],t.general_constraint_indicator_flags[3],t.general_constraint_indicator_flags[4],t.general_constraint_indicator_flags[5],t.general_level_idc,240|t.min_spatial_segmentation_idc>>8,255&t.min_spatial_segmentation_idc,252|t.parallelismType,252|t.chroma_format_idc,248|t.bit_depth_luma_minus8,248|t.bit_depth_chroma_minus8,0,parseInt(t.frame_rate.fps),r-1|t.temporal_id_nested<<2|t.num_temporal_layers<<3|(t.frame_rate.fixed?64:0),i.length]),a=n.length;for(let m=0;m<i.length;m+=1){a+=3;for(let p=0;p<i[m].length;p+=1)a+=2+i[m][p].length;}let o=new Uint8Array(a);o.set(n,0),a=n.length;let l=i.length-1;for(let m=0;m<i.length;m+=1){o.set(new Uint8Array([32+m|(m===l?128:0),0,i[m].length]),a),a+=3;for(let p=0;p<i[m].length;p+=1)o.set(new Uint8Array([i[m][p].length>>8,i[m][p].length&255]),a),a+=2,o.set(i[m][p],a),a+=i[m][p].length;}let d=s.box(s.types.hvcC,o),c=e.width,u=e.height,h=e.pixelRatio[0],f=e.pixelRatio[1];return s.box(s.types.hvc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,c>>8&255,c&255,u>>8&255,u&255,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),d,s.box(s.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),s.box(s.types.pasp,new Uint8Array([h>>24,h>>16&255,h>>8&255,h&255,f>>24,f>>16&255,f>>8&255,f&255])))}};Ve.types=void 0;Ve.HDLR_TYPES=void 0;Ve.STTS=void 0;Ve.STSC=void 0;Ve.STCO=void 0;Ve.STSZ=void 0;Ve.VMHD=void 0;Ve.SMHD=void 0;Ve.STSD=void 0;Ve.FTYP=void 0;Ve.DINF=void 0;var Ep=9e4;function Vu(s,e,t=1,i=false){let r=s*e*t;return i?Math.round(r):r}function Qy(s,e,t=1,i=false){return Vu(s,e,1/t,i)}function ln(s,e=false){return Vu(s,1e3,1/Ep,e)}function Xy(s,e=1){return Vu(s,Ep,1/e)}function Jm(s){let{baseTime:e,timescale:t,trackId:i}=s;return `${e/t} (${e}/${t}) trackId: ${i}`}var Zy=10*1e3,Jy=1024,eS=1152,tS=1536,Zs=null,ec=null;function eg(s,e,t,i){return {duration:e,size:t,cts:i,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:s?2:1,isNonSync:s?0:1}}}var rr=class extends ht{constructor(e,t,i,r){if(super("mp4-remuxer",r),this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.ISGenerated=false,this._initPTS=null,this._initDTS=null,this.nextVideoTs=null,this.nextAudioTs=null,this.videoSampleDuration=null,this.isAudioContiguous=false,this.isVideoContiguous=false,this.videoTrackConfig=void 0,this.observer=e,this.config=t,this.typeSupported=i,this.ISGenerated=false,Zs===null){let a=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Zs=a?parseInt(a[1]):0;}if(ec===null){let n=navigator.userAgent.match(/Safari\/(\d+)/i);ec=n?parseInt(n[1]):0;}}destroy(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null;}resetTimeStamp(e){let t=this._initPTS;(!t||!e||e.trackId!==t.trackId||e.baseTime!==t.baseTime||e.timescale!==t.timescale)&&this.log(`Reset initPTS: ${t&&Jm(t)} > ${e&&Jm(e)}`),this._initPTS=this._initDTS=e;}resetNextTimestamp(){this.log("reset next timestamp"),this.isVideoContiguous=false,this.isAudioContiguous=false;}resetInitSegment(){this.log("ISGenerated flag reset"),this.ISGenerated=false,this.videoTrackConfig=void 0;}getVideoStartPts(e){let t=false,i=e[0].pts,r=e.reduce((n,a)=>{let o=a.pts,l=o-n;return l<-4294967296&&(t=true,o=St(o,i),l=o-n),l>0?n:o},i);return t&&this.debug("PTS rollover detected"),r}remux(e,t,i,r,n,a,o,l){let d,c,u,h,f,m,p=n,E=n,v=e.pid>-1,T=t.pid>-1,S=t.samples.length,A=e.samples.length>0,b=o&&S>0||S>1;if((!v||A)&&(!T||b)||this.ISGenerated||o){if(this.ISGenerated){var I,k,R,L;let j=this.videoTrackConfig;(j&&(t.width!==j.width||t.height!==j.height||((I=t.pixelRatio)==null?void 0:I[0])!==((k=j.pixelRatio)==null?void 0:k[0])||((R=t.pixelRatio)==null?void 0:R[1])!==((L=j.pixelRatio)==null?void 0:L[1]))||!j&&b||this.nextAudioTs===null&&A)&&this.resetInitSegment();}this.ISGenerated||(u=this.generateIS(e,t,n,a));let M=this.isVideoContiguous,B=-1,H;if(b&&(B=iS(t.samples),!M&&this.config.forceKeyFrameOnDiscontinuity))if(m=true,B>0){this.warn(`Dropped ${B} out of ${S} video samples due to a missing keyframe`);let j=this.getVideoStartPts(t.samples);t.samples=t.samples.slice(B),t.dropped+=B,E+=(t.samples[0].pts-j)/t.inputTimeScale,H=E;}else B===-1&&(this.warn(`No keyframe found out of ${S} video samples`),m=false);if(this.ISGenerated){if(A&&b){let j=this.getVideoStartPts(t.samples),O=(St(e.samples[0].pts,j)-j)/t.inputTimeScale;p+=Math.max(0,O),E+=Math.max(0,-O);}if(A){if(e.samplerate||(this.warn("regenerate InitSegment as audio detected"),u=this.generateIS(e,t,n,a)),c=this.remuxAudio(e,p,this.isAudioContiguous,a,T||b||l===W.AUDIO?E:void 0),b){let j=c?c.endPTS-c.startPTS:0;t.inputTimeScale||(this.warn("regenerate InitSegment as video detected"),u=this.generateIS(e,t,n,a)),d=this.remuxVideo(t,E,M,j);}}else b&&(d=this.remuxVideo(t,E,M,0));d&&(d.firstKeyFrame=B,d.independent=B!==-1,d.firstKeyFramePTS=H);}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(i.samples.length&&(f=vp(i,n,this._initPTS,this._initDTS)),r.samples.length&&(h=Tp(r,n,this._initPTS))),{audio:c,video:d,initSegment:u,independent:m,text:h,id3:f}}computeInitPts(e,t,i,r){let n=Math.round(i*t),a=St(e,n);if(a<n+t)for(this.log(`Adjusting PTS for rollover in timeline near ${(n-a)/t} ${r}`);a<n+t;)a+=8589934592;return a-n}generateIS(e,t,i,r){let n=e.samples,a=t.samples,o=this.typeSupported,l={},d=this._initPTS,c=!d||r,u="audio/mp4",h,f,m,p=-1;if(c&&(h=f=1/0),e.config&&n.length){switch(e.timescale=e.samplerate,e.segmentCodec){case "mp3":o.mpeg?(u="audio/mpeg",e.codec=""):o.mp3&&(e.codec="mp3");break;case "ac3":e.codec="ac-3";break}l.audio={id:"audio",container:u,codec:e.codec,initSegment:e.segmentCodec==="mp3"&&o.mpeg?new Uint8Array(0):Ve.initSegment([e]),metadata:{channelCount:e.channelCount}},c&&(p=e.id,m=e.inputTimeScale,!d||m!==d.timescale?h=f=this.computeInitPts(n[0].pts,m,i,"audio"):c=false);}if(t.sps&&t.pps&&a.length){if(t.timescale=t.inputTimeScale,l.video={id:"main",container:"video/mp4",codec:t.codec,initSegment:Ve.initSegment([t]),metadata:{width:t.width,height:t.height}},c)if(p=t.id,m=t.inputTimeScale,!d||m!==d.timescale){let E=this.getVideoStartPts(a),v=St(a[0].dts,E),T=this.computeInitPts(v,m,i,"video"),S=this.computeInitPts(E,m,i,"video");f=Math.min(f,T),h=Math.min(h,S);}else c=false;this.videoTrackConfig={width:t.width,height:t.height,pixelRatio:t.pixelRatio};}if(Object.keys(l).length)return this.ISGenerated=true,c?(d&&this.warn(`Timestamps at playlist time: ${r?"":"~"}${i} ${h/m} != initPTS: ${d.baseTime/d.timescale} (${d.baseTime}/${d.timescale}) trackId: ${d.trackId}`),this.log(`Found initPTS at playlist time: ${i} offset: ${h/m} (${h}/${m}) trackId: ${p}`),this._initPTS={baseTime:h,timescale:m,trackId:p},this._initDTS={baseTime:f,timescale:m,trackId:p}):h=m=void 0,{tracks:l,initPTS:h,timescale:m,trackId:p}}remuxVideo(e,t,i,r){let n=e.inputTimeScale,a=e.samples,o=[],l=a.length,d=this._initPTS,c=d.baseTime*n/d.timescale,u=this.nextVideoTs,h=8,f=this.videoSampleDuration,m,p,E=Number.POSITIVE_INFINITY,v=Number.NEGATIVE_INFINITY,T=false;if(!i||u===null){let N=c+t*n,U=a[0].pts-St(a[0].dts,a[0].pts);Zs&&u!==null&&Math.abs(N-U-(u+c))<15e3?i=true:u=N-U-c;}let S=u+c;for(let N=0;N<l;N++){let U=a[N];U.pts=St(U.pts,S),U.dts=St(U.dts,S),U.dts<a[N>0?N-1:N].dts&&(T=true);}T&&a.sort(function(N,U){let te=N.dts-U.dts,ge=N.pts-U.pts;return te||ge}),m=a[0].dts,p=a[a.length-1].dts;let A=p-m,b=A?Math.round(A/(l-1)):f||e.inputTimeScale/30;if(i){let N=m-S,U=N>b,te=N<-1;if((U||te)&&(U?this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${ln(N,true)} ms (${N}dts) hole between fragments detected at ${t.toFixed(3)}`):this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${ln(-N,true)} ms (${N}dts) overlapping between fragments detected at ${t.toFixed(3)}`),!te||S>=a[0].pts||Zs)){m=S;let ge=a[0].pts-N;if(U)a[0].dts=m,a[0].pts=ge;else {let ie=true;for(let de=0;de<a.length&&!(a[de].dts>ge&&ie);de++){let Be=a[de].pts;if(a[de].dts-=N,a[de].pts-=N,de<a.length-1){let Fe=a[de+1].pts,tt=a[de].pts,ft=Fe<=tt,Kt=Fe<=Be;ie=ft==Kt;}}}this.log(`Video: Initial PTS/DTS adjusted: ${ln(ge,true)}/${ln(m,true)}, delta: ${ln(N,true)} ms`);}}m=Math.max(0,m);let D=0,I=0,k=m;for(let N=0;N<l;N++){let U=a[N],te=U.units,ge=te.length,ie=0;for(let de=0;de<ge;de++)ie+=te[de].data.length;I+=ie,D+=ge,U.length=ie,U.dts<k?(U.dts=k,k+=b/4|0||1):k=U.dts,E=Math.min(U.pts,E),v=Math.max(U.pts,v);}p=a[l-1].dts;let R=I+4*D+8,L;try{L=new Uint8Array(R);}catch(N){this.observer.emit(g.ERROR,g.ERROR,{type:z.MUX_ERROR,details:x.REMUX_ALLOC_ERROR,fatal:false,error:N,bytes:R,reason:`fail allocating video mdat ${R}`});return}let M=new DataView(L.buffer);M.setUint32(0,R),L.set(Ve.types.mdat,4);let B=false,H=Number.POSITIVE_INFINITY,j=Number.POSITIVE_INFINITY,K=Number.NEGATIVE_INFINITY,O=Number.NEGATIVE_INFINITY;for(let N=0;N<l;N++){let U=a[N],te=U.units,ge=0;for(let Be=0,Fe=te.length;Be<Fe;Be++){let tt=te[Be],ft=tt.data,Kt=tt.data.byteLength;M.setUint32(h,Kt),h+=4,L.set(ft,h),h+=Kt,ge+=4+Kt;}let ie;if(N<l-1)f=a[N+1].dts-U.dts,ie=a[N+1].pts-U.pts;else {let Be=this.config,Fe=N>0?U.dts-a[N-1].dts:b;if(ie=N>0?U.pts-a[N-1].pts:b,Be.stretchShortVideoTrack&&this.nextAudioTs!==null){let tt=Math.floor(Be.maxBufferHole*n),ft=(r?E+r*n:this.nextAudioTs+c)-U.pts;ft>tt?(f=ft-Fe,f<0?f=Fe:B=true,this.log(`It is approximately ${ft/90} ms to the next segment; using duration ${f/90} ms for the last video frame.`)):f=Fe;}else f=Fe;}let de=Math.round(U.pts-U.dts);H=Math.min(H,f),K=Math.max(K,f),j=Math.min(j,ie),O=Math.max(O,ie),o.push(eg(U.key,f,ge,de));}if(o.length){if(Zs){if(Zs<70){let N=o[0].flags;N.dependsOn=2,N.isNonSync=0;}}else if(ec&&O-j<K-H&&b/K<.025&&o[0].cts===0){this.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");let N=m;for(let U=0,te=o.length;U<te;U++){let ge=N+o[U].duration,ie=N+o[U].cts;if(U<te-1){let de=ge+o[U+1].cts;o[U].duration=de-ie;}else o[U].duration=U?o[U-1].duration:b;o[U].cts=0,N=ge;}}}f=B||!f?b:f;let Y=p+f;this.nextVideoTs=u=Y-c,this.videoSampleDuration=f,this.isVideoContiguous=true;let Q={data1:Ve.moof(e.sequenceNumber++,m,ye(e,{samples:o})),data2:L,startPTS:(E-c)/n,endPTS:(v+f-c)/n,startDTS:(m-c)/n,endDTS:u/n,type:"video",hasAudio:false,hasVideo:true,nb:o.length,dropped:e.dropped};return e.samples=[],e.dropped=0,Q}getSamplesPerFrame(e){switch(e.segmentCodec){case "mp3":return eS;case "ac3":return tS;default:return Jy}}remuxAudio(e,t,i,r,n){let a=e.inputTimeScale,o=e.samplerate?e.samplerate:a,l=a/o,d=this.getSamplesPerFrame(e),c=d*l,u=this._initPTS,h=e.segmentCodec==="mp3"&&this.typeSupported.mpeg,f=[],m=n!==void 0,p=e.samples,E=h?0:8,v=this.nextAudioTs||-1,T=u.baseTime*a/u.timescale,S=T+t*a;if(this.isAudioContiguous=i=i||p.length&&v>0&&(r&&Math.abs(S-(v+T))<9e3||Math.abs(St(p[0].pts,S)-(v+T))<20*c),p.forEach(function(O){O.pts=St(O.pts,S);}),!i||v<0){let O=p.length;if(p=p.filter(Y=>Y.pts>=0),O!==p.length&&this.warn(`Removed ${p.length-O} of ${O} samples (initPTS ${T} / ${a})`),!p.length)return;n===0?v=0:r&&!m?v=Math.max(0,S-T):v=p[0].pts-T;}if(e.segmentCodec==="aac"){let O=this.config.maxAudioFramesDrift;for(let Y=0,$=v+T;Y<p.length;Y++){let q=p[Y],Q=q.pts,N=Q-$,U=Math.abs(1e3*N/a);if(N<=-O*c&&m)Y===0&&(this.warn(`Audio frame @ ${(Q/a).toFixed(3)}s overlaps marker by ${Math.round(1e3*N/a)} ms.`),this.nextAudioTs=v=Q-T,$=Q);else if(N>=O*c&&U<Zy&&m){let te=Math.round(N/c);for($=Q-te*c;$<0&&te&&c;)te--,$+=c;Y===0&&(this.nextAudioTs=v=$-T),this.warn(`Injecting ${te} audio frames @ ${(($-T)/a).toFixed(3)}s due to ${Math.round(1e3*N/a)} ms gap.`);for(let ge=0;ge<te;ge++){let ie=Hc.getSilentFrame(e.parsedCodec||e.manifestCodec||e.codec,e.channelCount);ie||(this.log("Unable to get silent frame for given audio codec; duplicating last frame instead."),ie=q.unit.subarray()),p.splice(Y,0,{unit:ie,pts:$}),$+=c,Y++;}}q.pts=$,$+=c;}}let A=null,b=null,D,I=0,k=p.length;for(;k--;)I+=p[k].unit.byteLength;for(let O=0,Y=p.length;O<Y;O++){let $=p[O],q=$.unit,Q=$.pts;if(b!==null){let U=f[O-1];U.duration=Math.round((Q-b)/l);}else if(i&&e.segmentCodec==="aac"&&(Q=v+T),A=Q,I>0){I+=E;try{D=new Uint8Array(I);}catch(U){this.observer.emit(g.ERROR,g.ERROR,{type:z.MUX_ERROR,details:x.REMUX_ALLOC_ERROR,fatal:false,error:U,bytes:I,reason:`fail allocating audio mdat ${I}`});return}h||(new DataView(D.buffer).setUint32(0,I),D.set(Ve.types.mdat,4));}else return;D.set(q,E);let N=q.byteLength;E+=N,f.push(eg(true,d,N,0)),b=Q;}let R=f.length;if(!R)return;let L=f[f.length-1];v=b-T,this.nextAudioTs=v+l*L.duration;let M=h?new Uint8Array(0):Ve.moof(e.sequenceNumber++,A/l,ye({},e,{samples:f}));e.samples=[];let B=(A-T)/a,H=v/a,K={data1:M,data2:D,startPTS:B,endPTS:H,startDTS:B,endDTS:H,type:"audio",hasAudio:true,hasVideo:false,nb:R};return this.isAudioContiguous=true,K}};function St(s,e){let t;if(e===null)return s;for(e<s?t=-8589934592:t=8589934592;Math.abs(s-e)>4294967296;)s+=t;return s}function iS(s){for(let e=0;e<s.length;e++)if(s[e].key)return e;return -1}function vp(s,e,t,i){let r=s.samples.length;if(!r)return;let n=s.inputTimeScale;for(let o=0;o<r;o++){let l=s.samples[o];l.pts=St(l.pts-t.baseTime*n/t.timescale,e*n)/n,l.dts=St(l.dts-i.baseTime*n/i.timescale,e*n)/n;}let a=s.samples;return s.samples=[],{samples:a}}function Tp(s,e,t){let i=s.samples.length;if(!i)return;let r=s.inputTimeScale;for(let a=0;a<i;a++){let o=s.samples[a];o.pts=St(o.pts-t.baseTime*r/t.timescale,e*r)/r;}s.samples.sort((a,o)=>a.pts-o.pts);let n=s.samples;return s.samples=[],{samples:n}}var Kc=class extends ht{constructor(e,t,i,r){super("passthrough-remuxer",r),this.emitInitSegment=false,this.audioCodec=void 0,this.videoCodec=void 0,this.initData=void 0,this.initPTS=null,this.initTracks=void 0,this.lastEndTime=null,this.isVideoContiguous=false;}destroy(){}resetTimeStamp(e){this.lastEndTime=null;let t=this.initPTS;t&&e&&t.baseTime===e.baseTime&&t.timescale===e.timescale||(this.initPTS=e);}resetNextTimestamp(){this.isVideoContiguous=false,this.lastEndTime=null;}resetInitSegment(e,t,i,r){this.audioCodec=t,this.videoCodec=i,this.generateInitSegment(e,r),this.emitInitSegment=true;}generateInitSegment(e,t){let{audioCodec:i,videoCodec:r}=this;if(!(e!=null&&e.byteLength)){this.initTracks=void 0,this.initData=void 0;return}let{audio:n,video:a}=this.initData=kg(e);if(t)aT(e,t);else {let l=n||a;l!=null&&l.encrypted&&this.warn(`Init segment with encrypted track with has no key ("${l.codec}")!`);}n&&(i=tg(n,Se.AUDIO,this)),a&&(r=tg(a,Se.VIDEO,this));let o={};n&&a?o.audiovideo={container:"video/mp4",codec:i+","+r,supplemental:a.supplemental,encrypted:a.encrypted,initSegment:e,id:"main"}:n?o.audio={container:"audio/mp4",codec:i,encrypted:n.encrypted,initSegment:e,id:"audio"}:a?o.video={container:"video/mp4",codec:r,supplemental:a.supplemental,encrypted:a.encrypted,initSegment:e,id:"main"}:this.warn("initSegment does not contain moov or trak boxes."),this.initTracks=o;}remux(e,t,i,r,n,a){var o,l;let{initPTS:d,lastEndTime:c}=this,u={audio:void 0,video:void 0,text:r,id3:i,initSegment:void 0};G(c)||(c=this.lastEndTime=n||0);let h=t.samples;if(!h.length)return u;let f={initPTS:void 0,timescale:void 0,trackId:void 0},m=this.initData;if((o=m)!=null&&o.length||(this.generateInitSegment(h),m=this.initData),!((l=m)!=null&&l.length))return this.warn("Failed to generate initSegment."),u;this.emitInitSegment&&(f.tracks=this.initTracks,this.emitInitSegment=false);let p=lT(h,m,this),E=m.audio?p[m.audio.id]:null,v=m.video?p[m.video.id]:null,T=Io(v,1/0),S=Io(E,1/0),A=Io(v,0,true),b=Io(E,0,true),D=n,I=0,k=E&&(!v||!d&&S<T||d&&d.trackId===m.audio.id),R=k?E:v;if(R){let $=R.timescale,q=R.start-n*$,Q=k?m.audio.id:m.video.id;D=R.start/$,I=k?b-S:A-T,(a||!d)&&(sS(d,D,n,I)||$!==d.timescale)&&(d&&this.warn(`Timestamps at playlist time: ${a?"":"~"}${n} ${q/$} != initPTS: ${d.baseTime/d.timescale} (${d.baseTime}/${d.timescale}) trackId: ${d.trackId}`),this.log(`Found initPTS at playlist time: ${n} offset: ${D-n} (${q}/${$}) trackId: ${Q}`),d=null,f.initPTS=q,f.timescale=$,f.trackId=Q);}else this.warn(`No audio or video samples found for initPTS at playlist time: ${n}`);d?(f.initPTS=d.baseTime,f.timescale=d.timescale,f.trackId=d.trackId):((!f.timescale||f.trackId===void 0||f.initPTS===void 0)&&(this.warn("Could not set initPTS"),f.initPTS=D,f.timescale=1,f.trackId=-1),this.initPTS=d={baseTime:f.initPTS,timescale:f.timescale,trackId:f.trackId});let L=D-d.baseTime/d.timescale,M=L+I;I>0?this.lastEndTime=M:(this.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());let B=!!m.audio,H=!!m.video,j="";B&&(j+="audio"),H&&(j+="video");let K=(m.audio?m.audio.encrypted:false)||(m.video?m.video.encrypted:false),O={data1:h,startPTS:L,startDTS:L,endPTS:M,endDTS:M,type:j,hasAudio:B,hasVideo:H,nb:1,dropped:0,encrypted:K};u.audio=B&&!H?O:void 0,u.video=H?O:void 0;let Y=v?.sampleCount;if(Y){let $=v.keyFrameIndex,q=$!==-1;O.nb=Y,O.dropped=$===0||this.isVideoContiguous?0:q?$:Y,O.independent=q,O.firstKeyFrame=$,q&&v.keyFrameStart&&(O.firstKeyFramePTS=(v.keyFrameStart-d.baseTime)/d.timescale),this.isVideoContiguous||(u.independent=q),this.isVideoContiguous||(this.isVideoContiguous=q),O.dropped&&this.warn(`fmp4 does not start with IDR: firstIDR ${$}/${Y} dropped: ${O.dropped} start: ${O.firstKeyFramePTS||"NA"}`);}return u.initSegment=f,u.id3=vp(i,n,d,d),r.samples.length&&(u.text=Tp(r,n,d)),u}};function Io(s,e,t=false){return s?.start!==void 0?(s.start+(t?s.duration:0))/s.timescale:e}function sS(s,e,t,i){if(s===null)return true;let r=Math.max(i,1),n=e-s.baseTime/s.timescale;return Math.abs(n-t)>r}function tg(s,e,t){let i=s.codec;return i&&i.length>4?i:e===Se.AUDIO?i==="ec-3"||i==="ac-3"||i==="alac"?i:i==="fLaC"||i==="Opus"?Ho(i,false):(t.warn(`Unhandled audio codec "${i}" in mp4 MAP`),i||"mp4a"):(t.warn(`Unhandled video codec "${i}" in mp4 MAP`),i||"avc1")}var Ti;try{Ti=self.performance.now.bind(self.performance);}catch{Ti=Date.now;}var Fo=[{demux:Oc,remux:Kc},{demux:Bc,remux:rr},{demux:Mc,remux:rr},{demux:wc,remux:rr}];Fo.splice(2,0,{demux:Pc,remux:rr});var il=class{constructor(e,t,i,r,n,a){this.asyncResult=false,this.logger=void 0,this.observer=void 0,this.typeSupported=void 0,this.config=void 0,this.id=void 0,this.demuxer=void 0,this.remuxer=void 0,this.decrypter=void 0,this.probe=void 0,this.decryptionPromise=null,this.transmuxConfig=void 0,this.currentTransmuxState=void 0,this.observer=e,this.typeSupported=t,this.config=i,this.id=n,this.logger=a;}configure(e){this.transmuxConfig=e,this.decrypter&&this.decrypter.reset();}push(e,t,i,r){let n=i.transmuxing;n.executeStart=Ti();let a=new Uint8Array(e),{currentTransmuxState:o,transmuxConfig:l}=this;r&&(this.currentTransmuxState=r);let{contiguous:d,discontinuity:c,trackSwitch:u,accurateTimeOffset:h,timeOffset:f,initSegmentChange:m}=r||o,{audioCodec:p,videoCodec:E,defaultInitPts:v,duration:T,initSegmentData:S}=l,A=rS(a,t);if(A&&sr(A.method)){let k=this.getDecrypter(),R=Nu(A.method);if(k.isSync()){let L=k.softwareDecrypt(a,A.key.buffer,A.iv.buffer,R);if(i.part>-1){let B=k.flush();L=B&&B.buffer;}if(!L)return n.executeEnd=Ti(),tc(i);a=new Uint8Array(L);}else return this.asyncResult=true,this.decryptionPromise=k.webCryptoDecrypt(a,A.key.buffer,A.iv.buffer,R).then(L=>{let M=this.push(L,null,i);return this.decryptionPromise=null,M}),this.decryptionPromise}let b=this.needsProbing(c,u);if(b){let k=this.configureTransmuxer(a);if(k)return this.logger.warn(`[transmuxer] ${k.message}`),this.observer.emit(g.ERROR,g.ERROR,{type:z.MEDIA_ERROR,details:x.FRAG_PARSING_ERROR,fatal:false,error:k,reason:k.message}),n.executeEnd=Ti(),tc(i)}(c||u||m||b)&&this.resetInitSegment(S,p,E,T,t),(c||m||b)&&this.resetInitialTimestamp(v),d||this.resetContiguity();let D=this.transmux(a,A,f,h,i);this.asyncResult=_n(D);let I=this.currentTransmuxState;return I.contiguous=true,I.discontinuity=false,I.trackSwitch=false,n.executeEnd=Ti(),D}flush(e){let t=e.transmuxing;t.executeStart=Ti();let{decrypter:i,currentTransmuxState:r,decryptionPromise:n}=this;if(n)return this.asyncResult=true,n.then(()=>this.flush(e));let a=[],{timeOffset:o}=r;if(i){let u=i.flush();u&&a.push(this.push(u.buffer,null,e));}let{demuxer:l,remuxer:d}=this;if(!l||!d){t.executeEnd=Ti();let u=[tc(e)];return this.asyncResult?Promise.resolve(u):u}let c=l.flush(o);return _n(c)?(this.asyncResult=true,c.then(u=>(this.flushRemux(a,u,e),a))):(this.flushRemux(a,c,e),this.asyncResult?Promise.resolve(a):a)}flushRemux(e,t,i){let{audioTrack:r,videoTrack:n,id3Track:a,textTrack:o}=t,{accurateTimeOffset:l,timeOffset:d}=this.currentTransmuxState;this.logger.log(`[transmuxer.ts]: Flushed ${this.id} sn: ${i.sn}${i.part>-1?" part: "+i.part:""} of ${this.id===W.MAIN?"level":"track"} ${i.level}`);let c=this.remuxer.remux(r,n,a,o,d,l,true,this.id);e.push({remuxResult:c,chunkMeta:i}),i.transmuxing.executeEnd=Ti();}resetInitialTimestamp(e){let{demuxer:t,remuxer:i}=this;!t||!i||(t.resetTimeStamp(e),i.resetTimeStamp(e));}resetContiguity(){let{demuxer:e,remuxer:t}=this;!e||!t||(e.resetContiguity(),t.resetNextTimestamp());}resetInitSegment(e,t,i,r,n){let{demuxer:a,remuxer:o}=this;!a||!o||(a.resetInitSegment(e,t,i,r),o.resetInitSegment(e,t,i,n));}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0);}transmux(e,t,i,r,n){let a;return t&&t.method==="SAMPLE-AES"?a=this.transmuxSampleAes(e,t,i,r,n):a=this.transmuxUnencrypted(e,i,r,n),a}transmuxUnencrypted(e,t,i,r){let{audioTrack:n,videoTrack:a,id3Track:o,textTrack:l}=this.demuxer.demux(e,t,false,!this.config.progressive);return {remuxResult:this.remuxer.remux(n,a,o,l,t,i,false,this.id),chunkMeta:r}}transmuxSampleAes(e,t,i,r,n){return this.demuxer.demuxSampleAes(e,t,i).then(a=>({remuxResult:this.remuxer.remux(a.audioTrack,a.videoTrack,a.id3Track,a.textTrack,i,r,false,this.id),chunkMeta:n}))}configureTransmuxer(e){let{config:t,observer:i,typeSupported:r}=this,n;for(let u=0,h=Fo.length;u<h;u++){var a;if((a=Fo[u].demux)!=null&&a.probe(e,this.logger)){n=Fo[u];break}}if(!n)return new Error("Failed to find demuxer by probing fragment data");let o=this.demuxer,l=this.remuxer,d=n.remux,c=n.demux;(!l||!(l instanceof d))&&(this.remuxer=new d(i,t,r,this.logger)),(!o||!(o instanceof c))&&(this.demuxer=new c(i,t,r,this.logger),this.probe=c.probe);}needsProbing(e,t){return !this.demuxer||!this.remuxer||e||t}getDecrypter(){let e=this.decrypter;return e||(e=this.decrypter=new En(this.config)),e}};function rS(s,e){let t=null;return s.byteLength>0&&e?.key!=null&&e.iv!==null&&e.method!=null&&(t=e),t}var tc=s=>({remuxResult:{},chunkMeta:s});function _n(s){return "then"in s&&s.then instanceof Function}var Vc=class{constructor(e,t,i,r,n){this.audioCodec=void 0,this.videoCodec=void 0,this.initSegmentData=void 0,this.duration=void 0,this.defaultInitPts=void 0,this.audioCodec=e,this.videoCodec=t,this.initSegmentData=i,this.duration=r,this.defaultInitPts=n||null;}},Wc=class{constructor(e,t,i,r,n,a){this.discontinuity=void 0,this.contiguous=void 0,this.accurateTimeOffset=void 0,this.trackSwitch=void 0,this.timeOffset=void 0,this.initSegmentChange=void 0,this.discontinuity=e,this.contiguous=t,this.accurateTimeOffset=i,this.trackSwitch=r,this.timeOffset=n,this.initSegmentChange=a;}},ig=0,sl=class{constructor(e,t,i,r){this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=ig++,this.observer=void 0,this.frag=null,this.part=null,this.useWorker=void 0,this.workerContext=null,this.transmuxer=null,this.onTransmuxComplete=void 0,this.onFlush=void 0,this.onWorkerMessage=l=>{let d=l.data,c=this.hls;if(!(!c||!(d!=null&&d.event)||d.instanceNo!==this.instanceNo))switch(d.event){case "init":{var u;let h=(u=this.workerContext)==null?void 0:u.objectURL;h&&self.URL.revokeObjectURL(h);break}case "transmuxComplete":{this.handleTransmuxComplete(d.data);break}case "flush":{this.onFlush(d.data);break}case "workerLog":{c.logger[d.data.logType]&&c.logger[d.data.logType](d.data.message);break}default:{d.data=d.data||{},d.data.frag=this.frag,d.data.part=this.part,d.data.id=this.id,c.trigger(d.event,d.data);break}}},this.onWorkerError=l=>{if(!this.hls)return;let d=new Error(`${l.message} (${l.filename}:${l.lineno})`);this.hls.config.enableWorker=false,this.hls.logger.warn(`Error in "${this.id}" Web Worker, fallback to inline`),this.hls.trigger(g.ERROR,{type:z.OTHER_ERROR,details:x.INTERNAL_EXCEPTION,fatal:false,event:"demuxerWorker",error:d});};let n=e.config;this.hls=e,this.id=t,this.useWorker=!!n.enableWorker,this.onTransmuxComplete=i,this.onFlush=r;let a=(l,d)=>{d=d||{},d.frag=this.frag||void 0,l===g.ERROR&&(d=d,d.parent=this.id,d.part=this.part,this.error=d.error),this.hls.trigger(l,d);};this.observer=new Bu,this.observer.on(g.FRAG_DECRYPTED,a),this.observer.on(g.ERROR,a);let o=Tm(n.preferManagedMediaSource);if(this.useWorker&&typeof Worker<"u"){let l=this.hls.logger;if(n.workerPath||Ty()){try{n.workerPath?(l.log(`loading Web Worker ${n.workerPath} for "${t}"`),this.workerContext=Sy(n.workerPath)):(l.log(`injecting Web Worker for "${t}"`),this.workerContext=yy());let{worker:c}=this.workerContext;c.addEventListener("message",this.onWorkerMessage),c.addEventListener("error",this.onWorkerError),c.postMessage({instanceNo:this.instanceNo,cmd:"init",typeSupported:o,id:t,config:Ae(n)});}catch(c){l.warn(`Error setting up "${t}" Web Worker, fallback to inline`,c),this.terminateWorker(),this.error=null,this.transmuxer=new il(this.observer,o,n,"",t,e.logger);}return}}this.transmuxer=new il(this.observer,o,n,"",t,e.logger);}reset(){if(this.frag=null,this.part=null,this.workerContext){let e=this.instanceNo;this.instanceNo=ig++;let t=this.hls.config,i=Tm(t.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:e,typeSupported:i,id:this.id,config:Ae(t)});}}terminateWorker(){if(this.workerContext){let{worker:e}=this.workerContext;this.workerContext=null,e.removeEventListener("message",this.onWorkerMessage),e.removeEventListener("error",this.onWorkerError),Ay(this.hls.config.workerPath);}}destroy(){if(this.workerContext)this.terminateWorker(),this.onWorkerMessage=this.onWorkerError=null;else {let t=this.transmuxer;t&&(t.destroy(),this.transmuxer=null);}let e=this.observer;e&&e.removeAllListeners(),this.frag=null,this.part=null,this.observer=null,this.hls=null;}push(e,t,i,r,n,a,o,l,d,c){var u,h;d.transmuxing.start=self.performance.now();let{instanceNo:f,transmuxer:m}=this,p=a?a.start:n.start,E=n.decryptdata,v=this.frag,T=!(v&&n.cc===v.cc),S=!(v&&d.level===v.level),A=v?d.sn-v.sn:-1,b=this.part?d.part-this.part.index:-1,D=A===0&&d.id>1&&d.id===v?.stats.chunkCount,I=!S&&(A===1||A===0&&(b===1||D&&b<=0)),k=self.performance.now();(S||A||n.stats.parsing.start===0)&&(n.stats.parsing.start=k),a&&(b||!I)&&(a.stats.parsing.start=k);let R=!(v&&((u=n.initSegment)==null?void 0:u.url)===((h=v.initSegment)==null?void 0:h.url)),L=new Wc(T,I,l,S,p,R);if(!I||T||R){this.hls.logger.log(`[transmuxer-interface]: Starting new transmux session for ${n.type} sn: ${d.sn}${d.part>-1?" part: "+d.part:""} ${this.id===W.MAIN?"level":"track"}: ${d.level} id: ${d.id}
1364
+ ${t.m3u8}`)}function Xg(s,e,t=true){let i=e.startSN+e.skippedSegments-s.startSN,r=s.fragments,n=i>=0,a=0;if(n&&i<r.length)a=r[i].start;else if(n&&e.startSN===s.endSN+1)a=s.fragmentEnd;else if(n&&t)a=s.fragmentStart+i*e.levelTargetDuration;else if(!e.skippedSegments&&e.fragmentStart===0)a=s.fragmentStart;else return;Cc(e,a);}function Cc(s,e){if(e){let t=s.fragments;for(let i=s.skippedSegments;i<t.length;i++)t[i].addStart(e);s.fragmentHint&&s.fragmentHint.addStart(e);}}function Zg(s,e=1/0){let t=1e3*s.targetduration;if(s.updated){let i=s.fragments;if(i.length&&t*4>e){let n=i[i.length-1].duration*1e3;n<t&&(t=n);}}else t/=2;return Math.round(t)}function Jg(s,e,t){if(!s)return null;let i=s.fragments[e-s.startSN];return i||(i=s.fragmentHint,i&&i.sn===e)?i:e<s.startSN&&t&&t.sn===e?t:null}function jm(s,e,t){return s?ep(s.partList,e,t):null}function ep(s,e,t){if(s)for(let i=s.length;i--;){let r=s[i];if(r.index===t&&r.fragment.sn===e)return r}return null}function tp(s){s.forEach((e,t)=>{var i;(i=e.details)==null||i.fragments.forEach(r=>{r.level=t,r.initSegment&&(r.initSegment.level=t);});});}function fy(s,e){return s!==e&&e?zm(s)!==zm(e):false}function zm(s){return s.replace(/\?[^?]*$/,"")}function un(s,e){for(let i=0,r=s.length;i<r;i++){var t;if(((t=s[i])==null?void 0:t.cc)===e)return s[i]}return null}function my(s,e){return !!(s&&e.startCC<s.endCC&&e.endCC>s.startCC)}function Qm(s,e){let t=s.start+e;s.startPTS=t,s.setStart(t),s.endPTS=t+s.duration;}function ip(s,e){let t=e.fragments;for(let i=0,r=t.length;i<r;i++)Qm(t[i],s);e.fragmentHint&&Qm(e.fragmentHint,s),e.alignedSliding=true;}function gy(s,e){s&&(sp(e,s),e.alignedSliding||Zo(e,s),!e.alignedSliding&&!e.skippedSegments&&Xg(s,e,false));}function sp(s,e){if(!my(e,s))return;let t=Math.min(e.endCC,s.endCC),i=un(e.fragments,t),r=un(s.fragments,t);if(!i||!r)return;Te.log(`Aligning playlist at start of dicontinuity sequence ${t}`);let n=i.start-r.start;ip(n,s);}function Zo(s,e){if(!s.hasProgramDateTime||!e.hasProgramDateTime)return;let t=s.fragments,i=e.fragments;if(!t.length||!i.length)return;let r,n,a=Math.min(e.endCC,s.endCC);e.startCC<a&&s.startCC<a&&(r=un(i,a),n=un(t,a)),(!r||!n)&&(r=i[Math.floor(i.length/2)],n=un(t,r.cc)||t[Math.floor(t.length/2)]);let o=r.programDateTime,l=n.programDateTime;if(!o||!l)return;let d=(l-o)/1e3-(n.start-r.start);ip(d,s);}function nt(s,e,t){ut(s,e,t),s.addEventListener(e,t);}function ut(s,e,t){s.removeEventListener(e,t);}var py={toString:function(s){let e="",t=s.length;for(let i=0;i<t;i++)e+=`[${s.start(i).toFixed(3)}-${s.end(i).toFixed(3)}]`;return e}},C={STOPPED:"STOPPED",IDLE:"IDLE",KEY_LOADING:"KEY_LOADING",FRAG_LOADING:"FRAG_LOADING",FRAG_LOADING_WAITING_RETRY:"FRAG_LOADING_WAITING_RETRY",WAITING_TRACK:"WAITING_TRACK",PARSING:"PARSING",PARSED:"PARSED",ENDED:"ENDED",ERROR:"ERROR",WAITING_INIT_PTS:"WAITING_INIT_PTS",WAITING_LEVEL:"WAITING_LEVEL"},yn=class extends jo{constructor(e,t,i,r,n){super(r,e.logger),this.hls=void 0,this.fragPrevious=null,this.fragCurrent=null,this.fragmentTracker=void 0,this.transmuxer=null,this._state=C.STOPPED,this.playlistType=void 0,this.media=null,this.mediaBuffer=null,this.config=void 0,this.bitrateTest=false,this.lastCurrentTime=0,this.nextLoadPosition=0,this.startPosition=0,this.startTimeOffset=null,this.retryDate=0,this.levels=null,this.fragmentLoader=void 0,this.keyLoader=void 0,this.levelLastLoaded=null,this.startFragRequested=false,this.decrypter=void 0,this.initPTS=[],this.buffering=true,this.loadingParts=false,this.loopSn=void 0,this.onMediaSeeking=()=>{let{config:a,fragCurrent:o,media:l,mediaBuffer:d,state:c}=this,u=l?l.currentTime:0,h=re.bufferInfo(d||l,u,a.maxBufferHole),f=!h.len;if(this.log(`Media seeking to ${G(u)?u.toFixed(3):u}, state: ${c}, ${f?"out of":"in"} buffer`),this.state===C.ENDED)this.resetLoadingState();else if(o){let m=a.maxFragLookUpTolerance,p=o.start-m,E=o.start+o.duration+m;if(f||E<h.start||p>h.end){let v=u>E;(u<p||v)&&(v&&o.loader&&(this.log(`Cancelling fragment load for seek (sn: ${o.sn})`),o.abortRequests(),this.resetLoadingState()),this.fragPrevious=null);}}if(l){this.fragmentTracker.removeFragmentsInRange(u,1/0,this.playlistType,true);let m=this.lastCurrentTime;if(u>m&&(this.lastCurrentTime=u),!this.loadingParts){let p=Math.max(h.end,u),E=this.shouldLoadParts(this.getLevelDetails(),p);E&&(this.log(`LL-Part loading ON after seeking to ${u.toFixed(2)} with buffer @${p.toFixed(2)}`),this.loadingParts=E);}}this.hls.hasEnoughToStart||(this.log(`Setting ${f?"startPosition":"nextLoadPosition"} to ${u} for seek without enough to start`),this.nextLoadPosition=u,f&&(this.startPosition=u)),f&&this.state===C.IDLE&&this.tickImmediate();},this.onMediaEnded=()=>{this.log("setting startPosition to 0 because media ended"),this.startPosition=this.lastCurrentTime=0;},this.playlistType=n,this.hls=e,this.fragmentLoader=new Lc(e.config),this.keyLoader=i,this.fragmentTracker=t,this.config=e.config,this.decrypter=new En(e.config);}registerListeners(){let{hls:e}=this;e.on(g.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(g.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(g.MANIFEST_LOADING,this.onManifestLoading,this),e.on(g.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(g.ERROR,this.onError,this);}unregisterListeners(){let{hls:e}=this;e.off(g.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(g.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(g.MANIFEST_LOADING,this.onManifestLoading,this),e.off(g.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(g.ERROR,this.onError,this);}doTick(){this.onTickEnd();}onTickEnd(){}startLoad(e){}stopLoad(){if(this.state===C.STOPPED)return;this.fragmentLoader.abort(),this.keyLoader.abort(this.playlistType);let e=this.fragCurrent;e!=null&&e.loader&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.resetTransmuxer(),this.fragCurrent=null,this.fragPrevious=null,this.clearInterval(),this.clearNextTick(),this.state=C.STOPPED;}get startPositionValue(){let{nextLoadPosition:e,startPosition:t}=this;return t===-1&&e?e:t}get bufferingEnabled(){return this.buffering}pauseBuffering(){this.buffering=false;}resumeBuffering(){this.buffering=true;}get inFlightFrag(){return {frag:this.fragCurrent,state:this.state}}_streamEnded(e,t){if(t.live||!this.media)return false;let i=e.end||0,r=this.config.timelineOffset||0;if(i<=r)return false;let n=e.buffered;this.config.maxBufferHole&&n&&n.length>1&&(e=re.bufferedInfo(n,e.start,0));let a=e.nextStart;if(a&&a>r&&a<t.edge||this.media.currentTime<e.start)return false;let l=t.partList;if(l!=null&&l.length){let c=l[l.length-1];return re.isBuffered(this.media,c.start+c.duration/2)}let d=t.fragments[t.fragments.length-1].type;return this.fragmentTracker.isEndListAppended(d)}getLevelDetails(){if(this.levels&&this.levelLastLoaded!==null)return this.levelLastLoaded.details}get timelineOffset(){let e=this.config.timelineOffset;if(e){var t;return ((t=this.getLevelDetails())==null?void 0:t.appliedTimelineOffset)||e}return 0}onMediaAttached(e,t){let i=this.media=this.mediaBuffer=t.media;nt(i,"seeking",this.onMediaSeeking),nt(i,"ended",this.onMediaEnded);let r=this.config;this.levels&&r.autoStartLoad&&this.state===C.STOPPED&&this.startLoad(r.startPosition);}onMediaDetaching(e,t){let i=!!t.transferMedia,r=this.media;if(r!==null){if(r.ended&&(this.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0),ut(r,"seeking",this.onMediaSeeking),ut(r,"ended",this.onMediaEnded),this.keyLoader&&!i&&this.keyLoader.detach(),this.media=this.mediaBuffer=null,this.loopSn=void 0,i){this.resetLoadingState(),this.resetTransmuxer();return}this.loadingParts=false,this.fragmentTracker.removeAllFragments(),this.stopLoad();}}onManifestLoading(){this.initPTS=[],this.levels=this.levelLastLoaded=this.fragCurrent=null,this.lastCurrentTime=this.startPosition=0,this.startFragRequested=false;}onError(e,t){}onManifestLoaded(e,t){this.startTimeOffset=t.startTimeOffset;}onHandlerDestroying(){this.stopLoad(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),super.onHandlerDestroying(),this.hls=this.onMediaSeeking=this.onMediaEnded=null;}onHandlerDestroyed(){this.state=C.STOPPED,this.fragmentLoader&&this.fragmentLoader.destroy(),this.keyLoader&&this.keyLoader.destroy(),this.decrypter&&this.decrypter.destroy(),this.hls=this.log=this.warn=this.decrypter=this.keyLoader=this.fragmentLoader=this.fragmentTracker=null,super.onHandlerDestroyed();}loadFragment(e,t,i){this.startFragRequested=true,this._loadFragForPlayback(e,t,i);}_loadFragForPlayback(e,t,i){let r=n=>{let a=n.frag;if(this.fragContextChanged(a)){this.warn(`${a.type} sn: ${a.sn}${n.part?" part: "+n.part.index:""} of ${this.fragInfo(a,false,n.part)}) was dropped during download.`),this.fragmentTracker.removeFragment(a);return}a.stats.chunkCount++,this._handleFragmentLoadProgress(n);};this._doFragLoad(e,t,i,r).then(n=>{if(!n)return;let a=this.state,o=n.frag;if(this.fragContextChanged(o)){(a===C.FRAG_LOADING||!this.fragCurrent&&a===C.PARSING)&&(this.fragmentTracker.removeFragment(o),this.state=C.IDLE);return}"payload"in n&&(this.log(`Loaded ${o.type} sn: ${o.sn} of ${this.playlistLabel()} ${o.level}`),this.hls.trigger(g.FRAG_LOADED,n)),this._handleFragmentLoadComplete(n);}).catch(n=>{this.state===C.STOPPED||this.state===C.ERROR||(this.warn(`Frag error: ${n?.message||n}`),this.resetFragmentLoading(e));});}clearTrackerIfNeeded(e){var t;let{fragmentTracker:i}=this;if(i.getState(e)===Ke.APPENDING){let n=e.type,a=this.getFwdBufferInfo(this.mediaBuffer,n),o=Math.max(e.duration,a?a.len:this.config.maxBufferLength),l=this.backtrackFragment;((l?e.sn-l.sn:0)===1||this.reduceMaxBufferLength(o,e.duration))&&i.removeFragment(e);}else ((t=this.mediaBuffer)==null?void 0:t.buffered.length)===0?i.removeAllFragments():i.hasParts(e.type)&&(i.detectPartialFragments({frag:e,part:null,stats:e.stats,id:e.type}),i.getState(e)===Ke.PARTIAL&&i.removeFragment(e));}checkLiveUpdate(e){if(e.updated&&!e.live){let t=e.fragments[e.fragments.length-1];this.fragmentTracker.detectPartialFragments({frag:t,part:null,stats:t.stats,id:t.type});}e.fragments[0]||(e.deltaUpdateFailed=true);}waitForLive(e){let t=e.details;return t?.live&&t.type!=="EVENT"&&(this.levelLastLoaded!==e||t.expired)}flushMainBuffer(e,t,i=null){if(!(e-t))return;let r={startOffset:e,endOffset:t,type:i};this.hls.trigger(g.BUFFER_FLUSHING,r);}_loadInitSegment(e,t){this._doFragLoad(e,t).then(i=>{let r=i?.frag;if(!r||this.fragContextChanged(r)||!this.levels)throw new Error("init load aborted");return i}).then(i=>{let{hls:r}=this,{frag:n,payload:a}=i,o=n.decryptdata;if(a&&a.byteLength>0&&o!=null&&o.key&&o.iv&&sr(o.method)){let l=self.performance.now();return this.decrypter.decrypt(new Uint8Array(a),o.key.buffer,o.iv.buffer,Nu(o.method)).catch(d=>{throw r.trigger(g.ERROR,{type:z.MEDIA_ERROR,details:x.FRAG_DECRYPT_ERROR,fatal:false,error:d,reason:d.message,frag:n}),d}).then(d=>{let c=self.performance.now();return r.trigger(g.FRAG_DECRYPTED,{frag:n,payload:d,stats:{tstart:l,tdecrypt:c}}),i.payload=d,this.completeInitSegmentLoad(i)})}return this.completeInitSegmentLoad(i)}).catch(i=>{this.state===C.STOPPED||this.state===C.ERROR||(this.warn(i),this.resetFragmentLoading(e));});}completeInitSegmentLoad(e){let{levels:t}=this;if(!t)throw new Error("init load aborted, missing levels");let i=e.frag.stats;this.state!==C.STOPPED&&(this.state=C.IDLE),e.frag.data=new Uint8Array(e.payload),i.parsing.start=i.buffering.start=self.performance.now(),i.parsing.end=i.buffering.end=self.performance.now(),this.tick();}unhandledEncryptionError(e,t){var i,r;let n=e.tracks;if(n&&!t.encrypted&&((i=n.audio)!=null&&i.encrypted||(r=n.video)!=null&&r.encrypted)&&(!this.config.emeEnabled||!this.keyLoader.emeController)){let a=this.media,o=new Error(`Encrypted track with no key in ${this.fragInfo(t)} (media ${a?"attached mediaKeys: "+a.mediaKeys:"detached"})`);return this.warn(o.message),!a||a.mediaKeys?false:(this.hls.trigger(g.ERROR,{type:z.KEY_SYSTEM_ERROR,details:x.KEY_SYSTEM_NO_KEYS,fatal:false,error:o,frag:t}),this.resetTransmuxer(),true)}return false}fragContextChanged(e){let{fragCurrent:t}=this;return !e||!t||e.sn!==t.sn||e.level!==t.level}fragBufferedComplete(e,t){let i=this.mediaBuffer?this.mediaBuffer:this.media;if(this.log(`Buffered ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.fragInfo(e,false,t)} > buffer:${i?py.toString(re.getBuffered(i)):"(detached)"})`),Ue(e)){var r;if(e.type!==W.SUBTITLE){let a=e.elementaryStreams;if(!Object.keys(a).some(o=>!!a[o])){this.state=C.IDLE;return}}let n=(r=this.levels)==null?void 0:r[e.level];n!=null&&n.fragmentError&&(this.log(`Resetting level fragment error count of ${n.fragmentError} on frag buffered`),n.fragmentError=0);}this.state=C.IDLE;}_handleFragmentLoadComplete(e){let{transmuxer:t}=this;if(!t)return;let{frag:i,part:r,partsLoaded:n}=e,a=!n||n.length===0||n.some(l=>!l),o=new vn(i.level,i.sn,i.stats.chunkCount+1,0,r?r.index:-1,!a);t.flush(o);}_handleFragmentLoadProgress(e){}_doFragLoad(e,t,i=null,r){var n;this.fragCurrent=e;let a=t.details;if(!this.levels||!a)throw new Error(`frag load aborted, missing level${a?"":" detail"}s`);let o=null;if(e.encrypted&&!((n=e.decryptdata)!=null&&n.key)){if(this.log(`Loading key for ${e.sn} of [${a.startSN}-${a.endSN}], ${this.playlistLabel()} ${e.level}`),this.state=C.KEY_LOADING,this.fragCurrent=e,o=this.keyLoader.load(e).then(h=>{if(!this.fragContextChanged(h.frag))return this.hls.trigger(g.KEY_LOADED,h),this.state===C.KEY_LOADING&&(this.state=C.IDLE),h}),this.hls.trigger(g.KEY_LOADING,{frag:e}),this.fragCurrent===null)return this.log("context changed in KEY_LOADING"),Promise.resolve(null)}else e.encrypted||(o=this.keyLoader.loadClear(e,a.encryptedFragments,this.startFragRequested),o&&this.log("[eme] blocking frag load until media-keys acquired"));let l=this.fragPrevious;if(Ue(e)&&(!l||e.sn!==l.sn)){let h=this.shouldLoadParts(t.details,e.end);h!==this.loadingParts&&(this.log(`LL-Part loading ${h?"ON":"OFF"} loading sn ${l?.sn}->${e.sn}`),this.loadingParts=h);}if(i=Math.max(e.start,i||0),this.loadingParts&&Ue(e)){let h=a.partList;if(h&&r){i>a.fragmentEnd&&a.fragmentHint&&(e=a.fragmentHint);let f=this.getNextPart(h,e,i);if(f>-1){let m=h[f];e=this.fragCurrent=m.fragment,this.log(`Loading ${e.type} sn: ${e.sn} part: ${m.index} (${f}/${h.length-1}) of ${this.fragInfo(e,false,m)}) cc: ${e.cc} [${a.startSN}-${a.endSN}], target: ${parseFloat(i.toFixed(3))}`),this.nextLoadPosition=m.start+m.duration,this.state=C.FRAG_LOADING;let p;return o?p=o.then(E=>!E||this.fragContextChanged(E.frag)?null:this.doFragPartsLoad(e,m,t,r)).catch(E=>this.handleFragLoadError(E)):p=this.doFragPartsLoad(e,m,t,r).catch(E=>this.handleFragLoadError(E)),this.hls.trigger(g.FRAG_LOADING,{frag:e,part:m,targetBufferTime:i}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):p}else if(!e.url||this.loadedEndOfParts(h,i))return Promise.resolve(null)}}if(Ue(e)&&this.loadingParts){var d;this.log(`LL-Part loading OFF after next part miss @${i.toFixed(2)} Check buffer at sn: ${e.sn} loaded parts: ${(d=a.partList)==null?void 0:d.filter(h=>h.loaded).map(h=>`[${h.start}-${h.end}]`)}`),this.loadingParts=false;}else if(!e.url)return Promise.resolve(null);this.log(`Loading ${e.type} sn: ${e.sn} of ${this.fragInfo(e,false)}) cc: ${e.cc} ${"["+a.startSN+"-"+a.endSN+"]"}, target: ${parseFloat(i.toFixed(3))}`),G(e.sn)&&!this.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),this.state=C.FRAG_LOADING;let c=this.config.progressive,u;return c&&o?u=o.then(h=>!h||this.fragContextChanged(h.frag)?null:this.fragmentLoader.load(e,r)).catch(h=>this.handleFragLoadError(h)):u=Promise.all([this.fragmentLoader.load(e,c?r:void 0),o]).then(([h])=>(!c&&r&&r(h),h)).catch(h=>this.handleFragLoadError(h)),this.hls.trigger(g.FRAG_LOADING,{frag:e,targetBufferTime:i}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):u}doFragPartsLoad(e,t,i,r){return new Promise((n,a)=>{var o;let l=[],d=(o=i.details)==null?void 0:o.partList,c=u=>{this.fragmentLoader.loadPart(e,u,r).then(h=>{l[u.index]=h;let f=h.part;this.hls.trigger(g.FRAG_LOADED,h);let m=jm(i.details,e.sn,u.index+1)||ep(d,e.sn,u.index+1);if(m)c(m);else return n({frag:e,part:f,partsLoaded:l})}).catch(a);};c(t);})}handleFragLoadError(e){if("data"in e){let t=e.data;t.frag&&t.details===x.INTERNAL_ABORTED?this.handleFragLoadAborted(t.frag,t.part):t.frag&&t.type===z.KEY_SYSTEM_ERROR?(t.frag.abortRequests(),this.resetStartWhenNotLoaded(),this.resetFragmentLoading(t.frag)):this.hls.trigger(g.ERROR,t);}else this.hls.trigger(g.ERROR,{type:z.OTHER_ERROR,details:x.INTERNAL_EXCEPTION,err:e,error:e,fatal:true});return null}_handleTransmuxerFlush(e){let t=this.getCurrentContext(e);if(!t||this.state!==C.PARSING){!this.fragCurrent&&this.state!==C.STOPPED&&this.state!==C.ERROR&&(this.state=C.IDLE);return}let{frag:i,part:r,level:n}=t,a=self.performance.now();i.stats.parsing.end=a,r&&(r.stats.parsing.end=a);let o=this.getLevelDetails(),d=o&&i.sn>o.endSN||this.shouldLoadParts(o,i.end);d!==this.loadingParts&&(this.log(`LL-Part loading ${d?"ON":"OFF"} after parsing segment ending @${i.end.toFixed(2)}`),this.loadingParts=d),this.updateLevelTiming(i,r,n,e.partial);}shouldLoadParts(e,t){if(this.config.lowLatencyMode){if(!e)return this.loadingParts;if(e.partList){var i;let n=e.partList[0];if(n.fragment.type===W.SUBTITLE)return false;let a=n.end+(((i=e.fragmentHint)==null?void 0:i.duration)||0);if(t>=a){var r;if((this.hls.hasEnoughToStart?((r=this.media)==null?void 0:r.currentTime)||this.lastCurrentTime:this.getLoadPosition())>n.start-n.fragment.duration)return true}}}return false}getCurrentContext(e){let{levels:t,fragCurrent:i}=this,{level:r,sn:n,part:a}=e;if(!(t!=null&&t[r]))return this.warn(`Levels object was unset while buffering fragment ${n} of ${this.playlistLabel()} ${r}. The current chunk will not be buffered.`),null;let o=t[r],l=o.details,d=a>-1?jm(l,n,a):null,c=d?d.fragment:Jg(l,n,i);return c?(i&&i!==c&&(c.stats=i.stats),{frag:c,part:d,level:o}):null}bufferFragmentData(e,t,i,r,n){if(this.state!==C.PARSING)return;let{data1:a,data2:o}=e,l=a;if(o&&(l=Dt(a,o)),!l.length)return;let d=this.initPTS[t.cc],c=d?-d.baseTime/d.timescale:void 0,u={type:e.type,frag:t,part:i,chunkMeta:r,offset:c,parent:t.type,data:l};if(this.hls.trigger(g.BUFFER_APPENDING,u),e.dropped&&e.independent&&!i){if(n)return;this.flushBufferGap(t);}}flushBufferGap(e){let t=this.media;if(!t)return;if(!re.isBuffered(t,t.currentTime)){this.flushMainBuffer(0,e.start);return}let i=t.currentTime,r=re.bufferInfo(t,i,0),n=e.duration,a=Math.min(this.config.maxFragLookUpTolerance*2,n*.25),o=Math.max(Math.min(e.start-a,r.end-a),i+a);e.start-o>a&&this.flushMainBuffer(o,e.start);}getFwdBufferInfo(e,t){var i;let r=this.getLoadPosition();if(!G(r))return null;let a=this.lastCurrentTime>r||(i=this.media)!=null&&i.paused?0:this.config.maxBufferHole;return this.getFwdBufferInfoAtPos(e,r,t,a)}getFwdBufferInfoAtPos(e,t,i,r){let n=re.bufferInfo(e,t,r);if(n.len===0&&n.nextStart!==void 0){let a=this.fragmentTracker.getBufferedFrag(t,i);if(a&&(n.nextStart<=a.end||a.gap)){let o=Math.max(Math.min(n.nextStart,a.end)-t,r);return re.bufferInfo(e,t,o)}}return n}getMaxBufferLength(e){let{config:t}=this,i;return e?i=Math.max(8*t.maxBufferSize/e,t.maxBufferLength):i=t.maxBufferLength,Math.min(i,t.maxMaxBufferLength)}reduceMaxBufferLength(e,t){let i=this.config,r=Math.max(Math.min(e-t,i.maxBufferLength),t),n=Math.max(e-t*3,i.maxMaxBufferLength/2,r);return n>=r?(i.maxMaxBufferLength=n,this.warn(`Reduce max buffer length to ${n}s`),true):false}getAppendedFrag(e,t=W.MAIN){let i=this.fragmentTracker?this.fragmentTracker.getAppendedFrag(e,t):null;return i&&"fragment"in i?i.fragment:i}getNextFragment(e,t){let i=t.fragments,r=i.length;if(!r)return null;let{config:n}=this,a=i[0].start,o=n.lowLatencyMode&&!!t.partList,l=null;if(t.live){let u=n.initialLiveManifestSize;if(r<u)return this.warn(`Not enough fragments to start playback (have: ${r}, need: ${u})`),null;if(!t.PTSKnown&&!this.startFragRequested&&this.startPosition===-1||e<a){var d;o&&!this.loadingParts&&(this.log("LL-Part loading ON for initial live fragment"),this.loadingParts=true),l=this.getInitialLiveFragment(t);let h=this.hls.startPosition,f=this.hls.liveSyncPosition,m=l?(h!==-1&&h>=a?h:f)||l.start:e;this.log(`Setting startPosition to ${m} to match start frag at live edge. mainStart: ${h} liveSyncPosition: ${f} frag.start: ${(d=l)==null?void 0:d.start}`),this.startPosition=this.nextLoadPosition=m;}}else e<=a&&(l=i[0]);if(!l){let u=this.loadingParts?t.partEnd:t.fragmentEnd;l=this.getFragmentAtPosition(e,u,t);}let c=this.filterReplacedPrimary(l,t);if(!c&&l){let u=l.sn-t.startSN;c=this.filterReplacedPrimary(i[u+1]||null,t);}return this.mapToInitFragWhenRequired(c)}isLoopLoading(e,t){let i=this.fragmentTracker.getState(e);return (i===Ke.OK||i===Ke.PARTIAL&&!!e.gap)&&this.nextLoadPosition>t}getNextFragmentLoopLoading(e,t,i,r,n){let a=null;if(e.gap&&(a=this.getNextFragment(this.nextLoadPosition,t),a&&!a.gap&&i.nextStart)){let o=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,i.nextStart,r,0);if(o!==null&&i.len+o.len>=n){let l=a.sn;return this.loopSn!==l&&(this.log(`buffer full after gaps in "${r}" playlist starting at sn: ${l}`),this.loopSn=l),null}}return this.loopSn=void 0,a}get primaryPrefetch(){if(Xm(this.config)){var e;if((e=this.hls.interstitialsManager)==null||(e=e.playingItem)==null?void 0:e.event)return true}return false}filterReplacedPrimary(e,t){if(!e)return e;if(Xm(this.config)&&e.type!==W.SUBTITLE){let i=this.hls.interstitialsManager,r=i?.bufferingItem;if(r){let a=r.event;if(a){if(a.appendInPlace||Math.abs(e.start-r.start)>1||r.start===0)return null}else if(e.end<=r.start&&t?.live===false||e.start>r.end&&r.nextEvent&&(r.nextEvent.appendInPlace||e.start-r.end>1))return null}let n=i?.playerQueue;if(n)for(let a=n.length;a--;){let o=n[a].interstitial;if(o.appendInPlace&&e.start>=o.startTime&&e.end<=o.resumeTime)return null}}return e}mapToInitFragWhenRequired(e){return e!=null&&e.initSegment&&!e.initSegment.data&&!this.bitrateTest?e.initSegment:e}getNextPart(e,t,i){let r=-1,n=false,a=true;for(let o=0,l=e.length;o<l;o++){let d=e[o];if(a=a&&!d.independent,r>-1&&i<d.start)break;let c=d.loaded;c?r=-1:(n||(d.independent||a)&&d.fragment===t)&&(d.fragment!==t&&this.warn(`Need buffer at ${i} but next unloaded part starts at ${d.start}`),r=o),n=c;}return r}loadedEndOfParts(e,t){let i;for(let r=e.length;r--;){if(i=e[r],!i.loaded)return false;if(t>i.start)return true}return false}getInitialLiveFragment(e){let t=e.fragments,i=this.fragPrevious,r=null;if(i){if(e.hasProgramDateTime&&(this.log(`Live playlist, switching playlist, load frag with same PDT: ${i.programDateTime}`),r=BT(t,i.endProgramDateTime,this.config.maxFragLookUpTolerance)),!r){let n=i.sn+1;if(n>=e.startSN&&n<=e.endSN){let a=t[n-e.startSN];i.cc===a.cc&&(r=a,this.log(`Live playlist, switching playlist, load frag with next SN: ${r.sn}`));}r||(r=Gg(e,i.cc,i.end),r&&this.log(`Live playlist, switching playlist, load frag with same CC: ${r.sn}`));}}else {let n=this.hls.liveSyncPosition;n!==null&&(r=this.getFragmentAtPosition(n,this.bitrateTest?e.fragmentEnd:e.edge,e));}return r}getFragmentAtPosition(e,t,i){let{config:r}=this,{fragPrevious:n}=this,{fragments:a,endSN:o}=i,{fragmentHint:l}=i,{maxFragLookUpTolerance:d}=r,c=i.partList,u=!!(this.loadingParts&&c!=null&&c.length&&l);u&&!this.bitrateTest&&c[c.length-1].fragment.sn===l.sn&&(a=a.concat(l),o=l.sn);let h;if(e<t){var f;let p=e<this.lastCurrentTime||e>t-d||(f=this.media)!=null&&f.paused||!this.startFragRequested?0:d;h=cs(n,a,e,p);}else h=a[a.length-1];if(h){let m=h.sn-i.startSN,p=this.fragmentTracker.getState(h);if((p===Ke.OK||p===Ke.PARTIAL&&h.gap)&&(n=h),n&&h.sn===n.sn&&(!u||c[0].fragment.sn>h.sn||!i.live)&&h.level===n.level){let v=a[m+1];h.sn<o&&this.fragmentTracker.getState(v)!==Ke.OK?h=v:h=null;}}return h}alignPlaylists(e,t,i){let r=e.fragments.length;if(!r)return this.warn("No fragments in live playlist"),0;let n=e.fragmentStart,a=!t,o=e.alignedSliding&&G(n);if(a||!o&&!n){gy(i,e);let l=e.fragmentStart;return this.log(`Live playlist sliding: ${l.toFixed(2)} start-sn: ${t?t.startSN:"na"}->${e.startSN} fragments: ${r}`),l}return n}waitForCdnTuneIn(e){return e.live&&e.canBlockReload&&e.partTarget&&e.tuneInGoal>Math.max(e.partHoldBack,e.partTarget*3)}setStartPosition(e,t){let i=this.startPosition;i<t&&(i=-1);let r=this.timelineOffset;if(i===-1){let n=this.startTimeOffset!==null,a=n?this.startTimeOffset:e.startTimeOffset;a!==null&&G(a)?(i=t+a,a<0&&(i+=e.edge),i=Math.min(Math.max(t,i),t+e.totalduration),this.log(`Setting startPosition to ${i} for start time offset ${a} found in ${n?"multivariant":"media"} playlist`),this.startPosition=i):e.live?(i=this.hls.liveSyncPosition||t,this.log(`Setting startPosition to -1 to start at live edge ${i}`),this.startPosition=-1):(this.log("setting startPosition to 0 by default"),this.startPosition=i=0),this.lastCurrentTime=i+r;}this.nextLoadPosition=i+r;}getLoadPosition(){var e;let{media:t}=this,i=0;return (e=this.hls)!=null&&e.hasEnoughToStart&&t?i=t.currentTime:this.nextLoadPosition>=0&&(i=this.nextLoadPosition),i}handleFragLoadAborted(e,t){this.transmuxer&&e.type===this.playlistType&&Ue(e)&&e.stats.aborted&&(this.log(`Fragment ${e.sn}${t?" part "+t.index:""} of ${this.playlistLabel()} ${e.level} was aborted`),this.resetFragmentLoading(e));}resetFragmentLoading(e){(!this.fragCurrent||!this.fragContextChanged(e)&&this.state!==C.FRAG_LOADING_WAITING_RETRY)&&(this.state=C.IDLE);}onFragmentOrKeyLoadError(e,t){var i;if(t.chunkMeta&&!t.frag){let v=this.getCurrentContext(t.chunkMeta);v&&(t.frag=v.frag);}let r=t.frag;if(!r||r.type!==e||!this.levels)return;if(this.fragContextChanged(r)){var n;this.warn(`Frag load error must match current frag to retry ${r.url} > ${(n=this.fragCurrent)==null?void 0:n.url}`);return}let a=t.details===x.FRAG_GAP;a&&this.fragmentTracker.fragBuffered(r,true);let o=t.errorAction;if(!o){this.state=C.ERROR;return}let{action:l,flags:d,retryCount:c=0,retryConfig:u}=o,h=!!u,f=h&&l===ze.RetryRequest,m=h&&!o.resolved&&d===yt.MoveAllAlternatesMatchingHost,p=(i=this.hls.latestLevelDetails)==null?void 0:i.live;if(!f&&m&&Ue(r)&&!r.endList&&p&&!Kg(t))this.resetFragmentErrors(e),this.treatAsGap(r),o.resolved=true;else if((f||m)&&c<u.maxNumRetry){var E;let v=yc((E=t.response)==null?void 0:E.code),T=Fu(u,c);if(this.resetStartWhenNotLoaded(),this.retryDate=self.performance.now()+T,this.state=C.FRAG_LOADING_WAITING_RETRY,o.resolved=true,v){this.log("Waiting for connection (offline)"),this.retryDate=1/0,t.reason="offline";return}this.warn(`Fragment ${r.sn} of ${e} ${r.level} errored with ${t.details}, retrying loading ${c+1}/${u.maxNumRetry} in ${T}ms`);}else if(u)if(this.resetFragmentErrors(e),c<u.maxNumRetry)!a&&l!==ze.RemoveAlternatePermanently&&(o.resolved=true);else {this.warn(`${t.details} reached or exceeded max retry (${c})`);return}else l===ze.SendAlternateToPenaltyBox?this.state=C.WAITING_LEVEL:this.state=C.ERROR;this.tickImmediate();}checkRetryDate(){let e=self.performance.now(),t=this.retryDate,i=t===1/0;(!t||e>=t||i&&!yc(0))&&(i&&this.log("Connection restored (online)"),this.resetStartWhenNotLoaded(),this.state=C.IDLE);}reduceLengthAndFlushBuffer(e){if(this.state===C.PARSING||this.state===C.PARSED){let t=e.frag,i=e.parent,r=this.getFwdBufferInfo(this.mediaBuffer,i),n=r&&r.len>.5;n&&this.reduceMaxBufferLength(r.len,t?.duration||10);let a=!n;return a&&this.warn(`Buffer full error while media.currentTime (${this.getLoadPosition()}) is not buffered, flush ${i} buffer`),t&&(this.fragmentTracker.removeFragment(t),this.nextLoadPosition=t.start),this.resetLoadingState(),a}return false}resetFragmentErrors(e){e===W.AUDIO&&(this.fragCurrent=null),this.hls.hasEnoughToStart||(this.startFragRequested=false),this.state!==C.STOPPED&&(this.state=C.IDLE);}afterBufferFlushed(e,t,i){if(!e)return;let r=re.getBuffered(e);this.fragmentTracker.detectEvictedFragments(t,r,i),this.state===C.ENDED&&this.resetLoadingState();}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state!==C.STOPPED&&(this.state=C.IDLE);}resetStartWhenNotLoaded(){if(!this.hls.hasEnoughToStart){this.startFragRequested=false;let e=this.levelLastLoaded,t=e?e.details:null;t!=null&&t.live?(this.log("resetting startPosition for live start"),this.startPosition=-1,this.setStartPosition(t,t.fragmentStart),this.resetLoadingState()):this.nextLoadPosition=this.startPosition;}}resetWhenMissingContext(e){this.log(`Loading context changed while buffering sn ${e.sn} of ${this.playlistLabel()} ${e.level===-1?"<removed>":e.level}. This chunk will not be buffered.`),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(),this.resetLoadingState();}removeUnbufferedFrags(e=0){this.fragmentTracker.removeFragmentsInRange(e,1/0,this.playlistType,false,true);}updateLevelTiming(e,t,i,r){let n=i.details;if(!n){this.warn("level.details undefined");return}if(!Object.keys(e.elementaryStreams).reduce((l,d)=>{let c=e.elementaryStreams[d];if(c){let u=c.endPTS-c.startPTS;if(u<=0)return this.warn(`Could not parse fragment ${e.sn} ${d} duration reliably (${u})`),l||false;let h=r?0:Qg(n,e,c.startPTS,c.endPTS,c.startDTS,c.endDTS,this);return this.hls.trigger(g.LEVEL_PTS_UPDATED,{details:n,level:i,drift:h,type:d,frag:e,start:c.startPTS,end:c.endPTS}),true}return l},false)){var o;if(i.fragmentError===0&&this.treatAsGap(e,i),((o=this.transmuxer)==null?void 0:o.error)===null){let l=new Error(`Found no media in fragment ${e.sn} of ${this.playlistLabel()} ${e.level} resetting transmuxer to fallback to playlist timing`);if(this.warn(l.message),this.hls.trigger(g.ERROR,{type:z.MEDIA_ERROR,details:x.FRAG_PARSING_ERROR,fatal:false,error:l,frag:e,reason:`Found no media in msn ${e.sn} of ${this.playlistLabel()} "${i.url}"`}),!this.hls)return;this.resetTransmuxer();}}this.state=C.PARSED,this.log(`Parsed ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.fragInfo(e,false,t)})`),this.hls.trigger(g.FRAG_PARSED,{frag:e,part:t});}playlistLabel(){return this.playlistType===W.MAIN?"level":"track"}fragInfo(e,t=true,i){var r,n;return `${this.playlistLabel()} ${e.level} (${i?"part":"frag"}:[${((r=t&&!i?e.startPTS:(i||e).start)!=null?r:NaN).toFixed(3)}-${((n=t&&!i?e.endPTS:(i||e).end)!=null?n:NaN).toFixed(3)}]${i&&e.type==="main"?"INDEPENDENT="+(i.independent?"YES":"NO"):""}`}treatAsGap(e,t){t&&t.fragmentError++,e.gap=true,this.fragmentTracker.removeFragment(e),this.fragmentTracker.fragBuffered(e,true);}resetTransmuxer(){var e;(e=this.transmuxer)==null||e.reset();}recoverWorkerError(e){e.event==="demuxerWorker"&&(this.fragmentTracker.removeAllFragments(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),this.resetStartWhenNotLoaded(),this.resetLoadingState());}set state(e){let t=this._state;t!==e&&(this._state=e,this.log(`${t}->${e}`));}get state(){return this._state}};function Xm(s){return !!s.interstitialsController&&s.enableInterstitialPlayback!==false}var Jo=class{constructor(){this.chunks=[],this.dataLength=0;}push(e){this.chunks.push(e),this.dataLength+=e.length;}flush(){let{chunks:e,dataLength:t}=this,i;if(e.length)e.length===1?i=e[0]:i=Ey(e,t);else return new Uint8Array(0);return this.reset(),i}reset(){this.chunks.length=0,this.dataLength=0;}};function Ey(s,e){let t=new Uint8Array(e),i=0;for(let r=0;r<s.length;r++){let n=s[r];t.set(n,i),i+=n.length;}return t}var Xd={exports:{}},Zm;function vy(){return Zm||(Zm=1,function(s){var e=Object.prototype.hasOwnProperty,t="~";function i(){}Object.create&&(i.prototype=Object.create(null),new i().__proto__||(t=false));function r(l,d,c){this.fn=l,this.context=d,this.once=c||false;}function n(l,d,c,u,h){if(typeof c!="function")throw new TypeError("The listener must be a function");var f=new r(c,u||l,h),m=t?t+d:d;return l._events[m]?l._events[m].fn?l._events[m]=[l._events[m],f]:l._events[m].push(f):(l._events[m]=f,l._eventsCount++),l}function a(l,d){--l._eventsCount===0?l._events=new i:delete l._events[d];}function o(){this._events=new i,this._eventsCount=0;}o.prototype.eventNames=function(){var d=[],c,u;if(this._eventsCount===0)return d;for(u in c=this._events)e.call(c,u)&&d.push(t?u.slice(1):u);return Object.getOwnPropertySymbols?d.concat(Object.getOwnPropertySymbols(c)):d},o.prototype.listeners=function(d){var c=t?t+d:d,u=this._events[c];if(!u)return [];if(u.fn)return [u.fn];for(var h=0,f=u.length,m=new Array(f);h<f;h++)m[h]=u[h].fn;return m},o.prototype.listenerCount=function(d){var c=t?t+d:d,u=this._events[c];return u?u.fn?1:u.length:0},o.prototype.emit=function(d,c,u,h,f,m){var p=t?t+d:d;if(!this._events[p])return false;var E=this._events[p],v=arguments.length,T,S;if(E.fn){switch(E.once&&this.removeListener(d,E.fn,void 0,true),v){case 1:return E.fn.call(E.context),true;case 2:return E.fn.call(E.context,c),true;case 3:return E.fn.call(E.context,c,u),true;case 4:return E.fn.call(E.context,c,u,h),true;case 5:return E.fn.call(E.context,c,u,h,f),true;case 6:return E.fn.call(E.context,c,u,h,f,m),true}for(S=1,T=new Array(v-1);S<v;S++)T[S-1]=arguments[S];E.fn.apply(E.context,T);}else {var A=E.length,b;for(S=0;S<A;S++)switch(E[S].once&&this.removeListener(d,E[S].fn,void 0,true),v){case 1:E[S].fn.call(E[S].context);break;case 2:E[S].fn.call(E[S].context,c);break;case 3:E[S].fn.call(E[S].context,c,u);break;case 4:E[S].fn.call(E[S].context,c,u,h);break;default:if(!T)for(b=1,T=new Array(v-1);b<v;b++)T[b-1]=arguments[b];E[S].fn.apply(E[S].context,T);}}return true},o.prototype.on=function(d,c,u){return n(this,d,c,u,false)},o.prototype.once=function(d,c,u){return n(this,d,c,u,true)},o.prototype.removeListener=function(d,c,u,h){var f=t?t+d:d;if(!this._events[f])return this;if(!c)return a(this,f),this;var m=this._events[f];if(m.fn)m.fn===c&&(!h||m.once)&&(!u||m.context===u)&&a(this,f);else {for(var p=0,E=[],v=m.length;p<v;p++)(m[p].fn!==c||h&&!m[p].once||u&&m[p].context!==u)&&E.push(m[p]);E.length?this._events[f]=E.length===1?E[0]:E:a(this,f);}return this},o.prototype.removeAllListeners=function(d){var c;return d?(c=t?t+d:d,this._events[c]&&a(this,c)):(this._events=new i,this._eventsCount=0),this},o.prototype.off=o.prototype.removeListener,o.prototype.addListener=o.prototype.on,o.prefixed=t,o.EventEmitter=o,s.exports=o;}(Xd)),Xd.exports}var Ty=vy(),Bu=Jv(Ty),Sn="1.6.13",or={};function yy(){return typeof __HLS_WORKER_BUNDLE__=="function"}function Sy(){let s=or[Sn];if(s)return s.clientCount++,s;let e=new self.Blob([`var exports={};var module={exports:exports};function define(f){f()};define.amd=true;(${__HLS_WORKER_BUNDLE__.toString()})(true);`],{type:"text/javascript"}),t=self.URL.createObjectURL(e),r={worker:new self.Worker(t),objectURL:t,clientCount:1};return or[Sn]=r,r}function Ay(s){let e=or[s];if(e)return e.clientCount++,e;let t=new self.URL(s,self.location.href).href,r={worker:new self.Worker(t),scriptURL:t,clientCount:1};return or[s]=r,r}function by(s){let e=or[s||Sn];if(e&&e.clientCount--===1){let{worker:i,objectURL:r}=e;delete or[s||Sn],r&&self.URL.revokeObjectURL(r),i.terminate();}}function rp(s,e){return e+10<=s.length&&s[e]===51&&s[e+1]===68&&s[e+2]===73&&s[e+3]<255&&s[e+4]<255&&s[e+6]<128&&s[e+7]<128&&s[e+8]<128&&s[e+9]<128}function $u(s,e){return e+10<=s.length&&s[e]===73&&s[e+1]===68&&s[e+2]===51&&s[e+3]<255&&s[e+4]<255&&s[e+6]<128&&s[e+7]<128&&s[e+8]<128&&s[e+9]<128}function fl(s,e){let t=0;return t=(s[e]&127)<<21,t|=(s[e+1]&127)<<14,t|=(s[e+2]&127)<<7,t|=s[e+3]&127,t}function An(s,e){let t=e,i=0;for(;$u(s,e);){i+=10;let r=fl(s,e+6);i+=r,rp(s,e+10)&&(i+=10),e+=i;}if(i>0)return s.subarray(t,t+i)}function _y(s,e,t,i){let r=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],n=e[t+2],a=n>>2&15;if(a>12){let f=new Error(`invalid ADTS sampling index:${a}`);s.emit(g.ERROR,g.ERROR,{type:z.MEDIA_ERROR,details:x.FRAG_PARSING_ERROR,fatal:true,error:f,reason:f.message});return}let o=(n>>6&3)+1,l=e[t+3]>>6&3|(n&1)<<2,d="mp4a.40."+o,c=r[a],u=a;(o===5||o===29)&&(u-=3);let h=[o<<3|(u&14)>>1,(u&1)<<7|l<<3];return Te.log(`manifest codec:${i}, parsed codec:${d}, channels:${l}, rate:${c} (ADTS object type:${o} sampling index:${a})`),{config:h,samplerate:c,channelCount:l,codec:d,parsedCodec:d,manifestCodec:i}}function np(s,e){return s[e]===255&&(s[e+1]&246)===240}function ap(s,e){return s[e+1]&1?7:9}function Gu(s,e){return (s[e+3]&3)<<11|s[e+4]<<3|(s[e+5]&224)>>>5}function Iy(s,e){return e+5<s.length}function el(s,e){return e+1<s.length&&np(s,e)}function Ly(s,e){return Iy(s,e)&&np(s,e)&&Gu(s,e)<=s.length-e}function xy(s,e){if(el(s,e)){let t=ap(s,e);if(e+t>=s.length)return false;let i=Gu(s,e);if(i<=t)return false;let r=e+i;return r===s.length||el(s,r)}return false}function op(s,e,t,i,r){if(!s.samplerate){let n=_y(e,t,i,r);if(!n)return;ye(s,n);}}function lp(s){return 1024*9e4/s}function Ry(s,e){let t=ap(s,e);if(e+t<=s.length){let i=Gu(s,e)-t;if(i>0)return {headerLength:t,frameLength:i}}}function dp(s,e,t,i,r){let n=lp(s.samplerate),a=i+r*n,o=Ry(e,t),l;if(o){let{frameLength:u,headerLength:h}=o,f=h+u,m=Math.max(0,t+f-e.length);m?(l=new Uint8Array(f-h),l.set(e.subarray(t+h,e.length),0)):l=e.subarray(t+h,t+f);let p={unit:l,pts:a};return m||s.samples.push(p),{sample:p,length:f,missing:m}}let d=e.length-t;return l=new Uint8Array(d),l.set(e.subarray(t,e.length),0),{sample:{unit:l,pts:a},length:d,missing:-1}}function ky(s,e){return $u(s,e)&&fl(s,e+6)+10<=s.length-e}function Dy(s){return s instanceof ArrayBuffer?s:s.byteOffset==0&&s.byteLength==s.buffer.byteLength?s.buffer:new Uint8Array(s).buffer}function Zd(s,e=0,t=1/0){return Cy(s,e,t,Uint8Array)}function Cy(s,e,t,i){let r=My(s),n=1;"BYTES_PER_ELEMENT"in i&&(n=i.BYTES_PER_ELEMENT);let a=Py(s)?s.byteOffset:0,o=(a+s.byteLength)/n,l=(a+e)/n,d=Math.floor(Math.max(0,Math.min(l,o))),c=Math.floor(Math.min(d+Math.max(t,0),o));return new i(r,d,c-d)}function My(s){return s instanceof ArrayBuffer?s:s.buffer}function Py(s){return s&&s.buffer instanceof ArrayBuffer&&s.byteLength!==void 0&&s.byteOffset!==void 0}function wy(s){let e={key:s.type,description:"",data:"",mimeType:null,pictureType:null},t=3;if(s.size<2)return;if(s.data[0]!==t){console.log("Ignore frame with unrecognized character encoding");return}let i=s.data.subarray(1).indexOf(0);if(i===-1)return;let r=bt(Zd(s.data,1,i)),n=s.data[2+i],a=s.data.subarray(3+i).indexOf(0);if(a===-1)return;let o=bt(Zd(s.data,3+i,a)),l;return r==="-->"?l=bt(Zd(s.data,4+i+a)):l=Dy(s.data.subarray(4+i+a)),e.mimeType=r,e.pictureType=n,e.description=o,e.data=l,e}function Oy(s){if(s.size<2)return;let e=bt(s.data,true),t=new Uint8Array(s.data.subarray(e.length+1));return {key:s.type,info:e,data:t.buffer}}function Fy(s){if(s.size<2)return;if(s.type==="TXXX"){let t=1,i=bt(s.data.subarray(t),true);t+=i.length+1;let r=bt(s.data.subarray(t));return {key:s.type,info:i,data:r}}let e=bt(s.data.subarray(1));return {key:s.type,info:"",data:e}}function Ny(s){if(s.type==="WXXX"){if(s.size<2)return;let t=1,i=bt(s.data.subarray(t),true);t+=i.length+1;let r=bt(s.data.subarray(t));return {key:s.type,info:i,data:r}}let e=bt(s.data);return {key:s.type,info:"",data:e}}function Uy(s){return s.type==="PRIV"?Oy(s):s.type[0]==="W"?Ny(s):s.type==="APIC"?wy(s):Fy(s)}function By(s){let e=String.fromCharCode(s[0],s[1],s[2],s[3]),t=fl(s,4),i=10;return {type:e,size:t,data:s.subarray(i,i+t)}}var bo=10,$y=10;function cp(s){let e=0,t=[];for(;$u(s,e);){let i=fl(s,e+6);s[e+5]>>6&1&&(e+=bo),e+=bo;let r=e+i;for(;e+$y<r;){let n=By(s.subarray(e)),a=Uy(n);a&&t.push(a),e+=n.size+bo;}rp(s,e)&&(e+=bo);}return t}function up(s){return s&&s.key==="PRIV"&&s.info==="com.apple.streaming.transportStreamTimestamp"}function Gy(s){if(s.data.byteLength===8){let e=new Uint8Array(s.data),t=e[3]&1,i=(e[4]<<23)+(e[5]<<15)+(e[6]<<7)+e[7];return i/=45,t&&(i+=4772185884e-2),Math.round(i)}}function Hu(s){let e=cp(s);for(let t=0;t<e.length;t++){let i=e[t];if(up(i))return Gy(i)}}var At=function(s){return s.audioId3="org.id3",s.dateRange="com.apple.quicktime.HLS",s.emsg="https://aomedia.org/emsg/ID3",s.misbklv="urn:misb:KLV:bin:1910.1",s}({});function li(s="",e=9e4){return {type:s,id:-1,pid:-1,inputTimeScale:e,sequenceNumber:-1,samples:[],dropped:0}}var bn=class{constructor(){this._audioTrack=void 0,this._id3Track=void 0,this.frameIndex=0,this.cachedData=null,this.basePTS=null,this.initPTS=null,this.lastPTS=null;}resetInitSegment(e,t,i,r){this._id3Track={type:"id3",id:3,pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0};}resetTimeStamp(e){this.initPTS=e,this.resetContiguity();}resetContiguity(){this.basePTS=null,this.lastPTS=null,this.frameIndex=0;}canParse(e,t){return false}appendFrame(e,t,i){}demux(e,t){this.cachedData&&(e=Dt(this.cachedData,e),this.cachedData=null);let i=An(e,0),r=i?i.length:0,n,a=this._audioTrack,o=this._id3Track,l=i?Hu(i):void 0,d=e.length;for((this.basePTS===null||this.frameIndex===0&&G(l))&&(this.basePTS=Hy(l,t,this.initPTS),this.lastPTS=this.basePTS),this.lastPTS===null&&(this.lastPTS=this.basePTS),i&&i.length>0&&o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:i,type:At.audioId3,duration:Number.POSITIVE_INFINITY});r<d;){if(this.canParse(e,r)){let c=this.appendFrame(a,e,r);c?(this.frameIndex++,this.lastPTS=c.sample.pts,r+=c.length,n=r):r=d;}else ky(e,r)?(i=An(e,r),o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:i,type:At.audioId3,duration:Number.POSITIVE_INFINITY}),r+=i.length,n=r):r++;if(r===d&&n!==d){let c=e.slice(n);this.cachedData?this.cachedData=Dt(this.cachedData,c):this.cachedData=c;}}return {audioTrack:a,videoTrack:li(),id3Track:o,textTrack:li()}}demuxSampleAes(e,t,i){return Promise.reject(new Error(`[${this}] This demuxer does not support Sample-AES decryption`))}flush(e){let t=this.cachedData;return t&&(this.cachedData=null,this.demux(t,0)),{audioTrack:this._audioTrack,videoTrack:li(),id3Track:this._id3Track,textTrack:li()}}destroy(){this.cachedData=null,this._audioTrack=this._id3Track=void 0;}},Hy=(s,e,t)=>{if(G(s))return s*90;let i=t?t.baseTime*9e4/t.timescale:0;return e*9e4+i},_o=null,Ky=[32,64,96,128,160,192,224,256,288,320,352,384,416,448,32,48,56,64,80,96,112,128,160,192,224,256,320,384,32,40,48,56,64,80,96,112,128,160,192,224,256,320,32,48,56,64,80,96,112,128,144,160,176,192,224,256,8,16,24,32,40,48,56,64,80,96,112,128,144,160],Vy=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],Wy=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],Yy=[0,1,1,4];function hp(s,e,t,i,r){if(t+24>e.length)return;let n=fp(e,t);if(n&&t+n.frameLength<=e.length){let a=n.samplesPerFrame*9e4/n.sampleRate,o=i+r*a,l={unit:e.subarray(t,t+n.frameLength),pts:o,dts:o};return s.config=[],s.channelCount=n.channelCount,s.samplerate=n.sampleRate,s.samples.push(l),{sample:l,length:n.frameLength,missing:0}}}function fp(s,e){let t=s[e+1]>>3&3,i=s[e+1]>>1&3,r=s[e+2]>>4&15,n=s[e+2]>>2&3;if(t!==1&&r!==0&&r!==15&&n!==3){let a=s[e+2]>>1&1,o=s[e+3]>>6,l=t===3?3-i:i===3?3:4,d=Ky[l*14+r-1]*1e3,u=Vy[(t===3?0:t===2?1:2)*3+n],h=o===3?1:2,f=Wy[t][i],m=Yy[i],p=f*8*m,E=Math.floor(f*d/u+a)*m;if(_o===null){let S=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);_o=S?parseInt(S[1]):0;}return !!_o&&_o<=87&&i===2&&d>=224e3&&o===0&&(s[e+3]=s[e+3]|128),{sampleRate:u,channelCount:h,frameLength:E,samplesPerFrame:p}}}function Ku(s,e){return s[e]===255&&(s[e+1]&224)===224&&(s[e+1]&6)!==0}function mp(s,e){return e+1<s.length&&Ku(s,e)}function qy(s,e){return Ku(s,e)&&4<=s.length-e}function gp(s,e){if(e+1<s.length&&Ku(s,e)){let i=fp(s,e),r=4;i!=null&&i.frameLength&&(r=i.frameLength);let n=e+r;return n===s.length||mp(s,n)}return false}var Mc=class extends bn{constructor(e,t){super(),this.observer=void 0,this.config=void 0,this.observer=e,this.config=t;}resetInitSegment(e,t,i,r){super.resetInitSegment(e,t,i,r),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:t,duration:r,inputTimeScale:9e4,dropped:0};}static probe(e,t){if(!e)return false;let i=An(e,0),r=i?.length||0;if(gp(e,r))return false;for(let n=e.length;r<n;r++)if(xy(e,r))return t.log("ADTS sync word found !"),true;return false}canParse(e,t){return Ly(e,t)}appendFrame(e,t,i){op(e,this.observer,t,i,e.manifestCodec);let r=dp(e,t,i,this.basePTS,this.frameIndex);if(r&&r.missing===0)return r}},pp=(s,e)=>{let t=0,i=5;e+=i;let r=new Uint32Array(1),n=new Uint32Array(1),a=new Uint8Array(1);for(;i>0;){a[0]=s[e];let o=Math.min(i,8),l=8-o;n[0]=4278190080>>>24+l<<l,r[0]=(a[0]&n[0])>>l,t=t?t<<o|r[0]:r[0],e+=1,i-=o;}return t},Pc=class extends bn{constructor(e){super(),this.observer=void 0,this.observer=e;}resetInitSegment(e,t,i,r){super.resetInitSegment(e,t,i,r),this._audioTrack={container:"audio/ac-3",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"ac3",samples:[],manifestCodec:t,duration:r,inputTimeScale:9e4,dropped:0};}canParse(e,t){return t+64<e.length}appendFrame(e,t,i){let r=Ep(e,t,i,this.basePTS,this.frameIndex);if(r!==-1)return {sample:e.samples[e.samples.length-1],length:r,missing:0}}static probe(e){if(!e)return false;let t=An(e,0);if(!t)return false;let i=t.length;return e[i]===11&&e[i+1]===119&&Hu(t)!==void 0&&pp(e,i)<16}};function Ep(s,e,t,i,r){if(t+8>e.length||e[t]!==11||e[t+1]!==119)return -1;let n=e[t+4]>>6;if(n>=3)return -1;let o=[48e3,44100,32e3][n],l=e[t+4]&63,c=[64,69,96,64,70,96,80,87,120,80,88,120,96,104,144,96,105,144,112,121,168,112,122,168,128,139,192,128,140,192,160,174,240,160,175,240,192,208,288,192,209,288,224,243,336,224,244,336,256,278,384,256,279,384,320,348,480,320,349,480,384,417,576,384,418,576,448,487,672,448,488,672,512,557,768,512,558,768,640,696,960,640,697,960,768,835,1152,768,836,1152,896,975,1344,896,976,1344,1024,1114,1536,1024,1115,1536,1152,1253,1728,1152,1254,1728,1280,1393,1920,1280,1394,1920][l*3+n]*2;if(t+c>e.length)return -1;let u=e[t+6]>>5,h=0;u===2?h+=2:(u&1&&u!==1&&(h+=2),u&4&&(h+=2));let f=(e[t+6]<<8|e[t+7])>>12-h&1,p=[2,1,2,3,3,4,4,5][u]+f,E=e[t+5]>>3,v=e[t+5]&7,T=new Uint8Array([n<<6|E<<1|v>>2,(v&3)<<6|u<<3|f<<2|l>>4,l<<4&224]),S=1536/o*9e4,A=i+r*S,b=e.subarray(t,t+c);return s.config=T,s.channelCount=p,s.samplerate=o,s.samples.push({unit:b,pts:A}),c}var wc=class extends bn{resetInitSegment(e,t,i,r){super.resetInitSegment(e,t,i,r),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:t,duration:r,inputTimeScale:9e4,dropped:0};}static probe(e){if(!e)return false;let t=An(e,0),i=t?.length||0;if(t&&e[i]===11&&e[i+1]===119&&Hu(t)!==void 0&&pp(e,i)<=16)return false;for(let r=e.length;i<r;i++)if(gp(e,i))return Te.log("MPEG Audio sync word found !"),true;return false}canParse(e,t){return qy(e,t)}appendFrame(e,t,i){if(this.basePTS!==null)return hp(e,t,i,this.basePTS,this.frameIndex)}},jy=/\/emsg[-/]ID3/i,Oc=class{constructor(e,t){this.remainderData=null,this.timeOffset=0,this.config=void 0,this.videoTrack=void 0,this.audioTrack=void 0,this.id3Track=void 0,this.txtTrack=void 0,this.config=t;}resetTimeStamp(){}resetInitSegment(e,t,i,r){let n=this.videoTrack=li("video",1),a=this.audioTrack=li("audio",1),o=this.txtTrack=li("text",1);if(this.id3Track=li("id3",1),this.timeOffset=0,!(e!=null&&e.byteLength))return;let l=Dg(e);if(l.video){let{id:d,timescale:c,codec:u,supplemental:h}=l.video;n.id=d,n.timescale=o.timescale=c,n.codec=u,n.supplemental=h;}if(l.audio){let{id:d,timescale:c,codec:u}=l.audio;a.id=d,a.timescale=c,a.codec=u;}o.id=xg.text,n.sampleDuration=0,n.duration=a.duration=r;}resetContiguity(){this.remainderData=null;}static probe(e){return sT(e)}demux(e,t){this.timeOffset=t;let i=e,r=this.videoTrack,n=this.txtTrack;if(this.config.progressive){this.remainderData&&(i=Dt(this.remainderData,e));let o=cT(i);this.remainderData=o.remainder,r.samples=o.valid||new Uint8Array;}else r.samples=i;let a=this.extractID3Track(r,t);return n.samples=Em(t,r),{videoTrack:r,audioTrack:this.audioTrack,id3Track:a,textTrack:this.txtTrack}}flush(){let e=this.timeOffset,t=this.videoTrack,i=this.txtTrack;t.samples=this.remainderData||new Uint8Array,this.remainderData=null;let r=this.extractID3Track(t,this.timeOffset);return i.samples=Em(e,t),{videoTrack:t,audioTrack:li(),id3Track:r,textTrack:li()}}extractID3Track(e,t){let i=this.id3Track;if(e.samples.length){let r=le(e.samples,["emsg"]);r&&r.forEach(n=>{let a=hT(n);if(jy.test(a.schemeIdUri)){let o=Jm(a,t),l=a.eventDuration===4294967295?Number.POSITIVE_INFINITY:a.eventDuration/a.timeScale;l<=.001&&(l=Number.POSITIVE_INFINITY);let d=a.payload;i.samples.push({data:d,len:d.byteLength,dts:o,pts:o,type:At.emsg,duration:l});}else if(this.config.enableEmsgKLVMetadata&&a.schemeIdUri.startsWith("urn:misb:KLV:bin:1910.1")){let o=Jm(a,t);i.samples.push({data:a.payload,len:a.payload.byteLength,dts:o,pts:o,type:At.misbklv,duration:Number.POSITIVE_INFINITY});}});}return i}demuxSampleAes(e,t,i){return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"))}destroy(){this.config=null,this.remainderData=null,this.videoTrack=this.audioTrack=this.id3Track=this.txtTrack=void 0;}};function Jm(s,e){return G(s.presentationTime)?s.presentationTime/s.timeScale:e+s.presentationTimeDelta/s.timeScale}var Fc=class{constructor(e,t,i){this.keyData=void 0,this.decrypter=void 0,this.keyData=i,this.decrypter=new En(t,{removePKCS7Padding:false});}decryptBuffer(e){return this.decrypter.decrypt(e,this.keyData.key.buffer,this.keyData.iv.buffer,Ni.cbc)}decryptAacSample(e,t,i){let r=e[t].unit;if(r.length<=16)return;let n=r.subarray(16,r.length-r.length%16),a=n.buffer.slice(n.byteOffset,n.byteOffset+n.length);this.decryptBuffer(a).then(o=>{let l=new Uint8Array(o);r.set(l,16),this.decrypter.isSync()||this.decryptAacSamples(e,t+1,i);}).catch(i);}decryptAacSamples(e,t,i){for(;;t++){if(t>=e.length){i();return}if(!(e[t].unit.length<32)&&(this.decryptAacSample(e,t,i),!this.decrypter.isSync()))return}}getAvcEncryptedData(e){let t=Math.floor((e.length-48)/160)*16+16,i=new Int8Array(t),r=0;for(let n=32;n<e.length-16;n+=160,r+=16)i.set(e.subarray(n,n+16),r);return i}getAvcDecryptedUnit(e,t){let i=new Uint8Array(t),r=0;for(let n=32;n<e.length-16;n+=160,r+=16)e.set(i.subarray(r,r+16),n);return e}decryptAvcSample(e,t,i,r,n){let a=Pg(n.data),o=this.getAvcEncryptedData(a);this.decryptBuffer(o.buffer).then(l=>{n.data=this.getAvcDecryptedUnit(a,l),this.decrypter.isSync()||this.decryptAvcSamples(e,t,i+1,r);}).catch(r);}decryptAvcSamples(e,t,i,r){if(e instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;t++,i=0){if(t>=e.length){r();return}let n=e[t].units;for(;!(i>=n.length);i++){let a=n[i];if(!(a.data.length<=48||a.type!==1&&a.type!==5)&&(this.decryptAvcSample(e,t,i,r,a),!this.decrypter.isSync()))return}}}},tl=class{constructor(){this.VideoSample=null;}createVideoSample(e,t,i){return {key:e,frame:false,pts:t,dts:i,units:[],length:0}}getLastNalUnit(e){var t;let i=this.VideoSample,r;if((!i||i.units.length===0)&&(i=e[e.length-1]),(t=i)!=null&&t.units){let n=i.units;r=n[n.length-1];}return r}pushAccessUnit(e,t){if(e.units.length&&e.frame){if(e.pts===void 0){let i=t.samples,r=i.length;if(r){let n=i[r-1];e.pts=n.pts,e.dts=n.dts;}else {t.dropped++;return}}t.samples.push(e);}}parseNALu(e,t,i){let r=t.byteLength,n=e.naluState||0,a=n,o=[],l=0,d,c,u,h=-1,f=0;for(n===-1&&(h=0,f=this.getNALuType(t,0),n=0,l=1);l<r;){if(d=t[l++],!n){n=d?0:1;continue}if(n===1){n=d?0:2;continue}if(!d)n=3;else if(d===1){if(c=l-n-1,h>=0){let m={data:t.subarray(h,c),type:f};o.push(m);}else {let m=this.getLastNalUnit(e.samples);m&&(a&&l<=4-a&&m.state&&(m.data=m.data.subarray(0,m.data.byteLength-a)),c>0&&(m.data=Dt(m.data,t.subarray(0,c)),m.state=0));}l<r?(u=this.getNALuType(t,l),h=l,f=u,n=0):n=-1;}else n=0;}if(h>=0&&n>=0){let m={data:t.subarray(h,r),type:f,state:n};o.push(m);}if(o.length===0){let m=this.getLastNalUnit(e.samples);m&&(m.data=Dt(m.data,t));}return e.naluState=n,o}},ls=class{constructor(e){this.data=void 0,this.bytesAvailable=void 0,this.word=void 0,this.bitsAvailable=void 0,this.data=e,this.bytesAvailable=e.byteLength,this.word=0,this.bitsAvailable=0;}loadWord(){let e=this.data,t=this.bytesAvailable,i=e.byteLength-t,r=new Uint8Array(4),n=Math.min(4,t);if(n===0)throw new Error("no bytes available");r.set(e.subarray(i,i+n)),this.word=new DataView(r.buffer).getUint32(0),this.bitsAvailable=n*8,this.bytesAvailable-=n;}skipBits(e){let t;e=Math.min(e,this.bytesAvailable*8+this.bitsAvailable),this.bitsAvailable>e?(this.word<<=e,this.bitsAvailable-=e):(e-=this.bitsAvailable,t=e>>3,e-=t<<3,this.bytesAvailable-=t,this.loadWord(),this.word<<=e,this.bitsAvailable-=e);}readBits(e){let t=Math.min(this.bitsAvailable,e),i=this.word>>>32-t;if(e>32&&Te.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=t,this.bitsAvailable>0)this.word<<=t;else if(this.bytesAvailable>0)this.loadWord();else throw new Error("no bits available");return t=e-t,t>0&&this.bitsAvailable?i<<t|this.readBits(t):i}skipLZ(){let e;for(e=0;e<this.bitsAvailable;++e)if((this.word&2147483648>>>e)!==0)return this.word<<=e,this.bitsAvailable-=e,e;return this.loadWord(),e+this.skipLZ()}skipUEG(){this.skipBits(1+this.skipLZ());}skipEG(){this.skipBits(1+this.skipLZ());}readUEG(){let e=this.skipLZ();return this.readBits(e+1)-1}readEG(){let e=this.readUEG();return 1&e?1+e>>>1:-1*(e>>>1)}readBoolean(){return this.readBits(1)===1}readUByte(){return this.readBits(8)}readUShort(){return this.readBits(16)}readUInt(){return this.readBits(32)}},Nc=class extends tl{parsePES(e,t,i,r){let n=this.parseNALu(e,i.data,r),a=this.VideoSample,o,l=false;i.data=null,a&&n.length&&!e.audFound&&(this.pushAccessUnit(a,e),a=this.VideoSample=this.createVideoSample(false,i.pts,i.dts)),n.forEach(d=>{var c,u;switch(d.type){case 1:{let p=false;o=true;let E=d.data;if(l&&E.length>4){let v=this.readSliceType(E);(v===2||v===4||v===7||v===9)&&(p=true);}if(p){var h;(h=a)!=null&&h.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null);}a||(a=this.VideoSample=this.createVideoSample(true,i.pts,i.dts)),a.frame=true,a.key=p;break}case 5:o=true,(c=a)!=null&&c.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null),a||(a=this.VideoSample=this.createVideoSample(true,i.pts,i.dts)),a.key=true,a.frame=true;break;case 6:{o=true,Pu(d.data,1,i.pts,t.samples);break}case 7:{var f,m;o=true,l=true;let p=d.data,E=this.readSPS(p);if(!e.sps||e.width!==E.width||e.height!==E.height||((f=e.pixelRatio)==null?void 0:f[0])!==E.pixelRatio[0]||((m=e.pixelRatio)==null?void 0:m[1])!==E.pixelRatio[1]){e.width=E.width,e.height=E.height,e.pixelRatio=E.pixelRatio,e.sps=[p];let v=p.subarray(1,4),T="avc1.";for(let S=0;S<3;S++){let A=v[S].toString(16);A.length<2&&(A="0"+A),T+=A;}e.codec=T;}break}case 8:o=true,e.pps=[d.data];break;case 9:o=true,e.audFound=true,(u=a)!=null&&u.frame&&(this.pushAccessUnit(a,e),a=null),a||(a=this.VideoSample=this.createVideoSample(false,i.pts,i.dts));break;case 12:o=true;break;default:o=false;break}a&&o&&a.units.push(d);}),r&&a&&(this.pushAccessUnit(a,e),this.VideoSample=null);}getNALuType(e,t){return e[t]&31}readSliceType(e){let t=new ls(e);return t.readUByte(),t.readUEG(),t.readUEG()}skipScalingList(e,t){let i=8,r=8,n;for(let a=0;a<e;a++)r!==0&&(n=t.readEG(),r=(i+n+256)%256),i=r===0?i:r;}readSPS(e){let t=new ls(e),i=0,r=0,n=0,a=0,o,l,d,c=t.readUByte.bind(t),u=t.readBits.bind(t),h=t.readUEG.bind(t),f=t.readBoolean.bind(t),m=t.skipBits.bind(t),p=t.skipEG.bind(t),E=t.skipUEG.bind(t),v=this.skipScalingList.bind(this);c();let T=c();if(u(5),m(3),c(),E(),T===100||T===110||T===122||T===244||T===44||T===83||T===86||T===118||T===128){let k=h();if(k===3&&m(1),E(),E(),m(1),f())for(l=k!==3?8:12,d=0;d<l;d++)f()&&(d<6?v(16,t):v(64,t));}E();let S=h();if(S===0)h();else if(S===1)for(m(1),p(),p(),o=h(),d=0;d<o;d++)p();E(),m(1);let A=h(),b=h(),D=u(1);D===0&&m(1),m(1),f()&&(i=h(),r=h(),n=h(),a=h());let I=[1,1];if(f()&&f())switch(c()){case 1:I=[1,1];break;case 2:I=[12,11];break;case 3:I=[10,11];break;case 4:I=[16,11];break;case 5:I=[40,33];break;case 6:I=[24,11];break;case 7:I=[20,11];break;case 8:I=[32,11];break;case 9:I=[80,33];break;case 10:I=[18,11];break;case 11:I=[15,11];break;case 12:I=[64,33];break;case 13:I=[160,99];break;case 14:I=[4,3];break;case 15:I=[3,2];break;case 16:I=[2,1];break;case 255:{I=[c()<<8|c(),c()<<8|c()];break}}return {width:Math.ceil((A+1)*16-i*2-r*2),height:(2-D)*(b+1)*16-(D?2:4)*(n+a),pixelRatio:I}}},Uc=class extends tl{constructor(...e){super(...e),this.initVPS=null;}parsePES(e,t,i,r){let n=this.parseNALu(e,i.data,r),a=this.VideoSample,o,l=false;i.data=null,a&&n.length&&!e.audFound&&(this.pushAccessUnit(a,e),a=this.VideoSample=this.createVideoSample(false,i.pts,i.dts)),n.forEach(d=>{var c,u;switch(d.type){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:a||(a=this.VideoSample=this.createVideoSample(false,i.pts,i.dts)),a.frame=true,o=true;break;case 16:case 17:case 18:case 21:if(o=true,l){var h;(h=a)!=null&&h.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null);}a||(a=this.VideoSample=this.createVideoSample(true,i.pts,i.dts)),a.key=true,a.frame=true;break;case 19:case 20:o=true,(c=a)!=null&&c.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null),a||(a=this.VideoSample=this.createVideoSample(true,i.pts,i.dts)),a.key=true,a.frame=true;break;case 39:o=true,Pu(d.data,2,i.pts,t.samples);break;case 32:o=true,e.vps||(typeof e.params!="object"&&(e.params={}),e.params=ye(e.params,this.readVPS(d.data)),this.initVPS=d.data),e.vps=[d.data];break;case 33:if(o=true,l=true,e.vps!==void 0&&e.vps[0]!==this.initVPS&&e.sps!==void 0&&!this.matchSPS(e.sps[0],d.data)&&(this.initVPS=e.vps[0],e.sps=e.pps=void 0),!e.sps){let f=this.readSPS(d.data);e.width=f.width,e.height=f.height,e.pixelRatio=f.pixelRatio,e.codec=f.codecString,e.sps=[],typeof e.params!="object"&&(e.params={});for(let m in f.params)e.params[m]=f.params[m];}this.pushParameterSet(e.sps,d.data,e.vps),a||(a=this.VideoSample=this.createVideoSample(true,i.pts,i.dts)),a.key=true;break;case 34:if(o=true,typeof e.params=="object"){if(!e.pps){e.pps=[];let f=this.readPPS(d.data);for(let m in f)e.params[m]=f[m];}this.pushParameterSet(e.pps,d.data,e.vps);}break;case 35:o=true,e.audFound=true,(u=a)!=null&&u.frame&&(this.pushAccessUnit(a,e),a=null),a||(a=this.VideoSample=this.createVideoSample(false,i.pts,i.dts));break;default:o=false;break}a&&o&&a.units.push(d);}),r&&a&&(this.pushAccessUnit(a,e),this.VideoSample=null);}pushParameterSet(e,t,i){(i&&i[0]===this.initVPS||!i&&!e.length)&&e.push(t);}getNALuType(e,t){return (e[t]&126)>>>1}ebsp2rbsp(e){let t=new Uint8Array(e.byteLength),i=0;for(let r=0;r<e.byteLength;r++)r>=2&&e[r]===3&&e[r-1]===0&&e[r-2]===0||(t[i]=e[r],i++);return new Uint8Array(t.buffer,0,i)}pushAccessUnit(e,t){super.pushAccessUnit(e,t),this.initVPS&&(this.initVPS=null);}readVPS(e){let t=new ls(e);t.readUByte(),t.readUByte(),t.readBits(4),t.skipBits(2),t.readBits(6);let i=t.readBits(3),r=t.readBoolean();return {numTemporalLayers:i+1,temporalIdNested:r}}readSPS(e){let t=new ls(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.readBits(4);let i=t.readBits(3);t.readBoolean();let r=t.readBits(2),n=t.readBoolean(),a=t.readBits(5),o=t.readUByte(),l=t.readUByte(),d=t.readUByte(),c=t.readUByte(),u=t.readUByte(),h=t.readUByte(),f=t.readUByte(),m=t.readUByte(),p=t.readUByte(),E=t.readUByte(),v=t.readUByte(),T=[],S=[];for(let fe=0;fe<i;fe++)T.push(t.readBoolean()),S.push(t.readBoolean());if(i>0)for(let fe=i;fe<8;fe++)t.readBits(2);for(let fe=0;fe<i;fe++)T[fe]&&(t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte()),S[fe]&&t.readUByte();t.readUEG();let A=t.readUEG();A==3&&t.skipBits(1);let b=t.readUEG(),D=t.readUEG(),I=t.readBoolean(),k=0,R=0,L=0,M=0;I&&(k+=t.readUEG(),R+=t.readUEG(),L+=t.readUEG(),M+=t.readUEG());let B=t.readUEG(),K=t.readUEG(),j=t.readUEG(),V=t.readBoolean();for(let fe=V?0:i;fe<=i;fe++)t.skipUEG(),t.skipUEG(),t.skipUEG();if(t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.readBoolean()&&t.readBoolean())for(let $e=0;$e<4;$e++)for(let it=0;it<($e===3?2:6);it++)if(!t.readBoolean())t.readUEG();else {let _t=Math.min(64,1<<4+($e<<1));$e>1&&t.readEG();for(let me=0;me<_t;me++)t.readEG();}t.readBoolean(),t.readBoolean(),t.readBoolean()&&(t.readUByte(),t.skipUEG(),t.skipUEG(),t.readBoolean());let $=t.readUEG(),q=0;for(let fe=0;fe<$;fe++){let $e=false;if(fe!==0&&($e=t.readBoolean()),$e){fe===$&&t.readUEG(),t.readBoolean(),t.readUEG();let it=0;for(let Vt=0;Vt<=q;Vt++){let _t=t.readBoolean(),me=false;_t||(me=t.readBoolean()),(_t||me)&&it++;}q=it;}else {let it=t.readUEG(),Vt=t.readUEG();q=it+Vt;for(let _t=0;_t<it;_t++)t.readUEG(),t.readBoolean();for(let _t=0;_t<Vt;_t++)t.readUEG(),t.readBoolean();}}if(t.readBoolean()){let fe=t.readUEG();for(let $e=0;$e<fe;$e++){for(let it=0;it<j+4;it++)t.readBits(1);t.readBits(1);}}let N=0,U=1,te=1,ge=true,ie=1,de=0;t.readBoolean(),t.readBoolean();let Be=false;if(t.readBoolean()){if(t.readBoolean()){let mt=t.readUByte(),kn=[1,12,10,16,40,24,20,32,80,18,15,64,160,4,3,2],fs=[1,11,11,11,33,11,11,11,33,11,11,33,99,3,2,1];mt>0&&mt<16?(U=kn[mt-1],te=fs[mt-1]):mt===255&&(U=t.readBits(16),te=t.readBits(16));}if(t.readBoolean()&&t.readBoolean(),t.readBoolean()&&(t.readBits(3),t.readBoolean(),t.readBoolean()&&(t.readUByte(),t.readUByte(),t.readUByte())),t.readBoolean()&&(t.readUEG(),t.readUEG()),t.readBoolean(),t.readBoolean(),t.readBoolean(),Be=t.readBoolean(),Be&&(t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG()),t.readBoolean()&&(ie=t.readBits(32),de=t.readBits(32),t.readBoolean()&&t.readUEG(),t.readBoolean())){let fs=t.readBoolean(),Dn=t.readBoolean(),Ui=false;(fs||Dn)&&(Ui=t.readBoolean(),Ui&&(t.readUByte(),t.readBits(5),t.readBoolean(),t.readBits(5)),t.readBits(4),t.readBits(4),Ui&&t.readBits(4),t.readBits(5),t.readBits(5),t.readBits(5));for(let Cn=0;Cn<=i;Cn++){ge=t.readBoolean();let Tl=ge||t.readBoolean(),Mn=false;Tl?t.readEG():Mn=t.readBoolean();let Ze=Mn?1:t.readUEG()+1;if(fs)for(let Ie=0;Ie<Ze;Ie++)t.readUEG(),t.readUEG(),Ui&&(t.readUEG(),t.readUEG()),t.skipBits(1);if(Dn)for(let Ie=0;Ie<Ze;Ie++)t.readUEG(),t.readUEG(),Ui&&(t.readUEG(),t.readUEG()),t.skipBits(1);}}t.readBoolean()&&(t.readBoolean(),t.readBoolean(),t.readBoolean(),N=t.readUEG());}let tt=b,ft=D;if(I){let fe=1,$e=1;A===1?fe=$e=2:A==2&&(fe=2),tt=b-fe*R-fe*k,ft=D-$e*M-$e*L;}let Kt=r?["A","B","C"][r]:"",Si=o<<24|l<<16|d<<8|c,us=0;for(let fe=0;fe<32;fe++)us=(us|(Si>>fe&1)<<31-fe)>>>0;let hs=us.toString(16);return a===1&&hs==="2"&&(hs="6"),{codecString:`hvc1.${Kt}${a}.${hs}.${n?"H":"L"}${v}.B0`,params:{general_tier_flag:n,general_profile_idc:a,general_profile_space:r,general_profile_compatibility_flags:[o,l,d,c],general_constraint_indicator_flags:[u,h,f,m,p,E],general_level_idc:v,bit_depth:B+8,bit_depth_luma_minus8:B,bit_depth_chroma_minus8:K,min_spatial_segmentation_idc:N,chroma_format_idc:A,frame_rate:{fixed:ge,fps:de/ie}},width:tt,height:ft,pixelRatio:[U,te]}}readPPS(e){let t=new ls(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.skipUEG(),t.skipUEG(),t.skipBits(2),t.skipBits(3),t.skipBits(2),t.skipUEG(),t.skipUEG(),t.skipEG(),t.skipBits(2),t.readBoolean()&&t.skipUEG(),t.skipEG(),t.skipEG(),t.skipBits(4);let r=t.readBoolean(),n=t.readBoolean(),a=1;return n&&r?a=0:n?a=3:r&&(a=2),{parallelismType:a}}matchSPS(e,t){return String.fromCharCode.apply(null,e).substr(3)===String.fromCharCode.apply(null,t).substr(3)}},je=188,Bc=class s{constructor(e,t,i,r){this.logger=void 0,this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.sampleAes=null,this.pmtParsed=false,this.audioCodec=void 0,this.videoCodec=void 0,this._pmtId=-1,this._videoTrack=void 0,this._audioTrack=void 0,this._id3Track=void 0,this._txtTrack=void 0,this.aacOverFlow=null,this.remainderData=null,this.videoParser=void 0,this.observer=e,this.config=t,this.typeSupported=i,this.logger=r,this.videoParser=null;}static probe(e,t){let i=s.syncOffset(e);return i>0&&t.warn(`MPEG2-TS detected but first sync word found @ offset ${i}`),i!==-1}static syncOffset(e){let t=e.length,i=Math.min(je*5,t-je)+1,r=0;for(;r<i;){let n=false,a=-1,o=0;for(let l=r;l<t;l+=je)if(e[l]===71&&(t-l===je||e[l+je]===71)){if(o++,a===-1&&(a=l,a!==0&&(i=Math.min(a+je*99,e.length-je)+1)),n||(n=$c(e,l)===0),n&&o>1&&(a===0&&o>2||l+je>i))return a}else {if(o)return -1;break}r++;}return -1}static createTrack(e,t){return {container:e==="video"||e==="audio"?"video/mp2t":void 0,type:e,id:xg[e],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:e==="audio"?t:void 0}}resetInitSegment(e,t,i,r){this.pmtParsed=false,this._pmtId=-1,this._videoTrack=s.createTrack("video"),this._videoTrack.duration=r,this._audioTrack=s.createTrack("audio",r),this._id3Track=s.createTrack("id3"),this._txtTrack=s.createTrack("text"),this._audioTrack.segmentCodec="aac",this.videoParser=null,this.aacOverFlow=null,this.remainderData=null,this.audioCodec=t,this.videoCodec=i;}resetTimeStamp(){}resetContiguity(){let{_audioTrack:e,_videoTrack:t,_id3Track:i}=this;e&&(e.pesData=null),t&&(t.pesData=null),i&&(i.pesData=null),this.aacOverFlow=null,this.remainderData=null;}demux(e,t,i=false,r=false){i||(this.sampleAes=null);let n,a=this._videoTrack,o=this._audioTrack,l=this._id3Track,d=this._txtTrack,c=a.pid,u=a.pesData,h=o.pid,f=l.pid,m=o.pesData,p=l.pesData,E=null,v=this.pmtParsed,T=this._pmtId,S=e.length;if(this.remainderData&&(e=Dt(this.remainderData,e),S=e.length,this.remainderData=null),S<je&&!r)return this.remainderData=e,{audioTrack:o,videoTrack:a,id3Track:l,textTrack:d};let A=Math.max(0,s.syncOffset(e));S-=(S-A)%je,S<e.byteLength&&!r&&(this.remainderData=new Uint8Array(e.buffer,S,e.buffer.byteLength-S));let b=0;for(let I=A;I<S;I+=je)if(e[I]===71){let k=!!(e[I+1]&64),R=$c(e,I),L=(e[I+3]&48)>>4,M;if(L>1){if(M=I+5+e[I+4],M===I+je)continue}else M=I+4;switch(R){case c:k&&(u&&(n=Xs(u,this.logger))&&(this.readyVideoParser(a.segmentCodec),this.videoParser!==null&&this.videoParser.parsePES(a,d,n,false)),u={data:[],size:0}),u&&(u.data.push(e.subarray(M,I+je)),u.size+=I+je-M);break;case h:if(k){if(m&&(n=Xs(m,this.logger)))switch(o.segmentCodec){case "aac":this.parseAACPES(o,n);break;case "mp3":this.parseMPEGPES(o,n);break;case "ac3":this.parseAC3PES(o,n);break}m={data:[],size:0};}m&&(m.data.push(e.subarray(M,I+je)),m.size+=I+je-M);break;case f:k&&(p&&(n=Xs(p,this.logger))&&this.parseID3PES(l,n),p={data:[],size:0}),p&&(p.data.push(e.subarray(M,I+je)),p.size+=I+je-M);break;case 0:k&&(M+=e[M]+1),T=this._pmtId=zy(e,M);break;case T:{k&&(M+=e[M]+1);let B=Qy(e,M,this.typeSupported,i,this.observer,this.logger);c=B.videoPid,c>0&&(a.pid=c,a.segmentCodec=B.segmentVideoCodec),h=B.audioPid,h>0&&(o.pid=h,o.segmentCodec=B.segmentAudioCodec),f=B.id3Pid,f>0&&(l.pid=f),E!==null&&!v&&(this.logger.warn(`MPEG-TS PMT found at ${I} after unknown PID '${E}'. Backtracking to sync byte @${A} to parse all TS packets.`),E=null,I=A-188),v=this.pmtParsed=true;break}case 17:case 8191:break;default:E=R;break}}else b++;b>0&&Gc(this.observer,new Error(`Found ${b} TS packet/s that do not start with 0x47`),void 0,this.logger),a.pesData=u,o.pesData=m,l.pesData=p;let D={audioTrack:o,videoTrack:a,id3Track:l,textTrack:d};return r&&this.extractRemainingSamples(D),D}flush(){let{remainderData:e}=this;this.remainderData=null;let t;return e?t=this.demux(e,-1,false,true):t={videoTrack:this._videoTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(t),this.sampleAes?this.decrypt(t,this.sampleAes):t}extractRemainingSamples(e){let{audioTrack:t,videoTrack:i,id3Track:r,textTrack:n}=e,a=i.pesData,o=t.pesData,l=r.pesData,d;if(a&&(d=Xs(a,this.logger))?(this.readyVideoParser(i.segmentCodec),this.videoParser!==null&&(this.videoParser.parsePES(i,n,d,true),i.pesData=null)):i.pesData=a,o&&(d=Xs(o,this.logger))){switch(t.segmentCodec){case "aac":this.parseAACPES(t,d);break;case "mp3":this.parseMPEGPES(t,d);break;case "ac3":this.parseAC3PES(t,d);break}t.pesData=null;}else o!=null&&o.size&&this.logger.log("last AAC PES packet truncated,might overlap between fragments"),t.pesData=o;l&&(d=Xs(l,this.logger))?(this.parseID3PES(r,d),r.pesData=null):r.pesData=l;}demuxSampleAes(e,t,i){let r=this.demux(e,i,true,!this.config.progressive),n=this.sampleAes=new Fc(this.observer,this.config,t);return this.decrypt(r,n)}readyVideoParser(e){this.videoParser===null&&(e==="avc"?this.videoParser=new Nc:e==="hevc"&&(this.videoParser=new Uc));}decrypt(e,t){return new Promise(i=>{let{audioTrack:r,videoTrack:n}=e;r.samples&&r.segmentCodec==="aac"?t.decryptAacSamples(r.samples,0,()=>{n.samples?t.decryptAvcSamples(n.samples,0,0,()=>{i(e);}):i(e);}):n.samples&&t.decryptAvcSamples(n.samples,0,0,()=>{i(e);});})}destroy(){this.observer&&this.observer.removeAllListeners(),this.config=this.logger=this.observer=null,this.aacOverFlow=this.videoParser=this.remainderData=this.sampleAes=null,this._videoTrack=this._audioTrack=this._id3Track=this._txtTrack=void 0;}parseAACPES(e,t){let i=0,r=this.aacOverFlow,n=t.data;if(r){this.aacOverFlow=null;let u=r.missing,h=r.sample.unit.byteLength;if(u===-1)n=Dt(r.sample.unit,n);else {let f=h-u;r.sample.unit.set(n.subarray(0,u),f),e.samples.push(r.sample),i=r.missing;}}let a,o;for(a=i,o=n.length;a<o-1&&!el(n,a);a++);if(a!==i){let u,h=a<o-1;if(h?u=`AAC PES did not start with ADTS header,offset:${a}`:u="No ADTS header found in AAC PES",Gc(this.observer,new Error(u),h,this.logger),!h)return}op(e,this.observer,n,a,this.audioCodec);let l;if(t.pts!==void 0)l=t.pts;else if(r){let u=lp(e.samplerate);l=r.sample.pts+u;}else {this.logger.warn("[tsdemuxer]: AAC PES unknown PTS");return}let d=0,c;for(;a<o;)if(c=dp(e,n,a,l,d),a+=c.length,c.missing){this.aacOverFlow=c;break}else for(d++;a<o-1&&!el(n,a);a++);}parseMPEGPES(e,t){let i=t.data,r=i.length,n=0,a=0,o=t.pts;if(o===void 0){this.logger.warn("[tsdemuxer]: MPEG PES unknown PTS");return}for(;a<r;)if(mp(i,a)){let l=hp(e,i,a,o,n);if(l)a+=l.length,n++;else break}else a++;}parseAC3PES(e,t){{let i=t.data,r=t.pts;if(r===void 0){this.logger.warn("[tsdemuxer]: AC3 PES unknown PTS");return}let n=i.length,a=0,o=0,l;for(;o<n&&(l=Ep(e,i,o,r,a++))>0;)o+=l;}}parseID3PES(e,t){if(t.pts===void 0){this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS");return}let i=ye({},t,{type:this._videoTrack?At.emsg:At.audioId3,duration:Number.POSITIVE_INFINITY});e.samples.push(i);}};function $c(s,e){return ((s[e+1]&31)<<8)+s[e+2]}function zy(s,e){return (s[e+10]&31)<<8|s[e+11]}function Qy(s,e,t,i,r,n){let a={audioPid:-1,videoPid:-1,id3Pid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},o=(s[e+1]&15)<<8|s[e+2],l=e+3+o-4,d=(s[e+10]&15)<<8|s[e+11];for(e+=12+d;e<l;){let c=$c(s,e),u=(s[e+3]&15)<<8|s[e+4];switch(s[e]){case 207:if(!i){Jd("ADTS AAC",n);break}case 15:a.audioPid===-1&&(a.audioPid=c);break;case 21:a.id3Pid===-1&&(a.id3Pid=c);break;case 219:if(!i){Jd("H.264",n);break}case 27:a.videoPid===-1&&(a.videoPid=c);break;case 3:case 4:!t.mpeg&&!t.mp3?n.log("MPEG audio found, not supported in this browser"):a.audioPid===-1&&(a.audioPid=c,a.segmentAudioCodec="mp3");break;case 193:if(!i){Jd("AC-3",n);break}case 129:t.ac3?a.audioPid===-1&&(a.audioPid=c,a.segmentAudioCodec="ac3"):n.log("AC-3 audio found, not supported in this browser");break;case 6:if(a.audioPid===-1&&u>0){let h=e+5,f=u;for(;f>2;){switch(s[h]){case 106:t.ac3!==true?n.log("AC-3 audio found, not supported in this browser for now"):(a.audioPid=c,a.segmentAudioCodec="ac3");break}let p=s[h+1]+2;h+=p,f-=p;}}break;case 194:case 135:return Gc(r,new Error("Unsupported EC-3 in M2TS found"),void 0,n),a;case 36:a.videoPid===-1&&(a.videoPid=c,a.segmentVideoCodec="hevc",n.log("HEVC in M2TS found"));break}e+=u+5;}return a}function Gc(s,e,t,i){i.warn(`parsing error: ${e.message}`),s.emit(g.ERROR,g.ERROR,{type:z.MEDIA_ERROR,details:x.FRAG_PARSING_ERROR,fatal:false,levelRetry:t,error:e,reason:e.message});}function Jd(s,e){e.log(`${s} with AES-128-CBC encryption found in unencrypted stream`);}function Xs(s,e){let t=0,i,r,n,a,o,l=s.data;if(!s||s.size===0)return null;for(;l[0].length<19&&l.length>1;)l[0]=Dt(l[0],l[1]),l.splice(1,1);if(i=l[0],(i[0]<<16)+(i[1]<<8)+i[2]===1){if(r=(i[4]<<8)+i[5],r&&r>s.size-6)return null;let c=i[7];c&192&&(a=(i[9]&14)*536870912+(i[10]&255)*4194304+(i[11]&254)*16384+(i[12]&255)*128+(i[13]&254)/2,c&64?(o=(i[14]&14)*536870912+(i[15]&255)*4194304+(i[16]&254)*16384+(i[17]&255)*128+(i[18]&254)/2,a-o>60*9e4&&(e.warn(`${Math.round((a-o)/9e4)}s delta between PTS and DTS, align them`),a=o)):o=a),n=i[8];let u=n+9;if(s.size<=u)return null;s.size-=u;let h=new Uint8Array(s.size);for(let f=0,m=l.length;f<m;f++){i=l[f];let p=i.byteLength;if(u)if(u>p){u-=p;continue}else i=i.subarray(u),p-=u,u=0;h.set(i,t),t+=p;}return r&&(r-=n+3),{data:h,pts:a,dts:o,len:r}}return null}var Hc=class{static getSilentFrame(e,t){switch(e){case "mp4a.40.2":if(t===1)return new Uint8Array([0,200,0,128,35,128]);if(t===2)return new Uint8Array([33,0,73,144,2,25,0,35,128]);if(t===3)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,142]);if(t===4)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,128,44,128,8,2,56]);if(t===5)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,56]);if(t===6)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,0,178,0,32,8,224]);break;default:if(t===1)return new Uint8Array([1,64,34,128,163,78,230,128,186,8,0,0,0,28,6,241,193,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(t===2)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(t===3)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);break}}},Mi=Math.pow(2,32)-1,Ve=class s{static init(){s.types={avc1:[],avcC:[],hvc1:[],hvcC:[],btrt:[],dinf:[],dref:[],esds:[],ftyp:[],hdlr:[],mdat:[],mdhd:[],mdia:[],mfhd:[],minf:[],moof:[],moov:[],mp4a:[],".mp3":[],dac3:[],"ac-3":[],mvex:[],mvhd:[],pasp:[],sdtp:[],stbl:[],stco:[],stsc:[],stsd:[],stsz:[],stts:[],tfdt:[],tfhd:[],traf:[],trak:[],trun:[],trex:[],tkhd:[],vmhd:[],smhd:[]};let e;for(e in s.types)s.types.hasOwnProperty(e)&&(s.types[e]=[e.charCodeAt(0),e.charCodeAt(1),e.charCodeAt(2),e.charCodeAt(3)]);let t=new Uint8Array([0,0,0,0,0,0,0,0,118,105,100,101,0,0,0,0,0,0,0,0,0,0,0,0,86,105,100,101,111,72,97,110,100,108,101,114,0]),i=new Uint8Array([0,0,0,0,0,0,0,0,115,111,117,110,0,0,0,0,0,0,0,0,0,0,0,0,83,111,117,110,100,72,97,110,100,108,101,114,0]);s.HDLR_TYPES={video:t,audio:i};let r=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1]),n=new Uint8Array([0,0,0,0,0,0,0,0]);s.STTS=s.STSC=s.STCO=n,s.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),s.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),s.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),s.STSD=new Uint8Array([0,0,0,0,0,0,0,1]);let a=new Uint8Array([105,115,111,109]),o=new Uint8Array([97,118,99,49]),l=new Uint8Array([0,0,0,1]);s.FTYP=s.box(s.types.ftyp,a,l,a,o),s.DINF=s.box(s.types.dinf,s.box(s.types.dref,r));}static box(e,...t){let i=8,r=t.length,n=r;for(;r--;)i+=t[r].byteLength;let a=new Uint8Array(i);for(a[0]=i>>24&255,a[1]=i>>16&255,a[2]=i>>8&255,a[3]=i&255,a.set(e,4),r=0,i=8;r<n;r++)a.set(t[r],i),i+=t[r].byteLength;return a}static hdlr(e){return s.box(s.types.hdlr,s.HDLR_TYPES[e])}static mdat(e){return s.box(s.types.mdat,e)}static mdhd(e,t){t*=e;let i=Math.floor(t/(Mi+1)),r=Math.floor(t%(Mi+1));return s.box(s.types.mdhd,new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,e&255,i>>24,i>>16&255,i>>8&255,i&255,r>>24,r>>16&255,r>>8&255,r&255,85,196,0,0]))}static mdia(e){return s.box(s.types.mdia,s.mdhd(e.timescale||0,e.duration||0),s.hdlr(e.type),s.minf(e))}static mfhd(e){return s.box(s.types.mfhd,new Uint8Array([0,0,0,0,e>>24,e>>16&255,e>>8&255,e&255]))}static minf(e){return e.type==="audio"?s.box(s.types.minf,s.box(s.types.smhd,s.SMHD),s.DINF,s.stbl(e)):s.box(s.types.minf,s.box(s.types.vmhd,s.VMHD),s.DINF,s.stbl(e))}static moof(e,t,i){return s.box(s.types.moof,s.mfhd(e),s.traf(i,t))}static moov(e){let t=e.length,i=[];for(;t--;)i[t]=s.trak(e[t]);return s.box.apply(null,[s.types.moov,s.mvhd(e[0].timescale||0,e[0].duration||0)].concat(i).concat(s.mvex(e)))}static mvex(e){let t=e.length,i=[];for(;t--;)i[t]=s.trex(e[t]);return s.box.apply(null,[s.types.mvex,...i])}static mvhd(e,t){t*=e;let i=Math.floor(t/(Mi+1)),r=Math.floor(t%(Mi+1)),n=new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,e&255,i>>24,i>>16&255,i>>8&255,i&255,r>>24,r>>16&255,r>>8&255,r&255,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255]);return s.box(s.types.mvhd,n)}static sdtp(e){let t=e.samples||[],i=new Uint8Array(4+t.length),r,n;for(r=0;r<t.length;r++)n=t[r].flags,i[r+4]=n.dependsOn<<4|n.isDependedOn<<2|n.hasRedundancy;return s.box(s.types.sdtp,i)}static stbl(e){return s.box(s.types.stbl,s.stsd(e),s.box(s.types.stts,s.STTS),s.box(s.types.stsc,s.STSC),s.box(s.types.stsz,s.STSZ),s.box(s.types.stco,s.STCO))}static avc1(e){let t=[],i=[],r,n,a;for(r=0;r<e.sps.length;r++)n=e.sps[r],a=n.byteLength,t.push(a>>>8&255),t.push(a&255),t=t.concat(Array.prototype.slice.call(n));for(r=0;r<e.pps.length;r++)n=e.pps[r],a=n.byteLength,i.push(a>>>8&255),i.push(a&255),i=i.concat(Array.prototype.slice.call(n));let o=s.box(s.types.avcC,new Uint8Array([1,t[3],t[4],t[5],255,224|e.sps.length].concat(t).concat([e.pps.length]).concat(i))),l=e.width,d=e.height,c=e.pixelRatio[0],u=e.pixelRatio[1];return s.box(s.types.avc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,l>>8&255,l&255,d>>8&255,d&255,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),o,s.box(s.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),s.box(s.types.pasp,new Uint8Array([c>>24,c>>16&255,c>>8&255,c&255,u>>24,u>>16&255,u>>8&255,u&255])))}static esds(e){let t=e.config;return new Uint8Array([0,0,0,0,3,25,0,1,0,4,17,64,21,0,0,0,0,0,0,0,0,0,0,0,5,2,...t,6,1,2])}static audioStsd(e){let t=e.samplerate||0;return new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,e.channelCount||0,0,16,0,0,0,0,t>>8&255,t&255,0,0])}static mp4a(e){return s.box(s.types.mp4a,s.audioStsd(e),s.box(s.types.esds,s.esds(e)))}static mp3(e){return s.box(s.types[".mp3"],s.audioStsd(e))}static ac3(e){return s.box(s.types["ac-3"],s.audioStsd(e),s.box(s.types.dac3,e.config))}static stsd(e){let{segmentCodec:t}=e;if(e.type==="audio"){if(t==="aac")return s.box(s.types.stsd,s.STSD,s.mp4a(e));if(t==="ac3"&&e.config)return s.box(s.types.stsd,s.STSD,s.ac3(e));if(t==="mp3"&&e.codec==="mp3")return s.box(s.types.stsd,s.STSD,s.mp3(e))}else if(e.pps&&e.sps){if(t==="avc")return s.box(s.types.stsd,s.STSD,s.avc1(e));if(t==="hevc"&&e.vps)return s.box(s.types.stsd,s.STSD,s.hvc1(e))}else throw new Error("video track missing pps or sps");throw new Error(`unsupported ${e.type} segment codec (${t}/${e.codec})`)}static tkhd(e){let t=e.id,i=(e.duration||0)*(e.timescale||0),r=e.width||0,n=e.height||0,a=Math.floor(i/(Mi+1)),o=Math.floor(i%(Mi+1));return s.box(s.types.tkhd,new Uint8Array([1,0,0,7,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,t&255,0,0,0,0,a>>24,a>>16&255,a>>8&255,a&255,o>>24,o>>16&255,o>>8&255,o&255,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,r>>8&255,r&255,0,0,n>>8&255,n&255,0,0]))}static traf(e,t){let i=s.sdtp(e),r=e.id,n=Math.floor(t/(Mi+1)),a=Math.floor(t%(Mi+1));return s.box(s.types.traf,s.box(s.types.tfhd,new Uint8Array([0,0,0,0,r>>24,r>>16&255,r>>8&255,r&255])),s.box(s.types.tfdt,new Uint8Array([1,0,0,0,n>>24,n>>16&255,n>>8&255,n&255,a>>24,a>>16&255,a>>8&255,a&255])),s.trun(e,i.length+16+20+8+16+8+8),i)}static trak(e){return e.duration=e.duration||4294967295,s.box(s.types.trak,s.tkhd(e),s.mdia(e))}static trex(e){let t=e.id;return s.box(s.types.trex,new Uint8Array([0,0,0,0,t>>24,t>>16&255,t>>8&255,t&255,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))}static trun(e,t){let i=e.samples||[],r=i.length,n=12+16*r,a=new Uint8Array(n),o,l,d,c,u,h;for(t+=8+n,a.set([e.type==="video"?1:0,0,15,1,r>>>24&255,r>>>16&255,r>>>8&255,r&255,t>>>24&255,t>>>16&255,t>>>8&255,t&255],0),o=0;o<r;o++)l=i[o],d=l.duration,c=l.size,u=l.flags,h=l.cts,a.set([d>>>24&255,d>>>16&255,d>>>8&255,d&255,c>>>24&255,c>>>16&255,c>>>8&255,c&255,u.isLeading<<2|u.dependsOn,u.isDependedOn<<6|u.hasRedundancy<<4|u.paddingValue<<1|u.isNonSync,u.degradPrio&61440,u.degradPrio&15,h>>>24&255,h>>>16&255,h>>>8&255,h&255],12+16*o);return s.box(s.types.trun,a)}static initSegment(e){s.types||s.init();let t=s.moov(e);return Dt(s.FTYP,t)}static hvc1(e){let t=e.params,i=[e.vps,e.sps,e.pps],r=4,n=new Uint8Array([1,t.general_profile_space<<6|(t.general_tier_flag?32:0)|t.general_profile_idc,t.general_profile_compatibility_flags[0],t.general_profile_compatibility_flags[1],t.general_profile_compatibility_flags[2],t.general_profile_compatibility_flags[3],t.general_constraint_indicator_flags[0],t.general_constraint_indicator_flags[1],t.general_constraint_indicator_flags[2],t.general_constraint_indicator_flags[3],t.general_constraint_indicator_flags[4],t.general_constraint_indicator_flags[5],t.general_level_idc,240|t.min_spatial_segmentation_idc>>8,255&t.min_spatial_segmentation_idc,252|t.parallelismType,252|t.chroma_format_idc,248|t.bit_depth_luma_minus8,248|t.bit_depth_chroma_minus8,0,parseInt(t.frame_rate.fps),r-1|t.temporal_id_nested<<2|t.num_temporal_layers<<3|(t.frame_rate.fixed?64:0),i.length]),a=n.length;for(let m=0;m<i.length;m+=1){a+=3;for(let p=0;p<i[m].length;p+=1)a+=2+i[m][p].length;}let o=new Uint8Array(a);o.set(n,0),a=n.length;let l=i.length-1;for(let m=0;m<i.length;m+=1){o.set(new Uint8Array([32+m|(m===l?128:0),0,i[m].length]),a),a+=3;for(let p=0;p<i[m].length;p+=1)o.set(new Uint8Array([i[m][p].length>>8,i[m][p].length&255]),a),a+=2,o.set(i[m][p],a),a+=i[m][p].length;}let d=s.box(s.types.hvcC,o),c=e.width,u=e.height,h=e.pixelRatio[0],f=e.pixelRatio[1];return s.box(s.types.hvc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,c>>8&255,c&255,u>>8&255,u&255,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),d,s.box(s.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),s.box(s.types.pasp,new Uint8Array([h>>24,h>>16&255,h>>8&255,h&255,f>>24,f>>16&255,f>>8&255,f&255])))}};Ve.types=void 0;Ve.HDLR_TYPES=void 0;Ve.STTS=void 0;Ve.STSC=void 0;Ve.STCO=void 0;Ve.STSZ=void 0;Ve.VMHD=void 0;Ve.SMHD=void 0;Ve.STSD=void 0;Ve.FTYP=void 0;Ve.DINF=void 0;var vp=9e4;function Vu(s,e,t=1,i=false){let r=s*e*t;return i?Math.round(r):r}function Xy(s,e,t=1,i=false){return Vu(s,e,1/t,i)}function ln(s,e=false){return Vu(s,1e3,1/vp,e)}function Zy(s,e=1){return Vu(s,vp,1/e)}function eg(s){let{baseTime:e,timescale:t,trackId:i}=s;return `${e/t} (${e}/${t}) trackId: ${i}`}var Jy=10*1e3,eS=1024,tS=1152,iS=1536,Zs=null,ec=null;function tg(s,e,t,i){return {duration:e,size:t,cts:i,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:s?2:1,isNonSync:s?0:1}}}var rr=class extends ht{constructor(e,t,i,r){if(super("mp4-remuxer",r),this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.ISGenerated=false,this._initPTS=null,this._initDTS=null,this.nextVideoTs=null,this.nextAudioTs=null,this.videoSampleDuration=null,this.isAudioContiguous=false,this.isVideoContiguous=false,this.videoTrackConfig=void 0,this.observer=e,this.config=t,this.typeSupported=i,this.ISGenerated=false,Zs===null){let a=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Zs=a?parseInt(a[1]):0;}if(ec===null){let n=navigator.userAgent.match(/Safari\/(\d+)/i);ec=n?parseInt(n[1]):0;}}destroy(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null;}resetTimeStamp(e){let t=this._initPTS;(!t||!e||e.trackId!==t.trackId||e.baseTime!==t.baseTime||e.timescale!==t.timescale)&&this.log(`Reset initPTS: ${t&&eg(t)} > ${e&&eg(e)}`),this._initPTS=this._initDTS=e;}resetNextTimestamp(){this.log("reset next timestamp"),this.isVideoContiguous=false,this.isAudioContiguous=false;}resetInitSegment(){this.log("ISGenerated flag reset"),this.ISGenerated=false,this.videoTrackConfig=void 0;}getVideoStartPts(e){let t=false,i=e[0].pts,r=e.reduce((n,a)=>{let o=a.pts,l=o-n;return l<-4294967296&&(t=true,o=St(o,i),l=o-n),l>0?n:o},i);return t&&this.debug("PTS rollover detected"),r}remux(e,t,i,r,n,a,o,l){let d,c,u,h,f,m,p=n,E=n,v=e.pid>-1,T=t.pid>-1,S=t.samples.length,A=e.samples.length>0,b=o&&S>0||S>1;if((!v||A)&&(!T||b)||this.ISGenerated||o){if(this.ISGenerated){var I,k,R,L;let j=this.videoTrackConfig;(j&&(t.width!==j.width||t.height!==j.height||((I=t.pixelRatio)==null?void 0:I[0])!==((k=j.pixelRatio)==null?void 0:k[0])||((R=t.pixelRatio)==null?void 0:R[1])!==((L=j.pixelRatio)==null?void 0:L[1]))||!j&&b||this.nextAudioTs===null&&A)&&this.resetInitSegment();}this.ISGenerated||(u=this.generateIS(e,t,n,a));let M=this.isVideoContiguous,B=-1,K;if(b&&(B=sS(t.samples),!M&&this.config.forceKeyFrameOnDiscontinuity))if(m=true,B>0){this.warn(`Dropped ${B} out of ${S} video samples due to a missing keyframe`);let j=this.getVideoStartPts(t.samples);t.samples=t.samples.slice(B),t.dropped+=B,E+=(t.samples[0].pts-j)/t.inputTimeScale,K=E;}else B===-1&&(this.warn(`No keyframe found out of ${S} video samples`),m=false);if(this.ISGenerated){if(A&&b){let j=this.getVideoStartPts(t.samples),O=(St(e.samples[0].pts,j)-j)/t.inputTimeScale;p+=Math.max(0,O),E+=Math.max(0,-O);}if(A){if(e.samplerate||(this.warn("regenerate InitSegment as audio detected"),u=this.generateIS(e,t,n,a)),c=this.remuxAudio(e,p,this.isAudioContiguous,a,T||b||l===W.AUDIO?E:void 0),b){let j=c?c.endPTS-c.startPTS:0;t.inputTimeScale||(this.warn("regenerate InitSegment as video detected"),u=this.generateIS(e,t,n,a)),d=this.remuxVideo(t,E,M,j);}}else b&&(d=this.remuxVideo(t,E,M,0));d&&(d.firstKeyFrame=B,d.independent=B!==-1,d.firstKeyFramePTS=K);}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(i.samples.length&&(f=Tp(i,n,this._initPTS,this._initDTS)),r.samples.length&&(h=yp(r,n,this._initPTS))),{audio:c,video:d,initSegment:u,independent:m,text:h,id3:f}}computeInitPts(e,t,i,r){let n=Math.round(i*t),a=St(e,n);if(a<n+t)for(this.log(`Adjusting PTS for rollover in timeline near ${(n-a)/t} ${r}`);a<n+t;)a+=8589934592;return a-n}generateIS(e,t,i,r){let n=e.samples,a=t.samples,o=this.typeSupported,l={},d=this._initPTS,c=!d||r,u="audio/mp4",h,f,m,p=-1;if(c&&(h=f=1/0),e.config&&n.length){switch(e.timescale=e.samplerate,e.segmentCodec){case "mp3":o.mpeg?(u="audio/mpeg",e.codec=""):o.mp3&&(e.codec="mp3");break;case "ac3":e.codec="ac-3";break}l.audio={id:"audio",container:u,codec:e.codec,initSegment:e.segmentCodec==="mp3"&&o.mpeg?new Uint8Array(0):Ve.initSegment([e]),metadata:{channelCount:e.channelCount}},c&&(p=e.id,m=e.inputTimeScale,!d||m!==d.timescale?h=f=this.computeInitPts(n[0].pts,m,i,"audio"):c=false);}if(t.sps&&t.pps&&a.length){if(t.timescale=t.inputTimeScale,l.video={id:"main",container:"video/mp4",codec:t.codec,initSegment:Ve.initSegment([t]),metadata:{width:t.width,height:t.height}},c)if(p=t.id,m=t.inputTimeScale,!d||m!==d.timescale){let E=this.getVideoStartPts(a),v=St(a[0].dts,E),T=this.computeInitPts(v,m,i,"video"),S=this.computeInitPts(E,m,i,"video");f=Math.min(f,T),h=Math.min(h,S);}else c=false;this.videoTrackConfig={width:t.width,height:t.height,pixelRatio:t.pixelRatio};}if(Object.keys(l).length)return this.ISGenerated=true,c?(d&&this.warn(`Timestamps at playlist time: ${r?"":"~"}${i} ${h/m} != initPTS: ${d.baseTime/d.timescale} (${d.baseTime}/${d.timescale}) trackId: ${d.trackId}`),this.log(`Found initPTS at playlist time: ${i} offset: ${h/m} (${h}/${m}) trackId: ${p}`),this._initPTS={baseTime:h,timescale:m,trackId:p},this._initDTS={baseTime:f,timescale:m,trackId:p}):h=m=void 0,{tracks:l,initPTS:h,timescale:m,trackId:p}}remuxVideo(e,t,i,r){let n=e.inputTimeScale,a=e.samples,o=[],l=a.length,d=this._initPTS,c=d.baseTime*n/d.timescale,u=this.nextVideoTs,h=8,f=this.videoSampleDuration,m,p,E=Number.POSITIVE_INFINITY,v=Number.NEGATIVE_INFINITY,T=false;if(!i||u===null){let N=c+t*n,U=a[0].pts-St(a[0].dts,a[0].pts);Zs&&u!==null&&Math.abs(N-U-(u+c))<15e3?i=true:u=N-U-c;}let S=u+c;for(let N=0;N<l;N++){let U=a[N];U.pts=St(U.pts,S),U.dts=St(U.dts,S),U.dts<a[N>0?N-1:N].dts&&(T=true);}T&&a.sort(function(N,U){let te=N.dts-U.dts,ge=N.pts-U.pts;return te||ge}),m=a[0].dts,p=a[a.length-1].dts;let A=p-m,b=A?Math.round(A/(l-1)):f||e.inputTimeScale/30;if(i){let N=m-S,U=N>b,te=N<-1;if((U||te)&&(U?this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${ln(N,true)} ms (${N}dts) hole between fragments detected at ${t.toFixed(3)}`):this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${ln(-N,true)} ms (${N}dts) overlapping between fragments detected at ${t.toFixed(3)}`),!te||S>=a[0].pts||Zs)){m=S;let ge=a[0].pts-N;if(U)a[0].dts=m,a[0].pts=ge;else {let ie=true;for(let de=0;de<a.length&&!(a[de].dts>ge&&ie);de++){let Be=a[de].pts;if(a[de].dts-=N,a[de].pts-=N,de<a.length-1){let Fe=a[de+1].pts,tt=a[de].pts,ft=Fe<=tt,Kt=Fe<=Be;ie=ft==Kt;}}}this.log(`Video: Initial PTS/DTS adjusted: ${ln(ge,true)}/${ln(m,true)}, delta: ${ln(N,true)} ms`);}}m=Math.max(0,m);let D=0,I=0,k=m;for(let N=0;N<l;N++){let U=a[N],te=U.units,ge=te.length,ie=0;for(let de=0;de<ge;de++)ie+=te[de].data.length;I+=ie,D+=ge,U.length=ie,U.dts<k?(U.dts=k,k+=b/4|0||1):k=U.dts,E=Math.min(U.pts,E),v=Math.max(U.pts,v);}p=a[l-1].dts;let R=I+4*D+8,L;try{L=new Uint8Array(R);}catch(N){this.observer.emit(g.ERROR,g.ERROR,{type:z.MUX_ERROR,details:x.REMUX_ALLOC_ERROR,fatal:false,error:N,bytes:R,reason:`fail allocating video mdat ${R}`});return}let M=new DataView(L.buffer);M.setUint32(0,R),L.set(Ve.types.mdat,4);let B=false,K=Number.POSITIVE_INFINITY,j=Number.POSITIVE_INFINITY,V=Number.NEGATIVE_INFINITY,O=Number.NEGATIVE_INFINITY;for(let N=0;N<l;N++){let U=a[N],te=U.units,ge=0;for(let Be=0,Fe=te.length;Be<Fe;Be++){let tt=te[Be],ft=tt.data,Kt=tt.data.byteLength;M.setUint32(h,Kt),h+=4,L.set(ft,h),h+=Kt,ge+=4+Kt;}let ie;if(N<l-1)f=a[N+1].dts-U.dts,ie=a[N+1].pts-U.pts;else {let Be=this.config,Fe=N>0?U.dts-a[N-1].dts:b;if(ie=N>0?U.pts-a[N-1].pts:b,Be.stretchShortVideoTrack&&this.nextAudioTs!==null){let tt=Math.floor(Be.maxBufferHole*n),ft=(r?E+r*n:this.nextAudioTs+c)-U.pts;ft>tt?(f=ft-Fe,f<0?f=Fe:B=true,this.log(`It is approximately ${ft/90} ms to the next segment; using duration ${f/90} ms for the last video frame.`)):f=Fe;}else f=Fe;}let de=Math.round(U.pts-U.dts);K=Math.min(K,f),V=Math.max(V,f),j=Math.min(j,ie),O=Math.max(O,ie),o.push(tg(U.key,f,ge,de));}if(o.length){if(Zs){if(Zs<70){let N=o[0].flags;N.dependsOn=2,N.isNonSync=0;}}else if(ec&&O-j<V-K&&b/V<.025&&o[0].cts===0){this.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");let N=m;for(let U=0,te=o.length;U<te;U++){let ge=N+o[U].duration,ie=N+o[U].cts;if(U<te-1){let de=ge+o[U+1].cts;o[U].duration=de-ie;}else o[U].duration=U?o[U-1].duration:b;o[U].cts=0,N=ge;}}}f=B||!f?b:f;let Y=p+f;this.nextVideoTs=u=Y-c,this.videoSampleDuration=f,this.isVideoContiguous=true;let Q={data1:Ve.moof(e.sequenceNumber++,m,ye(e,{samples:o})),data2:L,startPTS:(E-c)/n,endPTS:(v+f-c)/n,startDTS:(m-c)/n,endDTS:u/n,type:"video",hasAudio:false,hasVideo:true,nb:o.length,dropped:e.dropped};return e.samples=[],e.dropped=0,Q}getSamplesPerFrame(e){switch(e.segmentCodec){case "mp3":return tS;case "ac3":return iS;default:return eS}}remuxAudio(e,t,i,r,n){let a=e.inputTimeScale,o=e.samplerate?e.samplerate:a,l=a/o,d=this.getSamplesPerFrame(e),c=d*l,u=this._initPTS,h=e.segmentCodec==="mp3"&&this.typeSupported.mpeg,f=[],m=n!==void 0,p=e.samples,E=h?0:8,v=this.nextAudioTs||-1,T=u.baseTime*a/u.timescale,S=T+t*a;if(this.isAudioContiguous=i=i||p.length&&v>0&&(r&&Math.abs(S-(v+T))<9e3||Math.abs(St(p[0].pts,S)-(v+T))<20*c),p.forEach(function(O){O.pts=St(O.pts,S);}),!i||v<0){let O=p.length;if(p=p.filter(Y=>Y.pts>=0),O!==p.length&&this.warn(`Removed ${p.length-O} of ${O} samples (initPTS ${T} / ${a})`),!p.length)return;n===0?v=0:r&&!m?v=Math.max(0,S-T):v=p[0].pts-T;}if(e.segmentCodec==="aac"){let O=this.config.maxAudioFramesDrift;for(let Y=0,$=v+T;Y<p.length;Y++){let q=p[Y],Q=q.pts,N=Q-$,U=Math.abs(1e3*N/a);if(N<=-O*c&&m)Y===0&&(this.warn(`Audio frame @ ${(Q/a).toFixed(3)}s overlaps marker by ${Math.round(1e3*N/a)} ms.`),this.nextAudioTs=v=Q-T,$=Q);else if(N>=O*c&&U<Jy&&m){let te=Math.round(N/c);for($=Q-te*c;$<0&&te&&c;)te--,$+=c;Y===0&&(this.nextAudioTs=v=$-T),this.warn(`Injecting ${te} audio frames @ ${(($-T)/a).toFixed(3)}s due to ${Math.round(1e3*N/a)} ms gap.`);for(let ge=0;ge<te;ge++){let ie=Hc.getSilentFrame(e.parsedCodec||e.manifestCodec||e.codec,e.channelCount);ie||(this.log("Unable to get silent frame for given audio codec; duplicating last frame instead."),ie=q.unit.subarray()),p.splice(Y,0,{unit:ie,pts:$}),$+=c,Y++;}}q.pts=$,$+=c;}}let A=null,b=null,D,I=0,k=p.length;for(;k--;)I+=p[k].unit.byteLength;for(let O=0,Y=p.length;O<Y;O++){let $=p[O],q=$.unit,Q=$.pts;if(b!==null){let U=f[O-1];U.duration=Math.round((Q-b)/l);}else if(i&&e.segmentCodec==="aac"&&(Q=v+T),A=Q,I>0){I+=E;try{D=new Uint8Array(I);}catch(U){this.observer.emit(g.ERROR,g.ERROR,{type:z.MUX_ERROR,details:x.REMUX_ALLOC_ERROR,fatal:false,error:U,bytes:I,reason:`fail allocating audio mdat ${I}`});return}h||(new DataView(D.buffer).setUint32(0,I),D.set(Ve.types.mdat,4));}else return;D.set(q,E);let N=q.byteLength;E+=N,f.push(tg(true,d,N,0)),b=Q;}let R=f.length;if(!R)return;let L=f[f.length-1];v=b-T,this.nextAudioTs=v+l*L.duration;let M=h?new Uint8Array(0):Ve.moof(e.sequenceNumber++,A/l,ye({},e,{samples:f}));e.samples=[];let B=(A-T)/a,K=v/a,V={data1:M,data2:D,startPTS:B,endPTS:K,startDTS:B,endDTS:K,type:"audio",hasAudio:true,hasVideo:false,nb:R};return this.isAudioContiguous=true,V}};function St(s,e){let t;if(e===null)return s;for(e<s?t=-8589934592:t=8589934592;Math.abs(s-e)>4294967296;)s+=t;return s}function sS(s){for(let e=0;e<s.length;e++)if(s[e].key)return e;return -1}function Tp(s,e,t,i){let r=s.samples.length;if(!r)return;let n=s.inputTimeScale;for(let o=0;o<r;o++){let l=s.samples[o];l.pts=St(l.pts-t.baseTime*n/t.timescale,e*n)/n,l.dts=St(l.dts-i.baseTime*n/i.timescale,e*n)/n;}let a=s.samples;return s.samples=[],{samples:a}}function yp(s,e,t){let i=s.samples.length;if(!i)return;let r=s.inputTimeScale;for(let a=0;a<i;a++){let o=s.samples[a];o.pts=St(o.pts-t.baseTime*r/t.timescale,e*r)/r;}s.samples.sort((a,o)=>a.pts-o.pts);let n=s.samples;return s.samples=[],{samples:n}}var Kc=class extends ht{constructor(e,t,i,r){super("passthrough-remuxer",r),this.emitInitSegment=false,this.audioCodec=void 0,this.videoCodec=void 0,this.initData=void 0,this.initPTS=null,this.initTracks=void 0,this.lastEndTime=null,this.isVideoContiguous=false;}destroy(){}resetTimeStamp(e){this.lastEndTime=null;let t=this.initPTS;t&&e&&t.baseTime===e.baseTime&&t.timescale===e.timescale||(this.initPTS=e);}resetNextTimestamp(){this.isVideoContiguous=false,this.lastEndTime=null;}resetInitSegment(e,t,i,r){this.audioCodec=t,this.videoCodec=i,this.generateInitSegment(e,r),this.emitInitSegment=true;}generateInitSegment(e,t){let{audioCodec:i,videoCodec:r}=this;if(!(e!=null&&e.byteLength)){this.initTracks=void 0,this.initData=void 0;return}let{audio:n,video:a}=this.initData=Dg(e);if(t)oT(e,t);else {let l=n||a;l!=null&&l.encrypted&&this.warn(`Init segment with encrypted track with has no key ("${l.codec}")!`);}n&&(i=ig(n,Se.AUDIO,this)),a&&(r=ig(a,Se.VIDEO,this));let o={};n&&a?o.audiovideo={container:"video/mp4",codec:i+","+r,supplemental:a.supplemental,encrypted:a.encrypted,initSegment:e,id:"main"}:n?o.audio={container:"audio/mp4",codec:i,encrypted:n.encrypted,initSegment:e,id:"audio"}:a?o.video={container:"video/mp4",codec:r,supplemental:a.supplemental,encrypted:a.encrypted,initSegment:e,id:"main"}:this.warn("initSegment does not contain moov or trak boxes."),this.initTracks=o;}remux(e,t,i,r,n,a){var o,l;let{initPTS:d,lastEndTime:c}=this,u={audio:void 0,video:void 0,text:r,id3:i,initSegment:void 0};G(c)||(c=this.lastEndTime=n||0);let h=t.samples;if(!h.length)return u;let f={initPTS:void 0,timescale:void 0,trackId:void 0},m=this.initData;if((o=m)!=null&&o.length||(this.generateInitSegment(h),m=this.initData),!((l=m)!=null&&l.length))return this.warn("Failed to generate initSegment."),u;this.emitInitSegment&&(f.tracks=this.initTracks,this.emitInitSegment=false);let p=dT(h,m,this),E=m.audio?p[m.audio.id]:null,v=m.video?p[m.video.id]:null,T=Io(v,1/0),S=Io(E,1/0),A=Io(v,0,true),b=Io(E,0,true),D=n,I=0,k=E&&(!v||!d&&S<T||d&&d.trackId===m.audio.id),R=k?E:v;if(R){let $=R.timescale,q=R.start-n*$,Q=k?m.audio.id:m.video.id;D=R.start/$,I=k?b-S:A-T,(a||!d)&&(rS(d,D,n,I)||$!==d.timescale)&&(d&&this.warn(`Timestamps at playlist time: ${a?"":"~"}${n} ${q/$} != initPTS: ${d.baseTime/d.timescale} (${d.baseTime}/${d.timescale}) trackId: ${d.trackId}`),this.log(`Found initPTS at playlist time: ${n} offset: ${D-n} (${q}/${$}) trackId: ${Q}`),d=null,f.initPTS=q,f.timescale=$,f.trackId=Q);}else this.warn(`No audio or video samples found for initPTS at playlist time: ${n}`);d?(f.initPTS=d.baseTime,f.timescale=d.timescale,f.trackId=d.trackId):((!f.timescale||f.trackId===void 0||f.initPTS===void 0)&&(this.warn("Could not set initPTS"),f.initPTS=D,f.timescale=1,f.trackId=-1),this.initPTS=d={baseTime:f.initPTS,timescale:f.timescale,trackId:f.trackId});let L=D-d.baseTime/d.timescale,M=L+I;I>0?this.lastEndTime=M:(this.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());let B=!!m.audio,K=!!m.video,j="";B&&(j+="audio"),K&&(j+="video");let V=(m.audio?m.audio.encrypted:false)||(m.video?m.video.encrypted:false),O={data1:h,startPTS:L,startDTS:L,endPTS:M,endDTS:M,type:j,hasAudio:B,hasVideo:K,nb:1,dropped:0,encrypted:V};u.audio=B&&!K?O:void 0,u.video=K?O:void 0;let Y=v?.sampleCount;if(Y){let $=v.keyFrameIndex,q=$!==-1;O.nb=Y,O.dropped=$===0||this.isVideoContiguous?0:q?$:Y,O.independent=q,O.firstKeyFrame=$,q&&v.keyFrameStart&&(O.firstKeyFramePTS=(v.keyFrameStart-d.baseTime)/d.timescale),this.isVideoContiguous||(u.independent=q),this.isVideoContiguous||(this.isVideoContiguous=q),O.dropped&&this.warn(`fmp4 does not start with IDR: firstIDR ${$}/${Y} dropped: ${O.dropped} start: ${O.firstKeyFramePTS||"NA"}`);}return u.initSegment=f,u.id3=Tp(i,n,d,d),r.samples.length&&(u.text=yp(r,n,d)),u}};function Io(s,e,t=false){return s?.start!==void 0?(s.start+(t?s.duration:0))/s.timescale:e}function rS(s,e,t,i){if(s===null)return true;let r=Math.max(i,1),n=e-s.baseTime/s.timescale;return Math.abs(n-t)>r}function ig(s,e,t){let i=s.codec;return i&&i.length>4?i:e===Se.AUDIO?i==="ec-3"||i==="ac-3"||i==="alac"?i:i==="fLaC"||i==="Opus"?Ho(i,false):(t.warn(`Unhandled audio codec "${i}" in mp4 MAP`),i||"mp4a"):(t.warn(`Unhandled video codec "${i}" in mp4 MAP`),i||"avc1")}var Ti;try{Ti=self.performance.now.bind(self.performance);}catch{Ti=Date.now;}var Fo=[{demux:Oc,remux:Kc},{demux:Bc,remux:rr},{demux:Mc,remux:rr},{demux:wc,remux:rr}];Fo.splice(2,0,{demux:Pc,remux:rr});var il=class{constructor(e,t,i,r,n,a){this.asyncResult=false,this.logger=void 0,this.observer=void 0,this.typeSupported=void 0,this.config=void 0,this.id=void 0,this.demuxer=void 0,this.remuxer=void 0,this.decrypter=void 0,this.probe=void 0,this.decryptionPromise=null,this.transmuxConfig=void 0,this.currentTransmuxState=void 0,this.observer=e,this.typeSupported=t,this.config=i,this.id=n,this.logger=a;}configure(e){this.transmuxConfig=e,this.decrypter&&this.decrypter.reset();}push(e,t,i,r){let n=i.transmuxing;n.executeStart=Ti();let a=new Uint8Array(e),{currentTransmuxState:o,transmuxConfig:l}=this;r&&(this.currentTransmuxState=r);let{contiguous:d,discontinuity:c,trackSwitch:u,accurateTimeOffset:h,timeOffset:f,initSegmentChange:m}=r||o,{audioCodec:p,videoCodec:E,defaultInitPts:v,duration:T,initSegmentData:S}=l,A=nS(a,t);if(A&&sr(A.method)){let k=this.getDecrypter(),R=Nu(A.method);if(k.isSync()){let L=k.softwareDecrypt(a,A.key.buffer,A.iv.buffer,R);if(i.part>-1){let B=k.flush();L=B&&B.buffer;}if(!L)return n.executeEnd=Ti(),tc(i);a=new Uint8Array(L);}else return this.asyncResult=true,this.decryptionPromise=k.webCryptoDecrypt(a,A.key.buffer,A.iv.buffer,R).then(L=>{let M=this.push(L,null,i);return this.decryptionPromise=null,M}),this.decryptionPromise}let b=this.needsProbing(c,u);if(b){let k=this.configureTransmuxer(a);if(k)return this.logger.warn(`[transmuxer] ${k.message}`),this.observer.emit(g.ERROR,g.ERROR,{type:z.MEDIA_ERROR,details:x.FRAG_PARSING_ERROR,fatal:false,error:k,reason:k.message}),n.executeEnd=Ti(),tc(i)}(c||u||m||b)&&this.resetInitSegment(S,p,E,T,t),(c||m||b)&&this.resetInitialTimestamp(v),d||this.resetContiguity();let D=this.transmux(a,A,f,h,i);this.asyncResult=_n(D);let I=this.currentTransmuxState;return I.contiguous=true,I.discontinuity=false,I.trackSwitch=false,n.executeEnd=Ti(),D}flush(e){let t=e.transmuxing;t.executeStart=Ti();let{decrypter:i,currentTransmuxState:r,decryptionPromise:n}=this;if(n)return this.asyncResult=true,n.then(()=>this.flush(e));let a=[],{timeOffset:o}=r;if(i){let u=i.flush();u&&a.push(this.push(u.buffer,null,e));}let{demuxer:l,remuxer:d}=this;if(!l||!d){t.executeEnd=Ti();let u=[tc(e)];return this.asyncResult?Promise.resolve(u):u}let c=l.flush(o);return _n(c)?(this.asyncResult=true,c.then(u=>(this.flushRemux(a,u,e),a))):(this.flushRemux(a,c,e),this.asyncResult?Promise.resolve(a):a)}flushRemux(e,t,i){let{audioTrack:r,videoTrack:n,id3Track:a,textTrack:o}=t,{accurateTimeOffset:l,timeOffset:d}=this.currentTransmuxState;this.logger.log(`[transmuxer.ts]: Flushed ${this.id} sn: ${i.sn}${i.part>-1?" part: "+i.part:""} of ${this.id===W.MAIN?"level":"track"} ${i.level}`);let c=this.remuxer.remux(r,n,a,o,d,l,true,this.id);e.push({remuxResult:c,chunkMeta:i}),i.transmuxing.executeEnd=Ti();}resetInitialTimestamp(e){let{demuxer:t,remuxer:i}=this;!t||!i||(t.resetTimeStamp(e),i.resetTimeStamp(e));}resetContiguity(){let{demuxer:e,remuxer:t}=this;!e||!t||(e.resetContiguity(),t.resetNextTimestamp());}resetInitSegment(e,t,i,r,n){let{demuxer:a,remuxer:o}=this;!a||!o||(a.resetInitSegment(e,t,i,r),o.resetInitSegment(e,t,i,n));}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0);}transmux(e,t,i,r,n){let a;return t&&t.method==="SAMPLE-AES"?a=this.transmuxSampleAes(e,t,i,r,n):a=this.transmuxUnencrypted(e,i,r,n),a}transmuxUnencrypted(e,t,i,r){let{audioTrack:n,videoTrack:a,id3Track:o,textTrack:l}=this.demuxer.demux(e,t,false,!this.config.progressive);return {remuxResult:this.remuxer.remux(n,a,o,l,t,i,false,this.id),chunkMeta:r}}transmuxSampleAes(e,t,i,r,n){return this.demuxer.demuxSampleAes(e,t,i).then(a=>({remuxResult:this.remuxer.remux(a.audioTrack,a.videoTrack,a.id3Track,a.textTrack,i,r,false,this.id),chunkMeta:n}))}configureTransmuxer(e){let{config:t,observer:i,typeSupported:r}=this,n;for(let u=0,h=Fo.length;u<h;u++){var a;if((a=Fo[u].demux)!=null&&a.probe(e,this.logger)){n=Fo[u];break}}if(!n)return new Error("Failed to find demuxer by probing fragment data");let o=this.demuxer,l=this.remuxer,d=n.remux,c=n.demux;(!l||!(l instanceof d))&&(this.remuxer=new d(i,t,r,this.logger)),(!o||!(o instanceof c))&&(this.demuxer=new c(i,t,r,this.logger),this.probe=c.probe);}needsProbing(e,t){return !this.demuxer||!this.remuxer||e||t}getDecrypter(){let e=this.decrypter;return e||(e=this.decrypter=new En(this.config)),e}};function nS(s,e){let t=null;return s.byteLength>0&&e?.key!=null&&e.iv!==null&&e.method!=null&&(t=e),t}var tc=s=>({remuxResult:{},chunkMeta:s});function _n(s){return "then"in s&&s.then instanceof Function}var Vc=class{constructor(e,t,i,r,n){this.audioCodec=void 0,this.videoCodec=void 0,this.initSegmentData=void 0,this.duration=void 0,this.defaultInitPts=void 0,this.audioCodec=e,this.videoCodec=t,this.initSegmentData=i,this.duration=r,this.defaultInitPts=n||null;}},Wc=class{constructor(e,t,i,r,n,a){this.discontinuity=void 0,this.contiguous=void 0,this.accurateTimeOffset=void 0,this.trackSwitch=void 0,this.timeOffset=void 0,this.initSegmentChange=void 0,this.discontinuity=e,this.contiguous=t,this.accurateTimeOffset=i,this.trackSwitch=r,this.timeOffset=n,this.initSegmentChange=a;}},sg=0,sl=class{constructor(e,t,i,r){this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=sg++,this.observer=void 0,this.frag=null,this.part=null,this.useWorker=void 0,this.workerContext=null,this.transmuxer=null,this.onTransmuxComplete=void 0,this.onFlush=void 0,this.onWorkerMessage=l=>{let d=l.data,c=this.hls;if(!(!c||!(d!=null&&d.event)||d.instanceNo!==this.instanceNo))switch(d.event){case "init":{var u;let h=(u=this.workerContext)==null?void 0:u.objectURL;h&&self.URL.revokeObjectURL(h);break}case "transmuxComplete":{this.handleTransmuxComplete(d.data);break}case "flush":{this.onFlush(d.data);break}case "workerLog":{c.logger[d.data.logType]&&c.logger[d.data.logType](d.data.message);break}default:{d.data=d.data||{},d.data.frag=this.frag,d.data.part=this.part,d.data.id=this.id,c.trigger(d.event,d.data);break}}},this.onWorkerError=l=>{if(!this.hls)return;let d=new Error(`${l.message} (${l.filename}:${l.lineno})`);this.hls.config.enableWorker=false,this.hls.logger.warn(`Error in "${this.id}" Web Worker, fallback to inline`),this.hls.trigger(g.ERROR,{type:z.OTHER_ERROR,details:x.INTERNAL_EXCEPTION,fatal:false,event:"demuxerWorker",error:d});};let n=e.config;this.hls=e,this.id=t,this.useWorker=!!n.enableWorker,this.onTransmuxComplete=i,this.onFlush=r;let a=(l,d)=>{d=d||{},d.frag=this.frag||void 0,l===g.ERROR&&(d=d,d.parent=this.id,d.part=this.part,this.error=d.error),this.hls.trigger(l,d);};this.observer=new Bu,this.observer.on(g.FRAG_DECRYPTED,a),this.observer.on(g.ERROR,a);let o=ym(n.preferManagedMediaSource);if(this.useWorker&&typeof Worker<"u"){let l=this.hls.logger;if(n.workerPath||yy()){try{n.workerPath?(l.log(`loading Web Worker ${n.workerPath} for "${t}"`),this.workerContext=Ay(n.workerPath)):(l.log(`injecting Web Worker for "${t}"`),this.workerContext=Sy());let{worker:c}=this.workerContext;c.addEventListener("message",this.onWorkerMessage),c.addEventListener("error",this.onWorkerError),c.postMessage({instanceNo:this.instanceNo,cmd:"init",typeSupported:o,id:t,config:Ae(n)});}catch(c){l.warn(`Error setting up "${t}" Web Worker, fallback to inline`,c),this.terminateWorker(),this.error=null,this.transmuxer=new il(this.observer,o,n,"",t,e.logger);}return}}this.transmuxer=new il(this.observer,o,n,"",t,e.logger);}reset(){if(this.frag=null,this.part=null,this.workerContext){let e=this.instanceNo;this.instanceNo=sg++;let t=this.hls.config,i=ym(t.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:e,typeSupported:i,id:this.id,config:Ae(t)});}}terminateWorker(){if(this.workerContext){let{worker:e}=this.workerContext;this.workerContext=null,e.removeEventListener("message",this.onWorkerMessage),e.removeEventListener("error",this.onWorkerError),by(this.hls.config.workerPath);}}destroy(){if(this.workerContext)this.terminateWorker(),this.onWorkerMessage=this.onWorkerError=null;else {let t=this.transmuxer;t&&(t.destroy(),this.transmuxer=null);}let e=this.observer;e&&e.removeAllListeners(),this.frag=null,this.part=null,this.observer=null,this.hls=null;}push(e,t,i,r,n,a,o,l,d,c){var u,h;d.transmuxing.start=self.performance.now();let{instanceNo:f,transmuxer:m}=this,p=a?a.start:n.start,E=n.decryptdata,v=this.frag,T=!(v&&n.cc===v.cc),S=!(v&&d.level===v.level),A=v?d.sn-v.sn:-1,b=this.part?d.part-this.part.index:-1,D=A===0&&d.id>1&&d.id===v?.stats.chunkCount,I=!S&&(A===1||A===0&&(b===1||D&&b<=0)),k=self.performance.now();(S||A||n.stats.parsing.start===0)&&(n.stats.parsing.start=k),a&&(b||!I)&&(a.stats.parsing.start=k);let R=!(v&&((u=n.initSegment)==null?void 0:u.url)===((h=v.initSegment)==null?void 0:h.url)),L=new Wc(T,I,l,S,p,R);if(!I||T||R){this.hls.logger.log(`[transmuxer-interface]: Starting new transmux session for ${n.type} sn: ${d.sn}${d.part>-1?" part: "+d.part:""} ${this.id===W.MAIN?"level":"track"}: ${d.level} id: ${d.id}
1365
1365
  discontinuity: ${T}
1366
1366
  trackSwitch: ${S}
1367
1367
  contiguous: ${I}
1368
1368
  accurateTimeOffset: ${l}
1369
1369
  timeOffset: ${p}
1370
- initSegmentChange: ${R}`);let M=new Vc(i,r,t,o,c);this.configureTransmuxer(M);}if(this.frag=n,this.part=a,this.workerContext)this.workerContext.worker.postMessage({instanceNo:f,cmd:"demux",data:e,decryptdata:E,chunkMeta:d,state:L},e instanceof ArrayBuffer?[e]:[]);else if(m){let M=m.push(e,E,d,L);_n(M)?M.then(B=>{this.handleTransmuxComplete(B);}).catch(B=>{this.transmuxerError(B,d,"transmuxer-interface push error");}):this.handleTransmuxComplete(M);}}flush(e){e.transmuxing.start=self.performance.now();let{instanceNo:t,transmuxer:i}=this;if(this.workerContext)this.workerContext.worker.postMessage({instanceNo:t,cmd:"flush",chunkMeta:e});else if(i){let r=i.flush(e);_n(r)?r.then(n=>{this.handleFlushResult(n,e);}).catch(n=>{this.transmuxerError(n,e,"transmuxer-interface flush error");}):this.handleFlushResult(r,e);}}transmuxerError(e,t,i){this.hls&&(this.error=e,this.hls.trigger(g.ERROR,{type:z.MEDIA_ERROR,details:x.FRAG_PARSING_ERROR,chunkMeta:t,frag:this.frag||void 0,part:this.part||void 0,fatal:false,error:e,err:e,reason:i}));}handleFlushResult(e,t){e.forEach(i=>{this.handleTransmuxComplete(i);}),this.onFlush(t);}configureTransmuxer(e){let{instanceNo:t,transmuxer:i}=this;this.workerContext?this.workerContext.worker.postMessage({instanceNo:t,cmd:"configure",config:e}):i&&i.configure(e);}handleTransmuxComplete(e){e.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(e);}},sg=100,Yc=class extends yn{constructor(e,t,i){super(e,t,i,"audio-stream-controller",W.AUDIO),this.mainAnchor=null,this.mainFragLoading=null,this.audioOnly=false,this.bufferedTrack=null,this.switchingTrack=null,this.trackId=-1,this.waitingData=null,this.mainDetails=null,this.flushing=false,this.bufferFlushed=false,this.cachedTrackLoadedData=null,this.registerListeners();}onHandlerDestroying(){this.unregisterListeners(),super.onHandlerDestroying(),this.resetItem();}resetItem(){this.mainDetails=this.mainAnchor=this.mainFragLoading=this.bufferedTrack=this.switchingTrack=this.waitingData=this.cachedTrackLoadedData=null;}registerListeners(){super.registerListeners();let{hls:e}=this;e.on(g.LEVEL_LOADED,this.onLevelLoaded,this),e.on(g.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.on(g.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(g.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(g.BUFFER_RESET,this.onBufferReset,this),e.on(g.BUFFER_CREATED,this.onBufferCreated,this),e.on(g.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(g.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(g.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(g.FRAG_LOADING,this.onFragLoading,this),e.on(g.FRAG_BUFFERED,this.onFragBuffered,this);}unregisterListeners(){let{hls:e}=this;e&&(super.unregisterListeners(),e.off(g.LEVEL_LOADED,this.onLevelLoaded,this),e.off(g.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.off(g.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(g.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(g.BUFFER_RESET,this.onBufferReset,this),e.off(g.BUFFER_CREATED,this.onBufferCreated,this),e.off(g.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(g.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(g.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(g.FRAG_LOADING,this.onFragLoading,this),e.off(g.FRAG_BUFFERED,this.onFragBuffered,this));}onInitPtsFound(e,{frag:t,id:i,initPTS:r,timescale:n,trackId:a}){if(i===W.MAIN){let o=t.cc,l=this.fragCurrent;if(this.initPTS[o]={baseTime:r,timescale:n,trackId:a},this.log(`InitPTS for cc: ${o} found from main: ${r/n} (${r}/${n}) trackId: ${a}`),this.mainAnchor=t,this.state===C.WAITING_INIT_PTS){let d=this.waitingData;(!d&&!this.loadingParts||d&&d.frag.cc!==o)&&this.syncWithAnchor(t,d?.frag);}else !this.hls.hasEnoughToStart&&l&&l.cc!==o?(l.abortRequests(),this.syncWithAnchor(t,l)):this.state===C.IDLE&&this.tick();}}getLoadPosition(){return !this.startFragRequested&&this.nextLoadPosition>=0?this.nextLoadPosition:super.getLoadPosition()}syncWithAnchor(e,t){var i;let r=((i=this.mainFragLoading)==null?void 0:i.frag)||null;if(t&&r?.cc===t.cc)return;let n=(r||e).cc,a=this.getLevelDetails(),o=this.getLoadPosition(),l=$g(a,n,o);l&&(this.log(`Syncing with main frag at ${l.start} cc ${l.cc}`),this.startFragRequested=false,this.nextLoadPosition=l.start,this.resetLoadingState(),this.state===C.IDLE&&this.doTickIdle());}startLoad(e,t){if(!this.levels){this.startPosition=e,this.state=C.STOPPED;return}let i=this.lastCurrentTime;this.stopLoad(),this.setInterval(sg),i>0&&e===-1?(this.log(`Override startPosition with lastCurrentTime @${i.toFixed(3)}`),e=i,this.state=C.IDLE):this.state=C.WAITING_TRACK,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick();}doTick(){switch(this.state){case C.IDLE:this.doTickIdle();break;case C.WAITING_TRACK:{let{levels:e,trackId:t}=this,i=e?.[t],r=i?.details;if(r&&!this.waitForLive(i)){if(this.waitForCdnTuneIn(r))break;this.state=C.WAITING_INIT_PTS;}break}case C.FRAG_LOADING_WAITING_RETRY:{this.checkRetryDate();break}case C.WAITING_INIT_PTS:{let e=this.waitingData;if(e){let{frag:t,part:i,cache:r,complete:n}=e,a=this.mainAnchor;if(this.initPTS[t.cc]!==void 0){this.waitingData=null,this.state=C.FRAG_LOADING;let o=r.flush().buffer,l={frag:t,part:i,payload:o,networkDetails:null};this._handleFragmentLoadProgress(l),n&&super._handleFragmentLoadComplete(l);}else a&&a.cc!==e.frag.cc&&this.syncWithAnchor(a,e.frag);}else this.state=C.IDLE;}}this.onTickEnd();}resetLoadingState(){let e=this.waitingData;e&&(this.fragmentTracker.removeFragment(e.frag),this.waitingData=null),super.resetLoadingState();}onTickEnd(){let{media:e}=this;e!=null&&e.readyState&&(this.lastCurrentTime=e.currentTime);}doTickIdle(){var e;let{hls:t,levels:i,media:r,trackId:n}=this,a=t.config;if(!this.buffering||!r&&!this.primaryPrefetch&&(this.startFragRequested||!a.startFragPrefetch)||!(i!=null&&i[n]))return;let o=i[n],l=o.details;if(!l||this.waitForLive(o)||this.waitForCdnTuneIn(l)){this.state=C.WAITING_TRACK,this.startFragRequested=false;return}let d=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&d&&(this.bufferFlushed=false,this.afterBufferFlushed(d,Se.AUDIO,W.AUDIO));let c=this.getFwdBufferInfo(d,W.AUDIO);if(c===null)return;if(!this.switchingTrack&&this._streamEnded(c,l)){t.trigger(g.BUFFER_EOS,{type:"audio"}),this.state=C.ENDED;return}let u=c.len,h=t.maxBufferLength,f=l.fragments,m=f[0].start,p=this.getLoadPosition(),E=this.flushing?p:c.end;if(this.switchingTrack&&r){let S=p;l.PTSKnown&&S<m&&(c.end>m||c.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),r.currentTime=m+.05);}if(u>=h&&!this.switchingTrack&&E<f[f.length-1].start)return;let v=this.getNextFragment(E,l);if(v&&this.isLoopLoading(v,E)&&(v=this.getNextFragmentLoopLoading(v,l,c,W.MAIN,h)),!v){this.bufferFlushed=true;return}let T=((e=this.mainFragLoading)==null?void 0:e.frag)||null;if(!this.audioOnly&&this.startFragRequested&&T&&Ue(v)&&!v.endList&&(!l.live||!this.loadingParts&&E<this.hls.liveSyncPosition)&&(this.fragmentTracker.getState(T)===Ke.OK&&(this.mainFragLoading=T=null),T&&Ue(T))){if(v.start>T.end){let A=this.fragmentTracker.getFragAtPos(E,W.MAIN);A&&A.end>T.end&&(T=A,this.mainFragLoading={frag:A,targetBufferTime:null});}if(v.start>T.end)return}this.loadFragment(v,o,E);}onMediaDetaching(e,t){this.bufferFlushed=this.flushing=false,super.onMediaDetaching(e,t);}onAudioTracksUpdated(e,{audioTracks:t}){this.resetTransmuxer(),this.levels=t.map(i=>new ds(i));}onAudioTrackSwitching(e,t){let i=!!t.url;this.trackId=t.id;let{fragCurrent:r}=this;r&&(r.abortRequests(),this.removeUnbufferedFrags(r.start)),this.resetLoadingState(),i?(this.switchingTrack=t,this.flushAudioIfNeeded(t),this.state!==C.STOPPED&&(this.setInterval(sg),this.state=C.IDLE,this.tick())):(this.resetTransmuxer(),this.switchingTrack=null,this.bufferedTrack=t,this.clearInterval());}onManifestLoading(){super.onManifestLoading(),this.bufferFlushed=this.flushing=this.audioOnly=false,this.resetItem(),this.trackId=-1;}onLevelLoaded(e,t){this.mainDetails=t.details;let i=this.cachedTrackLoadedData;i&&(this.cachedTrackLoadedData=null,this.onAudioTrackLoaded(g.AUDIO_TRACK_LOADED,i));}onAudioTrackLoaded(e,t){var i;let{levels:r}=this,{details:n,id:a,groupId:o,track:l}=t;if(!r){this.warn(`Audio tracks reset while loading track ${a} "${l.name}" of "${o}"`);return}let d=this.mainDetails;if(!d||n.endCC>d.endCC||d.expired){this.cachedTrackLoadedData=t,this.state!==C.STOPPED&&(this.state=C.WAITING_TRACK);return}this.cachedTrackLoadedData=null,this.log(`Audio track ${a} "${l.name}" of "${o}" loaded [${n.startSN},${n.endSN}]${n.lastPartSn?`[part-${n.lastPartSn}-${n.lastPartIndex}]`:""},duration:${n.totalduration}`);let c=r[a],u=0;if(n.live||(i=c.details)!=null&&i.live){if(this.checkLiveUpdate(n),n.deltaUpdateFailed)return;if(c.details){var h;u=this.alignPlaylists(n,c.details,(h=this.levelLastLoaded)==null?void 0:h.details);}n.alignedSliding||(ip(n,d),n.alignedSliding||Zo(n,d),u=n.fragmentStart);}c.details=n,this.levelLastLoaded=c,this.startFragRequested||this.setStartPosition(d,u),this.hls.trigger(g.AUDIO_TRACK_UPDATED,{details:n,id:a,groupId:t.groupId}),this.state===C.WAITING_TRACK&&!this.waitForCdnTuneIn(n)&&(this.state=C.IDLE),this.tick();}_handleFragmentLoadProgress(e){var t;let i=e.frag,{part:r,payload:n}=e,{config:a,trackId:o,levels:l}=this;if(!l){this.warn(`Audio tracks were reset while fragment load was in progress. Fragment ${i.sn} of level ${i.level} will not be buffered`);return}let d=l[o];if(!d){this.warn("Audio track is undefined on fragment load progress");return}let c=d.details;if(!c){this.warn("Audio track details undefined on fragment load progress"),this.removeUnbufferedFrags(i.start);return}let u=a.defaultAudioCodec||d.audioCodec||"mp4a.40.2",h=this.transmuxer;h||(h=this.transmuxer=new sl(this.hls,W.AUDIO,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));let f=this.initPTS[i.cc],m=(t=i.initSegment)==null?void 0:t.data;if(f!==void 0){let E=r?r.index:-1,v=E!==-1,T=new vn(i.level,i.sn,i.stats.chunkCount,n.byteLength,E,v);h.push(n,m,u,"",i,r,c.totalduration,false,T,f);}else {this.log(`Unknown video PTS for cc ${i.cc}, waiting for video PTS before demuxing audio frag ${i.sn} of [${c.startSN} ,${c.endSN}],track ${o}`);let{cache:p}=this.waitingData=this.waitingData||{frag:i,part:r,cache:new Jo,complete:false};p.push(new Uint8Array(n)),this.state!==C.STOPPED&&(this.state=C.WAITING_INIT_PTS);}}_handleFragmentLoadComplete(e){if(this.waitingData){this.waitingData.complete=true;return}super._handleFragmentLoadComplete(e);}onBufferReset(){this.mediaBuffer=null;}onBufferCreated(e,t){this.bufferFlushed=this.flushing=false;let i=t.tracks.audio;i&&(this.mediaBuffer=i.buffer||null);}onFragLoading(e,t){!this.audioOnly&&t.frag.type===W.MAIN&&Ue(t.frag)&&(this.mainFragLoading=t,this.state===C.IDLE&&this.tick());}onFragBuffered(e,t){let{frag:i,part:r}=t;if(i.type!==W.AUDIO){!this.audioOnly&&i.type===W.MAIN&&!i.elementaryStreams.video&&!i.elementaryStreams.audiovideo&&(this.audioOnly=true,this.mainFragLoading=null);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}, audioSwitch: ${this.switchingTrack?this.switchingTrack.name:"false"}`);return}if(Ue(i)){this.fragPrevious=i;let n=this.switchingTrack;n&&(this.bufferedTrack=n,this.switchingTrack=null,this.hls.trigger(g.AUDIO_TRACK_SWITCHED,ve({},n)));}this.fragBufferedComplete(i,r),this.media&&this.tick();}onError(e,t){var i;if(t.fatal){this.state=C.ERROR;return}switch(t.details){case x.FRAG_GAP:case x.FRAG_PARSING_ERROR:case x.FRAG_DECRYPT_ERROR:case x.FRAG_LOAD_ERROR:case x.FRAG_LOAD_TIMEOUT:case x.KEY_LOAD_ERROR:case x.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(W.AUDIO,t);break;case x.AUDIO_TRACK_LOAD_ERROR:case x.AUDIO_TRACK_LOAD_TIMEOUT:case x.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===C.WAITING_TRACK&&((i=t.context)==null?void 0:i.type)===ce.AUDIO_TRACK&&(this.state=C.IDLE);break;case x.BUFFER_ADD_CODEC_ERROR:case x.BUFFER_APPEND_ERROR:if(t.parent!=="audio")return;this.reduceLengthAndFlushBuffer(t)||this.resetLoadingState();break;case x.BUFFER_FULL_ERROR:if(t.parent!=="audio")return;this.reduceLengthAndFlushBuffer(t)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case x.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}onBufferFlushing(e,{type:t}){t!==Se.VIDEO&&(this.flushing=true);}onBufferFlushed(e,{type:t}){if(t!==Se.VIDEO){this.flushing=false,this.bufferFlushed=true,this.state===C.ENDED&&(this.state=C.IDLE);let i=this.mediaBuffer||this.media;i&&(this.afterBufferFlushed(i,t,W.AUDIO),this.tick());}}_handleTransmuxComplete(e){var t;let i="audio",{hls:r}=this,{remuxResult:n,chunkMeta:a}=e,o=this.getCurrentContext(a);if(!o){this.resetWhenMissingContext(a);return}let{frag:l,part:d,level:c}=o,{details:u}=c,{audio:h,text:f,id3:m,initSegment:p}=n;if(this.fragContextChanged(l)||!u){this.fragmentTracker.removeFragment(l);return}if(this.state=C.PARSING,this.switchingTrack&&h&&this.completeAudioSwitch(this.switchingTrack),p!=null&&p.tracks){let E=l.initSegment||l;if(this.unhandledEncryptionError(p,l))return;this._bufferInitSegment(c,p.tracks,E,a),r.trigger(g.FRAG_PARSING_INIT_SEGMENT,{frag:E,id:i,tracks:p.tracks});}if(h){let{startPTS:E,endPTS:v,startDTS:T,endDTS:S}=h;d&&(d.elementaryStreams[Se.AUDIO]={startPTS:E,endPTS:v,startDTS:T,endDTS:S}),l.setElementaryStreamInfo(Se.AUDIO,E,v,T,S),this.bufferFragmentData(h,l,d,a);}if(m!=null&&(t=m.samples)!=null&&t.length){let E=ye({id:i,frag:l,details:u},m);r.trigger(g.FRAG_PARSING_METADATA,E);}if(f){let E=ye({id:i,frag:l,details:u},f);r.trigger(g.FRAG_PARSING_USERDATA,E);}}_bufferInitSegment(e,t,i,r){if(this.state!==C.PARSING||(t.video&&delete t.video,t.audiovideo&&delete t.audiovideo,!t.audio))return;let n=t.audio;n.id=W.AUDIO;let a=e.audioCodec;this.log(`Init audio buffer, container:${n.container}, codecs[level/parsed]=[${a}/${n.codec}]`),a&&a.split(",").length===1&&(n.levelCodec=a),this.hls.trigger(g.BUFFER_CODECS,t);let o=n.initSegment;if(o!=null&&o.byteLength){let l={type:"audio",frag:i,part:null,chunkMeta:r,parent:i.type,data:o};this.hls.trigger(g.BUFFER_APPENDING,l);}this.tickImmediate();}loadFragment(e,t,i){let r=this.fragmentTracker.getState(e);if(this.switchingTrack||r===Ke.NOT_LOADED||r===Ke.PARTIAL){var n;if(!Ue(e))this._loadInitSegment(e,t);else if((n=t.details)!=null&&n.live&&!this.initPTS[e.cc]){this.log(`Waiting for video PTS in continuity counter ${e.cc} of live stream before loading audio fragment ${e.sn} of level ${this.trackId}`),this.state=C.WAITING_INIT_PTS;let a=this.mainDetails;a&&a.fragmentStart!==t.details.fragmentStart&&Zo(t.details,a);}else super.loadFragment(e,t,i);}else this.clearTrackerIfNeeded(e);}flushAudioIfNeeded(e){if(this.media&&this.bufferedTrack){let{name:t,lang:i,assocLang:r,characteristics:n,audioCodec:a,channels:o}=this.bufferedTrack;os({name:t,lang:i,assocLang:r,characteristics:n,audioCodec:a,channels:o},e,ns)||(Wo(e.url,this.hls)?(this.log("Switching audio track : flushing all audio"),super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"),this.bufferedTrack=null):this.bufferedTrack=e);}}completeAudioSwitch(e){let{hls:t}=this;this.flushAudioIfNeeded(e),this.bufferedTrack=e,this.switchingTrack=null,t.trigger(g.AUDIO_TRACK_SWITCHED,ve({},e));}},In=class extends ht{constructor(e,t){super(t,e.logger),this.hls=void 0,this.canLoad=false,this.timer=-1,this.hls=e;}destroy(){this.clearTimer(),this.hls=this.log=this.warn=null;}clearTimer(){this.timer!==-1&&(self.clearTimeout(this.timer),this.timer=-1);}startLoad(){this.canLoad=true,this.loadPlaylist();}stopLoad(){this.canLoad=false,this.clearTimer();}switchParams(e,t,i){let r=t?.renditionReports;if(r){let n=-1;for(let a=0;a<r.length;a++){let o=r[a],l;try{l=new self.URL(o.URI,t.url).href;}catch(d){this.warn(`Could not construct new URL for Rendition Report: ${d}`),l=o.URI||"";}if(l===e){n=a;break}else l===e.substring(0,l.length)&&(n=a);}if(n!==-1){let a=r[n],o=parseInt(a["LAST-MSN"])||t.lastPartSn,l=parseInt(a["LAST-PART"])||t.lastPartIndex;if(this.hls.config.lowLatencyMode){let c=Math.min(t.age-t.partTarget,t.targetduration);l>=0&&c>t.partTarget&&(l+=1);}let d=i&&ym(i);return new Vo(o,l>=0?l:void 0,d)}}}loadPlaylist(e){this.clearTimer();}loadingPlaylist(e,t){this.clearTimer();}shouldLoadPlaylist(e){return this.canLoad&&!!e&&!!e.url&&(!e.details||e.details.live)}getUrlWithDirectives(e,t){if(t)try{return t.addDirectives(e)}catch(i){this.warn(`Could not construct new URL with HLS Delivery Directives: ${i}`);}return e}playlistLoaded(e,t,i){let{details:r,stats:n}=t,a=self.performance.now(),o=n.loading.first?Math.max(0,a-n.loading.first):0;r.advancedDateTime=Date.now()-o;let l=this.hls.config.timelineOffset;if(l!==r.appliedTimelineOffset){let c=Math.max(l||0,0);r.appliedTimelineOffset=c,r.fragments.forEach(u=>{u.setStart(u.playlistOffset+c);});}if(r.live||i!=null&&i.live){let c="levelInfo"in t?t.levelInfo:t.track;if(r.reloaded(i),i&&r.fragments.length>0){ly(i,r,this);let T=r.playlistParsingError;if(T){this.warn(T);let S=this.hls;if(!S.config.ignorePlaylistParsingErrors){var d;let{networkDetails:A}=t;S.trigger(g.ERROR,{type:z.NETWORK_ERROR,details:x.LEVEL_PARSING_ERROR,fatal:false,url:r.url,error:T,reason:T.message,level:t.level||void 0,parent:(d=r.fragments[0])==null?void 0:d.type,networkDetails:A,stats:n});return}r.playlistParsingError=null;}}r.requestScheduled===-1&&(r.requestScheduled=n.loading.start);let u=this.hls.mainForwardBufferInfo,h=u?u.end-u.len:0,f=(r.edge-h)*1e3,m=Xg(r,f);if(r.requestScheduled+m<a?r.requestScheduled=a:r.requestScheduled+=m,this.log(`live playlist ${e} ${r.advanced?"REFRESHED "+r.lastPartSn+"-"+r.lastPartIndex:r.updated?"UPDATED":"MISSED"}`),!this.canLoad||!r.live)return;let p,E,v;if(r.canBlockReload&&r.endSN&&r.advanced){let T=this.hls.config.lowLatencyMode,S=r.lastPartSn,A=r.endSN,b=r.lastPartIndex,D=b!==-1,I=S===A;D?I?(E=A+1,v=T?0:b):(E=S,v=T?b+1:r.maxPartIndex):E=A+1;let k=r.age,R=k+r.ageHeader,L=Math.min(R-r.partTarget,r.targetduration*1.5);if(L>0){if(R>r.targetduration*3)this.log(`Playlist last advanced ${k.toFixed(2)}s ago. Omitting segment and part directives.`),E=void 0,v=void 0;else if(i!=null&&i.tuneInGoal&&R-r.partTarget>i.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${i.tuneInGoal} to: ${L} with playlist age: ${r.age}`),L=0;else {let M=Math.floor(L/r.targetduration);if(E+=M,v!==void 0){let B=Math.round(L%r.targetduration/r.partTarget);v+=B;}this.log(`CDN Tune-in age: ${r.ageHeader}s last advanced ${k.toFixed(2)}s goal: ${L} skip sn ${M} to part ${v}`);}r.tuneInGoal=L;}if(p=this.getDeliveryDirectives(r,t.deliveryDirectives,E,v),T||!I){r.requestScheduled=a,this.loadingPlaylist(c,p);return}}else (r.canBlockReload||r.canSkipUntil)&&(p=this.getDeliveryDirectives(r,t.deliveryDirectives,E,v));p&&E!==void 0&&r.canBlockReload&&(r.requestScheduled=n.loading.first+Math.max(m-o*2,m/2)),this.scheduleLoading(c,p,r);}else this.clearTimer();}scheduleLoading(e,t,i){let r=i||e.details;if(!r){this.loadingPlaylist(e,t);return}let n=self.performance.now(),a=r.requestScheduled;if(n>=a){this.loadingPlaylist(e,t);return}let o=a-n;this.log(`reload live playlist ${e.name||e.bitrate+"bps"} in ${Math.round(o)} ms`),this.clearTimer(),this.timer=self.setTimeout(()=>this.loadingPlaylist(e,t),o);}getDeliveryDirectives(e,t,i,r){let n=ym(e);return t!=null&&t.skip&&e.deltaUpdateFailed&&(i=t.msn,r=t.part,n=wo.No),new Vo(i,r,n)}checkRetry(e){let t=e.details,i=Yo(e),r=e.errorAction,{action:n,retryCount:a=0,retryConfig:o}=r||{},l=!!r&&!!o&&(n===ze.RetryRequest||!r.resolved&&n===ze.SendAlternateToPenaltyBox);if(l){var d;if(a>=o.maxNumRetry)return false;if(i&&(d=e.context)!=null&&d.deliveryDirectives)this.warn(`Retrying playlist loading ${a+1}/${o.maxNumRetry} after "${t}" without delivery-directives`),this.loadPlaylist();else {let c=Fu(o,a);this.clearTimer(),this.timer=self.setTimeout(()=>this.loadPlaylist(),c),this.warn(`Retrying playlist loading ${a+1}/${o.maxNumRetry} after "${t}" in ${c}ms`);}e.levelRetry=true,r.resolved=true;}return l}};function yp(s,e){if(s.length!==e.length)return false;for(let t=0;t<s.length;t++)if(!Ln(s[t].attrs,e[t].attrs))return false;return true}function Ln(s,e,t){let i=s["STABLE-RENDITION-ID"];return i&&!t?i===e["STABLE-RENDITION-ID"]:!(t||["LANGUAGE","NAME","CHARACTERISTICS","AUTOSELECT","DEFAULT","FORCED","ASSOC-LANGUAGE"]).some(r=>s[r]!==e[r])}function qc(s,e){return e.label.toLowerCase()===s.name.toLowerCase()&&(!e.language||e.language.toLowerCase()===(s.lang||"").toLowerCase())}var jc=class extends In{constructor(e){super(e,"audio-track-controller"),this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=true,this.registerListeners();}registerListeners(){let{hls:e}=this;e.on(g.MANIFEST_LOADING,this.onManifestLoading,this),e.on(g.MANIFEST_PARSED,this.onManifestParsed,this),e.on(g.LEVEL_LOADING,this.onLevelLoading,this),e.on(g.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(g.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(g.ERROR,this.onError,this);}unregisterListeners(){let{hls:e}=this;e.off(g.MANIFEST_LOADING,this.onManifestLoading,this),e.off(g.MANIFEST_PARSED,this.onManifestParsed,this),e.off(g.LEVEL_LOADING,this.onLevelLoading,this),e.off(g.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(g.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(g.ERROR,this.onError,this);}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,super.destroy();}onManifestLoading(){this.tracks=[],this.tracksInGroup=[],this.groupIds=null,this.currentTrack=null,this.trackId=-1,this.selectDefaultTrack=true;}onManifestParsed(e,t){this.tracks=t.audioTracks||[];}onAudioTrackLoaded(e,t){let{id:i,groupId:r,details:n}=t,a=this.tracksInGroup[i];if(!a||a.groupId!==r){this.warn(`Audio track with id:${i} and group:${r} not found in active group ${a?.groupId}`);return}let o=a.details;a.details=t.details,this.log(`Audio track ${i} "${a.name}" lang:${a.lang} group:${r} loaded [${n.startSN}-${n.endSN}]`),i===this.trackId&&this.playlistLoaded(i,t,o);}onLevelLoading(e,t){this.switchLevel(t.level);}onLevelSwitching(e,t){this.switchLevel(t.level);}switchLevel(e){let t=this.hls.levels[e];if(!t)return;let i=t.audioGroups||null,r=this.groupIds,n=this.currentTrack;if(!i||r?.length!==i?.length||i!=null&&i.some(o=>r?.indexOf(o)===-1)){this.groupIds=i,this.trackId=-1,this.currentTrack=null;let o=this.tracks.filter(h=>!i||i.indexOf(h.groupId)!==-1);if(o.length)this.selectDefaultTrack&&!o.some(h=>h.default)&&(this.selectDefaultTrack=false),o.forEach((h,f)=>{h.id=f;});else if(!n&&!this.tracksInGroup.length)return;this.tracksInGroup=o;let l=this.hls.config.audioPreference;if(!n&&l){let h=di(l,o,ns);if(h>-1)n=o[h];else {let f=di(l,this.tracks);n=this.tracks[f];}}let d=this.findTrackId(n);d===-1&&n&&(d=this.findTrackId(null));let c={audioTracks:o};this.log(`Updating audio tracks, ${o.length} track(s) found in group(s): ${i?.join(",")}`),this.hls.trigger(g.AUDIO_TRACKS_UPDATED,c);let u=this.trackId;if(d!==-1&&u===-1)this.setAudioTrack(d);else if(o.length&&u===-1){var a;let h=new Error(`No audio track selected for current audio group-ID(s): ${(a=this.groupIds)==null?void 0:a.join(",")} track count: ${o.length}`);this.warn(h.message),this.hls.trigger(g.ERROR,{type:z.MEDIA_ERROR,details:x.AUDIO_TRACK_LOAD_ERROR,fatal:true,error:h});}}}onError(e,t){t.fatal||!t.context||t.context.type===ce.AUDIO_TRACK&&t.context.id===this.trackId&&(!this.groupIds||this.groupIds.indexOf(t.context.groupId)!==-1)&&this.checkRetry(t);}get allAudioTracks(){return this.tracks}get audioTracks(){return this.tracksInGroup}get audioTrack(){return this.trackId}set audioTrack(e){this.selectDefaultTrack=false,this.setAudioTrack(e);}setAudioOption(e){let t=this.hls;if(t.config.audioPreference=e,e){let i=this.allAudioTracks;if(this.selectDefaultTrack=false,i.length){let r=this.currentTrack;if(r&&os(e,r,ns))return r;let n=di(e,this.tracksInGroup,ns);if(n>-1){let a=this.tracksInGroup[n];return this.setAudioTrack(n),a}else if(r){let a=t.loadLevel;a===-1&&(a=t.firstAutoLevel);let o=NT(e,t.levels,i,a,ns);if(o===-1)return null;t.nextLoadLevel=o;}if(e.channels||e.audioCodec){let a=di(e,i);if(a>-1)return i[a]}}}return null}setAudioTrack(e){let t=this.tracksInGroup;if(e<0||e>=t.length){this.warn(`Invalid audio track id: ${e}`);return}this.selectDefaultTrack=false;let i=this.currentTrack,r=t[e],n=r.details&&!r.details.live;if(e===this.trackId&&r===i&&n||(this.log(`Switching to audio-track ${e} "${r.name}" lang:${r.lang} group:${r.groupId} channels:${r.channels}`),this.trackId=e,this.currentTrack=r,this.hls.trigger(g.AUDIO_TRACK_SWITCHING,ve({},r)),n))return;let a=this.switchParams(r.url,i?.details,r.details);this.loadPlaylist(a);}findTrackId(e){let t=this.tracksInGroup;for(let i=0;i<t.length;i++){let r=t[i];if(!(this.selectDefaultTrack&&!r.default)&&(!e||os(e,r,ns)))return i}if(e){let{name:i,lang:r,assocLang:n,characteristics:a,audioCodec:o,channels:l}=e;for(let d=0;d<t.length;d++){let c=t[d];if(os({name:i,lang:r,assocLang:n,characteristics:a,audioCodec:o,channels:l},c,ns))return d}for(let d=0;d<t.length;d++){let c=t[d];if(Ln(e.attrs,c.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return d}for(let d=0;d<t.length;d++){let c=t[d];if(Ln(e.attrs,c.attrs,["LANGUAGE"]))return d}}return -1}loadPlaylist(e){super.loadPlaylist();let t=this.currentTrack;this.shouldLoadPlaylist(t)&&Wo(t.url,this.hls)&&this.scheduleLoading(t,e);}loadingPlaylist(e,t){super.loadingPlaylist(e,t);let i=e.id,r=e.groupId,n=this.getUrlWithDirectives(e.url,t),a=e.details,o=a?.age;this.log(`Loading audio-track ${i} "${e.name}" lang:${e.lang} group:${r}${t?.msn!==void 0?" at sn "+t.msn+" part "+t.part:""}${o&&a.live?" age "+o.toFixed(1)+(a.type&&" "+a.type||""):""} ${n}`),this.hls.trigger(g.AUDIO_TRACK_LOADING,{url:n,id:i,groupId:r,deliveryDirectives:t||null,track:e});}},zc=class{constructor(e){this.tracks=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.tracks=e;}destroy(){this.tracks=this.queues=null;}append(e,t,i){if(this.queues===null||this.tracks===null)return;let r=this.queues[t];r.push(e),r.length===1&&!i&&this.executeNext(t);}appendBlocker(e){return new Promise(t=>{let i={label:"async-blocker",execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.append(i,e);})}prependBlocker(e){return new Promise(t=>{if(this.queues){let i={label:"async-blocker-prepend",execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.queues[e].unshift(i);}})}removeBlockers(){this.queues!==null&&[this.queues.video,this.queues.audio,this.queues.audiovideo].forEach(e=>{var t;let i=(t=e[0])==null?void 0:t.label;(i==="async-blocker"||i==="async-blocker-prepend")&&(e[0].execute(),e.splice(0,1));});}unblockAudio(e){if(this.queues===null)return;this.queues.audio[0]===e&&this.shiftAndExecuteNext("audio");}executeNext(e){if(this.queues===null||this.tracks===null)return;let t=this.queues[e];if(t.length){let r=t[0];try{r.execute();}catch(n){var i;if(r.onError(n),this.queues===null||this.tracks===null)return;let a=(i=this.tracks[e])==null?void 0:i.buffer;a!=null&&a.updating||this.shiftAndExecuteNext(e);}}}shiftAndExecuteNext(e){this.queues!==null&&(this.queues[e].shift(),this.executeNext(e));}current(e){var t;return ((t=this.queues)==null?void 0:t[e][0])||null}toString(){let{queues:e,tracks:t}=this;return e===null||t===null?"<destroyed>":`
1370
+ initSegmentChange: ${R}`);let M=new Vc(i,r,t,o,c);this.configureTransmuxer(M);}if(this.frag=n,this.part=a,this.workerContext)this.workerContext.worker.postMessage({instanceNo:f,cmd:"demux",data:e,decryptdata:E,chunkMeta:d,state:L},e instanceof ArrayBuffer?[e]:[]);else if(m){let M=m.push(e,E,d,L);_n(M)?M.then(B=>{this.handleTransmuxComplete(B);}).catch(B=>{this.transmuxerError(B,d,"transmuxer-interface push error");}):this.handleTransmuxComplete(M);}}flush(e){e.transmuxing.start=self.performance.now();let{instanceNo:t,transmuxer:i}=this;if(this.workerContext)this.workerContext.worker.postMessage({instanceNo:t,cmd:"flush",chunkMeta:e});else if(i){let r=i.flush(e);_n(r)?r.then(n=>{this.handleFlushResult(n,e);}).catch(n=>{this.transmuxerError(n,e,"transmuxer-interface flush error");}):this.handleFlushResult(r,e);}}transmuxerError(e,t,i){this.hls&&(this.error=e,this.hls.trigger(g.ERROR,{type:z.MEDIA_ERROR,details:x.FRAG_PARSING_ERROR,chunkMeta:t,frag:this.frag||void 0,part:this.part||void 0,fatal:false,error:e,err:e,reason:i}));}handleFlushResult(e,t){e.forEach(i=>{this.handleTransmuxComplete(i);}),this.onFlush(t);}configureTransmuxer(e){let{instanceNo:t,transmuxer:i}=this;this.workerContext?this.workerContext.worker.postMessage({instanceNo:t,cmd:"configure",config:e}):i&&i.configure(e);}handleTransmuxComplete(e){e.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(e);}},rg=100,Yc=class extends yn{constructor(e,t,i){super(e,t,i,"audio-stream-controller",W.AUDIO),this.mainAnchor=null,this.mainFragLoading=null,this.audioOnly=false,this.bufferedTrack=null,this.switchingTrack=null,this.trackId=-1,this.waitingData=null,this.mainDetails=null,this.flushing=false,this.bufferFlushed=false,this.cachedTrackLoadedData=null,this.registerListeners();}onHandlerDestroying(){this.unregisterListeners(),super.onHandlerDestroying(),this.resetItem();}resetItem(){this.mainDetails=this.mainAnchor=this.mainFragLoading=this.bufferedTrack=this.switchingTrack=this.waitingData=this.cachedTrackLoadedData=null;}registerListeners(){super.registerListeners();let{hls:e}=this;e.on(g.LEVEL_LOADED,this.onLevelLoaded,this),e.on(g.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.on(g.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(g.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(g.BUFFER_RESET,this.onBufferReset,this),e.on(g.BUFFER_CREATED,this.onBufferCreated,this),e.on(g.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(g.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(g.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(g.FRAG_LOADING,this.onFragLoading,this),e.on(g.FRAG_BUFFERED,this.onFragBuffered,this);}unregisterListeners(){let{hls:e}=this;e&&(super.unregisterListeners(),e.off(g.LEVEL_LOADED,this.onLevelLoaded,this),e.off(g.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.off(g.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(g.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(g.BUFFER_RESET,this.onBufferReset,this),e.off(g.BUFFER_CREATED,this.onBufferCreated,this),e.off(g.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(g.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(g.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(g.FRAG_LOADING,this.onFragLoading,this),e.off(g.FRAG_BUFFERED,this.onFragBuffered,this));}onInitPtsFound(e,{frag:t,id:i,initPTS:r,timescale:n,trackId:a}){if(i===W.MAIN){let o=t.cc,l=this.fragCurrent;if(this.initPTS[o]={baseTime:r,timescale:n,trackId:a},this.log(`InitPTS for cc: ${o} found from main: ${r/n} (${r}/${n}) trackId: ${a}`),this.mainAnchor=t,this.state===C.WAITING_INIT_PTS){let d=this.waitingData;(!d&&!this.loadingParts||d&&d.frag.cc!==o)&&this.syncWithAnchor(t,d?.frag);}else !this.hls.hasEnoughToStart&&l&&l.cc!==o?(l.abortRequests(),this.syncWithAnchor(t,l)):this.state===C.IDLE&&this.tick();}}getLoadPosition(){return !this.startFragRequested&&this.nextLoadPosition>=0?this.nextLoadPosition:super.getLoadPosition()}syncWithAnchor(e,t){var i;let r=((i=this.mainFragLoading)==null?void 0:i.frag)||null;if(t&&r?.cc===t.cc)return;let n=(r||e).cc,a=this.getLevelDetails(),o=this.getLoadPosition(),l=Gg(a,n,o);l&&(this.log(`Syncing with main frag at ${l.start} cc ${l.cc}`),this.startFragRequested=false,this.nextLoadPosition=l.start,this.resetLoadingState(),this.state===C.IDLE&&this.doTickIdle());}startLoad(e,t){if(!this.levels){this.startPosition=e,this.state=C.STOPPED;return}let i=this.lastCurrentTime;this.stopLoad(),this.setInterval(rg),i>0&&e===-1?(this.log(`Override startPosition with lastCurrentTime @${i.toFixed(3)}`),e=i,this.state=C.IDLE):this.state=C.WAITING_TRACK,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick();}doTick(){switch(this.state){case C.IDLE:this.doTickIdle();break;case C.WAITING_TRACK:{let{levels:e,trackId:t}=this,i=e?.[t],r=i?.details;if(r&&!this.waitForLive(i)){if(this.waitForCdnTuneIn(r))break;this.state=C.WAITING_INIT_PTS;}break}case C.FRAG_LOADING_WAITING_RETRY:{this.checkRetryDate();break}case C.WAITING_INIT_PTS:{let e=this.waitingData;if(e){let{frag:t,part:i,cache:r,complete:n}=e,a=this.mainAnchor;if(this.initPTS[t.cc]!==void 0){this.waitingData=null,this.state=C.FRAG_LOADING;let o=r.flush().buffer,l={frag:t,part:i,payload:o,networkDetails:null};this._handleFragmentLoadProgress(l),n&&super._handleFragmentLoadComplete(l);}else a&&a.cc!==e.frag.cc&&this.syncWithAnchor(a,e.frag);}else this.state=C.IDLE;}}this.onTickEnd();}resetLoadingState(){let e=this.waitingData;e&&(this.fragmentTracker.removeFragment(e.frag),this.waitingData=null),super.resetLoadingState();}onTickEnd(){let{media:e}=this;e!=null&&e.readyState&&(this.lastCurrentTime=e.currentTime);}doTickIdle(){var e;let{hls:t,levels:i,media:r,trackId:n}=this,a=t.config;if(!this.buffering||!r&&!this.primaryPrefetch&&(this.startFragRequested||!a.startFragPrefetch)||!(i!=null&&i[n]))return;let o=i[n],l=o.details;if(!l||this.waitForLive(o)||this.waitForCdnTuneIn(l)){this.state=C.WAITING_TRACK,this.startFragRequested=false;return}let d=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&d&&(this.bufferFlushed=false,this.afterBufferFlushed(d,Se.AUDIO,W.AUDIO));let c=this.getFwdBufferInfo(d,W.AUDIO);if(c===null)return;if(!this.switchingTrack&&this._streamEnded(c,l)){t.trigger(g.BUFFER_EOS,{type:"audio"}),this.state=C.ENDED;return}let u=c.len,h=t.maxBufferLength,f=l.fragments,m=f[0].start,p=this.getLoadPosition(),E=this.flushing?p:c.end;if(this.switchingTrack&&r){let S=p;l.PTSKnown&&S<m&&(c.end>m||c.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),r.currentTime=m+.05);}if(u>=h&&!this.switchingTrack&&E<f[f.length-1].start)return;let v=this.getNextFragment(E,l);if(v&&this.isLoopLoading(v,E)&&(v=this.getNextFragmentLoopLoading(v,l,c,W.MAIN,h)),!v){this.bufferFlushed=true;return}let T=((e=this.mainFragLoading)==null?void 0:e.frag)||null;if(!this.audioOnly&&this.startFragRequested&&T&&Ue(v)&&!v.endList&&(!l.live||!this.loadingParts&&E<this.hls.liveSyncPosition)&&(this.fragmentTracker.getState(T)===Ke.OK&&(this.mainFragLoading=T=null),T&&Ue(T))){if(v.start>T.end){let A=this.fragmentTracker.getFragAtPos(E,W.MAIN);A&&A.end>T.end&&(T=A,this.mainFragLoading={frag:A,targetBufferTime:null});}if(v.start>T.end)return}this.loadFragment(v,o,E);}onMediaDetaching(e,t){this.bufferFlushed=this.flushing=false,super.onMediaDetaching(e,t);}onAudioTracksUpdated(e,{audioTracks:t}){this.resetTransmuxer(),this.levels=t.map(i=>new ds(i));}onAudioTrackSwitching(e,t){let i=!!t.url;this.trackId=t.id;let{fragCurrent:r}=this;r&&(r.abortRequests(),this.removeUnbufferedFrags(r.start)),this.resetLoadingState(),i?(this.switchingTrack=t,this.flushAudioIfNeeded(t),this.state!==C.STOPPED&&(this.setInterval(rg),this.state=C.IDLE,this.tick())):(this.resetTransmuxer(),this.switchingTrack=null,this.bufferedTrack=t,this.clearInterval());}onManifestLoading(){super.onManifestLoading(),this.bufferFlushed=this.flushing=this.audioOnly=false,this.resetItem(),this.trackId=-1;}onLevelLoaded(e,t){this.mainDetails=t.details;let i=this.cachedTrackLoadedData;i&&(this.cachedTrackLoadedData=null,this.onAudioTrackLoaded(g.AUDIO_TRACK_LOADED,i));}onAudioTrackLoaded(e,t){var i;let{levels:r}=this,{details:n,id:a,groupId:o,track:l}=t;if(!r){this.warn(`Audio tracks reset while loading track ${a} "${l.name}" of "${o}"`);return}let d=this.mainDetails;if(!d||n.endCC>d.endCC||d.expired){this.cachedTrackLoadedData=t,this.state!==C.STOPPED&&(this.state=C.WAITING_TRACK);return}this.cachedTrackLoadedData=null,this.log(`Audio track ${a} "${l.name}" of "${o}" loaded [${n.startSN},${n.endSN}]${n.lastPartSn?`[part-${n.lastPartSn}-${n.lastPartIndex}]`:""},duration:${n.totalduration}`);let c=r[a],u=0;if(n.live||(i=c.details)!=null&&i.live){if(this.checkLiveUpdate(n),n.deltaUpdateFailed)return;if(c.details){var h;u=this.alignPlaylists(n,c.details,(h=this.levelLastLoaded)==null?void 0:h.details);}n.alignedSliding||(sp(n,d),n.alignedSliding||Zo(n,d),u=n.fragmentStart);}c.details=n,this.levelLastLoaded=c,this.startFragRequested||this.setStartPosition(d,u),this.hls.trigger(g.AUDIO_TRACK_UPDATED,{details:n,id:a,groupId:t.groupId}),this.state===C.WAITING_TRACK&&!this.waitForCdnTuneIn(n)&&(this.state=C.IDLE),this.tick();}_handleFragmentLoadProgress(e){var t;let i=e.frag,{part:r,payload:n}=e,{config:a,trackId:o,levels:l}=this;if(!l){this.warn(`Audio tracks were reset while fragment load was in progress. Fragment ${i.sn} of level ${i.level} will not be buffered`);return}let d=l[o];if(!d){this.warn("Audio track is undefined on fragment load progress");return}let c=d.details;if(!c){this.warn("Audio track details undefined on fragment load progress"),this.removeUnbufferedFrags(i.start);return}let u=a.defaultAudioCodec||d.audioCodec||"mp4a.40.2",h=this.transmuxer;h||(h=this.transmuxer=new sl(this.hls,W.AUDIO,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));let f=this.initPTS[i.cc],m=(t=i.initSegment)==null?void 0:t.data;if(f!==void 0){let E=r?r.index:-1,v=E!==-1,T=new vn(i.level,i.sn,i.stats.chunkCount,n.byteLength,E,v);h.push(n,m,u,"",i,r,c.totalduration,false,T,f);}else {this.log(`Unknown video PTS for cc ${i.cc}, waiting for video PTS before demuxing audio frag ${i.sn} of [${c.startSN} ,${c.endSN}],track ${o}`);let{cache:p}=this.waitingData=this.waitingData||{frag:i,part:r,cache:new Jo,complete:false};p.push(new Uint8Array(n)),this.state!==C.STOPPED&&(this.state=C.WAITING_INIT_PTS);}}_handleFragmentLoadComplete(e){if(this.waitingData){this.waitingData.complete=true;return}super._handleFragmentLoadComplete(e);}onBufferReset(){this.mediaBuffer=null;}onBufferCreated(e,t){this.bufferFlushed=this.flushing=false;let i=t.tracks.audio;i&&(this.mediaBuffer=i.buffer||null);}onFragLoading(e,t){!this.audioOnly&&t.frag.type===W.MAIN&&Ue(t.frag)&&(this.mainFragLoading=t,this.state===C.IDLE&&this.tick());}onFragBuffered(e,t){let{frag:i,part:r}=t;if(i.type!==W.AUDIO){!this.audioOnly&&i.type===W.MAIN&&!i.elementaryStreams.video&&!i.elementaryStreams.audiovideo&&(this.audioOnly=true,this.mainFragLoading=null);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}, audioSwitch: ${this.switchingTrack?this.switchingTrack.name:"false"}`);return}if(Ue(i)){this.fragPrevious=i;let n=this.switchingTrack;n&&(this.bufferedTrack=n,this.switchingTrack=null,this.hls.trigger(g.AUDIO_TRACK_SWITCHED,ve({},n)));}this.fragBufferedComplete(i,r),this.media&&this.tick();}onError(e,t){var i;if(t.fatal){this.state=C.ERROR;return}switch(t.details){case x.FRAG_GAP:case x.FRAG_PARSING_ERROR:case x.FRAG_DECRYPT_ERROR:case x.FRAG_LOAD_ERROR:case x.FRAG_LOAD_TIMEOUT:case x.KEY_LOAD_ERROR:case x.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(W.AUDIO,t);break;case x.AUDIO_TRACK_LOAD_ERROR:case x.AUDIO_TRACK_LOAD_TIMEOUT:case x.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===C.WAITING_TRACK&&((i=t.context)==null?void 0:i.type)===ce.AUDIO_TRACK&&(this.state=C.IDLE);break;case x.BUFFER_ADD_CODEC_ERROR:case x.BUFFER_APPEND_ERROR:if(t.parent!=="audio")return;this.reduceLengthAndFlushBuffer(t)||this.resetLoadingState();break;case x.BUFFER_FULL_ERROR:if(t.parent!=="audio")return;this.reduceLengthAndFlushBuffer(t)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case x.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}onBufferFlushing(e,{type:t}){t!==Se.VIDEO&&(this.flushing=true);}onBufferFlushed(e,{type:t}){if(t!==Se.VIDEO){this.flushing=false,this.bufferFlushed=true,this.state===C.ENDED&&(this.state=C.IDLE);let i=this.mediaBuffer||this.media;i&&(this.afterBufferFlushed(i,t,W.AUDIO),this.tick());}}_handleTransmuxComplete(e){var t;let i="audio",{hls:r}=this,{remuxResult:n,chunkMeta:a}=e,o=this.getCurrentContext(a);if(!o){this.resetWhenMissingContext(a);return}let{frag:l,part:d,level:c}=o,{details:u}=c,{audio:h,text:f,id3:m,initSegment:p}=n;if(this.fragContextChanged(l)||!u){this.fragmentTracker.removeFragment(l);return}if(this.state=C.PARSING,this.switchingTrack&&h&&this.completeAudioSwitch(this.switchingTrack),p!=null&&p.tracks){let E=l.initSegment||l;if(this.unhandledEncryptionError(p,l))return;this._bufferInitSegment(c,p.tracks,E,a),r.trigger(g.FRAG_PARSING_INIT_SEGMENT,{frag:E,id:i,tracks:p.tracks});}if(h){let{startPTS:E,endPTS:v,startDTS:T,endDTS:S}=h;d&&(d.elementaryStreams[Se.AUDIO]={startPTS:E,endPTS:v,startDTS:T,endDTS:S}),l.setElementaryStreamInfo(Se.AUDIO,E,v,T,S),this.bufferFragmentData(h,l,d,a);}if(m!=null&&(t=m.samples)!=null&&t.length){let E=ye({id:i,frag:l,details:u},m);r.trigger(g.FRAG_PARSING_METADATA,E);}if(f){let E=ye({id:i,frag:l,details:u},f);r.trigger(g.FRAG_PARSING_USERDATA,E);}}_bufferInitSegment(e,t,i,r){if(this.state!==C.PARSING||(t.video&&delete t.video,t.audiovideo&&delete t.audiovideo,!t.audio))return;let n=t.audio;n.id=W.AUDIO;let a=e.audioCodec;this.log(`Init audio buffer, container:${n.container}, codecs[level/parsed]=[${a}/${n.codec}]`),a&&a.split(",").length===1&&(n.levelCodec=a),this.hls.trigger(g.BUFFER_CODECS,t);let o=n.initSegment;if(o!=null&&o.byteLength){let l={type:"audio",frag:i,part:null,chunkMeta:r,parent:i.type,data:o};this.hls.trigger(g.BUFFER_APPENDING,l);}this.tickImmediate();}loadFragment(e,t,i){let r=this.fragmentTracker.getState(e);if(this.switchingTrack||r===Ke.NOT_LOADED||r===Ke.PARTIAL){var n;if(!Ue(e))this._loadInitSegment(e,t);else if((n=t.details)!=null&&n.live&&!this.initPTS[e.cc]){this.log(`Waiting for video PTS in continuity counter ${e.cc} of live stream before loading audio fragment ${e.sn} of level ${this.trackId}`),this.state=C.WAITING_INIT_PTS;let a=this.mainDetails;a&&a.fragmentStart!==t.details.fragmentStart&&Zo(t.details,a);}else super.loadFragment(e,t,i);}else this.clearTrackerIfNeeded(e);}flushAudioIfNeeded(e){if(this.media&&this.bufferedTrack){let{name:t,lang:i,assocLang:r,characteristics:n,audioCodec:a,channels:o}=this.bufferedTrack;os({name:t,lang:i,assocLang:r,characteristics:n,audioCodec:a,channels:o},e,ns)||(Wo(e.url,this.hls)?(this.log("Switching audio track : flushing all audio"),super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"),this.bufferedTrack=null):this.bufferedTrack=e);}}completeAudioSwitch(e){let{hls:t}=this;this.flushAudioIfNeeded(e),this.bufferedTrack=e,this.switchingTrack=null,t.trigger(g.AUDIO_TRACK_SWITCHED,ve({},e));}},In=class extends ht{constructor(e,t){super(t,e.logger),this.hls=void 0,this.canLoad=false,this.timer=-1,this.hls=e;}destroy(){this.clearTimer(),this.hls=this.log=this.warn=null;}clearTimer(){this.timer!==-1&&(self.clearTimeout(this.timer),this.timer=-1);}startLoad(){this.canLoad=true,this.loadPlaylist();}stopLoad(){this.canLoad=false,this.clearTimer();}switchParams(e,t,i){let r=t?.renditionReports;if(r){let n=-1;for(let a=0;a<r.length;a++){let o=r[a],l;try{l=new self.URL(o.URI,t.url).href;}catch(d){this.warn(`Could not construct new URL for Rendition Report: ${d}`),l=o.URI||"";}if(l===e){n=a;break}else l===e.substring(0,l.length)&&(n=a);}if(n!==-1){let a=r[n],o=parseInt(a["LAST-MSN"])||t.lastPartSn,l=parseInt(a["LAST-PART"])||t.lastPartIndex;if(this.hls.config.lowLatencyMode){let c=Math.min(t.age-t.partTarget,t.targetduration);l>=0&&c>t.partTarget&&(l+=1);}let d=i&&Sm(i);return new Vo(o,l>=0?l:void 0,d)}}}loadPlaylist(e){this.clearTimer();}loadingPlaylist(e,t){this.clearTimer();}shouldLoadPlaylist(e){return this.canLoad&&!!e&&!!e.url&&(!e.details||e.details.live)}getUrlWithDirectives(e,t){if(t)try{return t.addDirectives(e)}catch(i){this.warn(`Could not construct new URL with HLS Delivery Directives: ${i}`);}return e}playlistLoaded(e,t,i){let{details:r,stats:n}=t,a=self.performance.now(),o=n.loading.first?Math.max(0,a-n.loading.first):0;r.advancedDateTime=Date.now()-o;let l=this.hls.config.timelineOffset;if(l!==r.appliedTimelineOffset){let c=Math.max(l||0,0);r.appliedTimelineOffset=c,r.fragments.forEach(u=>{u.setStart(u.playlistOffset+c);});}if(r.live||i!=null&&i.live){let c="levelInfo"in t?t.levelInfo:t.track;if(r.reloaded(i),i&&r.fragments.length>0){dy(i,r,this);let T=r.playlistParsingError;if(T){this.warn(T);let S=this.hls;if(!S.config.ignorePlaylistParsingErrors){var d;let{networkDetails:A}=t;S.trigger(g.ERROR,{type:z.NETWORK_ERROR,details:x.LEVEL_PARSING_ERROR,fatal:false,url:r.url,error:T,reason:T.message,level:t.level||void 0,parent:(d=r.fragments[0])==null?void 0:d.type,networkDetails:A,stats:n});return}r.playlistParsingError=null;}}r.requestScheduled===-1&&(r.requestScheduled=n.loading.start);let u=this.hls.mainForwardBufferInfo,h=u?u.end-u.len:0,f=(r.edge-h)*1e3,m=Zg(r,f);if(r.requestScheduled+m<a?r.requestScheduled=a:r.requestScheduled+=m,this.log(`live playlist ${e} ${r.advanced?"REFRESHED "+r.lastPartSn+"-"+r.lastPartIndex:r.updated?"UPDATED":"MISSED"}`),!this.canLoad||!r.live)return;let p,E,v;if(r.canBlockReload&&r.endSN&&r.advanced){let T=this.hls.config.lowLatencyMode,S=r.lastPartSn,A=r.endSN,b=r.lastPartIndex,D=b!==-1,I=S===A;D?I?(E=A+1,v=T?0:b):(E=S,v=T?b+1:r.maxPartIndex):E=A+1;let k=r.age,R=k+r.ageHeader,L=Math.min(R-r.partTarget,r.targetduration*1.5);if(L>0){if(R>r.targetduration*3)this.log(`Playlist last advanced ${k.toFixed(2)}s ago. Omitting segment and part directives.`),E=void 0,v=void 0;else if(i!=null&&i.tuneInGoal&&R-r.partTarget>i.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${i.tuneInGoal} to: ${L} with playlist age: ${r.age}`),L=0;else {let M=Math.floor(L/r.targetduration);if(E+=M,v!==void 0){let B=Math.round(L%r.targetduration/r.partTarget);v+=B;}this.log(`CDN Tune-in age: ${r.ageHeader}s last advanced ${k.toFixed(2)}s goal: ${L} skip sn ${M} to part ${v}`);}r.tuneInGoal=L;}if(p=this.getDeliveryDirectives(r,t.deliveryDirectives,E,v),T||!I){r.requestScheduled=a,this.loadingPlaylist(c,p);return}}else (r.canBlockReload||r.canSkipUntil)&&(p=this.getDeliveryDirectives(r,t.deliveryDirectives,E,v));p&&E!==void 0&&r.canBlockReload&&(r.requestScheduled=n.loading.first+Math.max(m-o*2,m/2)),this.scheduleLoading(c,p,r);}else this.clearTimer();}scheduleLoading(e,t,i){let r=i||e.details;if(!r){this.loadingPlaylist(e,t);return}let n=self.performance.now(),a=r.requestScheduled;if(n>=a){this.loadingPlaylist(e,t);return}let o=a-n;this.log(`reload live playlist ${e.name||e.bitrate+"bps"} in ${Math.round(o)} ms`),this.clearTimer(),this.timer=self.setTimeout(()=>this.loadingPlaylist(e,t),o);}getDeliveryDirectives(e,t,i,r){let n=Sm(e);return t!=null&&t.skip&&e.deltaUpdateFailed&&(i=t.msn,r=t.part,n=wo.No),new Vo(i,r,n)}checkRetry(e){let t=e.details,i=Yo(e),r=e.errorAction,{action:n,retryCount:a=0,retryConfig:o}=r||{},l=!!r&&!!o&&(n===ze.RetryRequest||!r.resolved&&n===ze.SendAlternateToPenaltyBox);if(l){var d;if(a>=o.maxNumRetry)return false;if(i&&(d=e.context)!=null&&d.deliveryDirectives)this.warn(`Retrying playlist loading ${a+1}/${o.maxNumRetry} after "${t}" without delivery-directives`),this.loadPlaylist();else {let c=Fu(o,a);this.clearTimer(),this.timer=self.setTimeout(()=>this.loadPlaylist(),c),this.warn(`Retrying playlist loading ${a+1}/${o.maxNumRetry} after "${t}" in ${c}ms`);}e.levelRetry=true,r.resolved=true;}return l}};function Sp(s,e){if(s.length!==e.length)return false;for(let t=0;t<s.length;t++)if(!Ln(s[t].attrs,e[t].attrs))return false;return true}function Ln(s,e,t){let i=s["STABLE-RENDITION-ID"];return i&&!t?i===e["STABLE-RENDITION-ID"]:!(t||["LANGUAGE","NAME","CHARACTERISTICS","AUTOSELECT","DEFAULT","FORCED","ASSOC-LANGUAGE"]).some(r=>s[r]!==e[r])}function qc(s,e){return e.label.toLowerCase()===s.name.toLowerCase()&&(!e.language||e.language.toLowerCase()===(s.lang||"").toLowerCase())}var jc=class extends In{constructor(e){super(e,"audio-track-controller"),this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=true,this.registerListeners();}registerListeners(){let{hls:e}=this;e.on(g.MANIFEST_LOADING,this.onManifestLoading,this),e.on(g.MANIFEST_PARSED,this.onManifestParsed,this),e.on(g.LEVEL_LOADING,this.onLevelLoading,this),e.on(g.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(g.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(g.ERROR,this.onError,this);}unregisterListeners(){let{hls:e}=this;e.off(g.MANIFEST_LOADING,this.onManifestLoading,this),e.off(g.MANIFEST_PARSED,this.onManifestParsed,this),e.off(g.LEVEL_LOADING,this.onLevelLoading,this),e.off(g.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(g.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(g.ERROR,this.onError,this);}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,super.destroy();}onManifestLoading(){this.tracks=[],this.tracksInGroup=[],this.groupIds=null,this.currentTrack=null,this.trackId=-1,this.selectDefaultTrack=true;}onManifestParsed(e,t){this.tracks=t.audioTracks||[];}onAudioTrackLoaded(e,t){let{id:i,groupId:r,details:n}=t,a=this.tracksInGroup[i];if(!a||a.groupId!==r){this.warn(`Audio track with id:${i} and group:${r} not found in active group ${a?.groupId}`);return}let o=a.details;a.details=t.details,this.log(`Audio track ${i} "${a.name}" lang:${a.lang} group:${r} loaded [${n.startSN}-${n.endSN}]`),i===this.trackId&&this.playlistLoaded(i,t,o);}onLevelLoading(e,t){this.switchLevel(t.level);}onLevelSwitching(e,t){this.switchLevel(t.level);}switchLevel(e){let t=this.hls.levels[e];if(!t)return;let i=t.audioGroups||null,r=this.groupIds,n=this.currentTrack;if(!i||r?.length!==i?.length||i!=null&&i.some(o=>r?.indexOf(o)===-1)){this.groupIds=i,this.trackId=-1,this.currentTrack=null;let o=this.tracks.filter(h=>!i||i.indexOf(h.groupId)!==-1);if(o.length)this.selectDefaultTrack&&!o.some(h=>h.default)&&(this.selectDefaultTrack=false),o.forEach((h,f)=>{h.id=f;});else if(!n&&!this.tracksInGroup.length)return;this.tracksInGroup=o;let l=this.hls.config.audioPreference;if(!n&&l){let h=di(l,o,ns);if(h>-1)n=o[h];else {let f=di(l,this.tracks);n=this.tracks[f];}}let d=this.findTrackId(n);d===-1&&n&&(d=this.findTrackId(null));let c={audioTracks:o};this.log(`Updating audio tracks, ${o.length} track(s) found in group(s): ${i?.join(",")}`),this.hls.trigger(g.AUDIO_TRACKS_UPDATED,c);let u=this.trackId;if(d!==-1&&u===-1)this.setAudioTrack(d);else if(o.length&&u===-1){var a;let h=new Error(`No audio track selected for current audio group-ID(s): ${(a=this.groupIds)==null?void 0:a.join(",")} track count: ${o.length}`);this.warn(h.message),this.hls.trigger(g.ERROR,{type:z.MEDIA_ERROR,details:x.AUDIO_TRACK_LOAD_ERROR,fatal:true,error:h});}}}onError(e,t){t.fatal||!t.context||t.context.type===ce.AUDIO_TRACK&&t.context.id===this.trackId&&(!this.groupIds||this.groupIds.indexOf(t.context.groupId)!==-1)&&this.checkRetry(t);}get allAudioTracks(){return this.tracks}get audioTracks(){return this.tracksInGroup}get audioTrack(){return this.trackId}set audioTrack(e){this.selectDefaultTrack=false,this.setAudioTrack(e);}setAudioOption(e){let t=this.hls;if(t.config.audioPreference=e,e){let i=this.allAudioTracks;if(this.selectDefaultTrack=false,i.length){let r=this.currentTrack;if(r&&os(e,r,ns))return r;let n=di(e,this.tracksInGroup,ns);if(n>-1){let a=this.tracksInGroup[n];return this.setAudioTrack(n),a}else if(r){let a=t.loadLevel;a===-1&&(a=t.firstAutoLevel);let o=UT(e,t.levels,i,a,ns);if(o===-1)return null;t.nextLoadLevel=o;}if(e.channels||e.audioCodec){let a=di(e,i);if(a>-1)return i[a]}}}return null}setAudioTrack(e){let t=this.tracksInGroup;if(e<0||e>=t.length){this.warn(`Invalid audio track id: ${e}`);return}this.selectDefaultTrack=false;let i=this.currentTrack,r=t[e],n=r.details&&!r.details.live;if(e===this.trackId&&r===i&&n||(this.log(`Switching to audio-track ${e} "${r.name}" lang:${r.lang} group:${r.groupId} channels:${r.channels}`),this.trackId=e,this.currentTrack=r,this.hls.trigger(g.AUDIO_TRACK_SWITCHING,ve({},r)),n))return;let a=this.switchParams(r.url,i?.details,r.details);this.loadPlaylist(a);}findTrackId(e){let t=this.tracksInGroup;for(let i=0;i<t.length;i++){let r=t[i];if(!(this.selectDefaultTrack&&!r.default)&&(!e||os(e,r,ns)))return i}if(e){let{name:i,lang:r,assocLang:n,characteristics:a,audioCodec:o,channels:l}=e;for(let d=0;d<t.length;d++){let c=t[d];if(os({name:i,lang:r,assocLang:n,characteristics:a,audioCodec:o,channels:l},c,ns))return d}for(let d=0;d<t.length;d++){let c=t[d];if(Ln(e.attrs,c.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return d}for(let d=0;d<t.length;d++){let c=t[d];if(Ln(e.attrs,c.attrs,["LANGUAGE"]))return d}}return -1}loadPlaylist(e){super.loadPlaylist();let t=this.currentTrack;this.shouldLoadPlaylist(t)&&Wo(t.url,this.hls)&&this.scheduleLoading(t,e);}loadingPlaylist(e,t){super.loadingPlaylist(e,t);let i=e.id,r=e.groupId,n=this.getUrlWithDirectives(e.url,t),a=e.details,o=a?.age;this.log(`Loading audio-track ${i} "${e.name}" lang:${e.lang} group:${r}${t?.msn!==void 0?" at sn "+t.msn+" part "+t.part:""}${o&&a.live?" age "+o.toFixed(1)+(a.type&&" "+a.type||""):""} ${n}`),this.hls.trigger(g.AUDIO_TRACK_LOADING,{url:n,id:i,groupId:r,deliveryDirectives:t||null,track:e});}},zc=class{constructor(e){this.tracks=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.tracks=e;}destroy(){this.tracks=this.queues=null;}append(e,t,i){if(this.queues===null||this.tracks===null)return;let r=this.queues[t];r.push(e),r.length===1&&!i&&this.executeNext(t);}appendBlocker(e){return new Promise(t=>{let i={label:"async-blocker",execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.append(i,e);})}prependBlocker(e){return new Promise(t=>{if(this.queues){let i={label:"async-blocker-prepend",execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.queues[e].unshift(i);}})}removeBlockers(){this.queues!==null&&[this.queues.video,this.queues.audio,this.queues.audiovideo].forEach(e=>{var t;let i=(t=e[0])==null?void 0:t.label;(i==="async-blocker"||i==="async-blocker-prepend")&&(e[0].execute(),e.splice(0,1));});}unblockAudio(e){if(this.queues===null)return;this.queues.audio[0]===e&&this.shiftAndExecuteNext("audio");}executeNext(e){if(this.queues===null||this.tracks===null)return;let t=this.queues[e];if(t.length){let r=t[0];try{r.execute();}catch(n){var i;if(r.onError(n),this.queues===null||this.tracks===null)return;let a=(i=this.tracks[e])==null?void 0:i.buffer;a!=null&&a.updating||this.shiftAndExecuteNext(e);}}}shiftAndExecuteNext(e){this.queues!==null&&(this.queues[e].shift(),this.executeNext(e));}current(e){var t;return ((t=this.queues)==null?void 0:t[e][0])||null}toString(){let{queues:e,tracks:t}=this;return e===null||t===null?"<destroyed>":`
1371
1371
  ${this.list("video")}
1372
1372
  ${this.list("audio")}
1373
- ${this.list("audiovideo")}}`}list(e){var t,i;return (t=this.queues)!=null&&t[e]||(i=this.tracks)!=null&&i[e]?`${e}: (${this.listSbInfo(e)}) ${this.listOps(e)}`:""}listSbInfo(e){var t;let i=(t=this.tracks)==null?void 0:t[e],r=i?.buffer;return r?`SourceBuffer${r.updating?" updating":""}${i.ended?" ended":""}${i.ending?" ending":""}`:"none"}listOps(e){var t;return ((t=this.queues)==null?void 0:t[e].map(i=>i.label).join(", "))||""}},rg=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,Sp="HlsJsTrackRemovedError",Qc=class extends Error{constructor(e){super(e),this.name=Sp;}},Xc=class extends ht{constructor(e,t){super("buffer-controller",e.logger),this.hls=void 0,this.fragmentTracker=void 0,this.details=null,this._objectUrl=null,this.operationQueue=null,this.bufferCodecEventsTotal=0,this.media=null,this.mediaSource=null,this.lastMpegAudioChunk=null,this.blockedAudioAppend=null,this.lastVideoAppendEnd=0,this.appendSource=void 0,this.transferData=void 0,this.overrides=void 0,this.appendErrors={audio:0,video:0,audiovideo:0},this.tracks={},this.sourceBuffers=[[null,null],[null,null]],this._onEndStreaming=i=>{var r;this.hls&&((r=this.mediaSource)==null?void 0:r.readyState)==="open"&&this.hls.pauseBuffering();},this._onStartStreaming=i=>{this.hls&&this.hls.resumeBuffering();},this._onMediaSourceOpen=i=>{let{media:r,mediaSource:n}=this;i&&this.log("Media source opened"),!(!r||!n)&&(n.removeEventListener("sourceopen",this._onMediaSourceOpen),r.removeEventListener("emptied",this._onMediaEmptied),this.updateDuration(),this.hls.trigger(g.MEDIA_ATTACHED,{media:r,mediaSource:n}),this.mediaSource!==null&&this.checkPendingTracks());},this._onMediaSourceClose=()=>{this.log("Media source closed");},this._onMediaSourceEnded=()=>{this.log("Media source ended");},this._onMediaEmptied=()=>{let{mediaSrc:i,_objectUrl:r}=this;i!==r&&this.error(`Media element src was set while attaching MediaSource (${r} > ${i})`);},this.hls=e,this.fragmentTracker=t,this.appendSource=Xv(Fi(e.config.preferManagedMediaSource)),this.initTracks(),this.registerListeners();}hasSourceTypes(){return Object.keys(this.tracks).length>0}destroy(){this.unregisterListeners(),this.details=null,this.lastMpegAudioChunk=this.blockedAudioAppend=null,this.transferData=this.overrides=void 0,this.operationQueue&&(this.operationQueue.destroy(),this.operationQueue=null),this.hls=this.fragmentTracker=null,this._onMediaSourceOpen=this._onMediaSourceClose=null,this._onMediaSourceEnded=null,this._onStartStreaming=this._onEndStreaming=null;}registerListeners(){let{hls:e}=this;e.on(g.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(g.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(g.MANIFEST_LOADING,this.onManifestLoading,this),e.on(g.MANIFEST_PARSED,this.onManifestParsed,this),e.on(g.BUFFER_RESET,this.onBufferReset,this),e.on(g.BUFFER_APPENDING,this.onBufferAppending,this),e.on(g.BUFFER_CODECS,this.onBufferCodecs,this),e.on(g.BUFFER_EOS,this.onBufferEos,this),e.on(g.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(g.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(g.FRAG_PARSED,this.onFragParsed,this),e.on(g.FRAG_CHANGED,this.onFragChanged,this),e.on(g.ERROR,this.onError,this);}unregisterListeners(){let{hls:e}=this;e.off(g.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(g.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(g.MANIFEST_LOADING,this.onManifestLoading,this),e.off(g.MANIFEST_PARSED,this.onManifestParsed,this),e.off(g.BUFFER_RESET,this.onBufferReset,this),e.off(g.BUFFER_APPENDING,this.onBufferAppending,this),e.off(g.BUFFER_CODECS,this.onBufferCodecs,this),e.off(g.BUFFER_EOS,this.onBufferEos,this),e.off(g.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(g.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(g.FRAG_PARSED,this.onFragParsed,this),e.off(g.FRAG_CHANGED,this.onFragChanged,this),e.off(g.ERROR,this.onError,this);}transferMedia(){let{media:e,mediaSource:t}=this;if(!e)return null;let i={};if(this.operationQueue){let n=this.isUpdating();n||this.operationQueue.removeBlockers();let a=this.isQueued();(n||a)&&this.warn(`Transfering MediaSource with${a?" operations in queue":""}${n?" updating SourceBuffer(s)":""} ${this.operationQueue}`),this.operationQueue.destroy();}let r=this.transferData;return !this.sourceBufferCount&&r&&r.mediaSource===t?ye(i,r.tracks):this.sourceBuffers.forEach(n=>{let[a]=n;a&&(i[a]=ye({},this.tracks[a]),this.removeBuffer(a)),n[0]=n[1]=null;}),{media:e,mediaSource:t,tracks:i}}initTracks(){let e={};this.sourceBuffers=[[null,null],[null,null]],this.tracks=e,this.resetQueue(),this.resetAppendErrors(),this.lastMpegAudioChunk=this.blockedAudioAppend=null,this.lastVideoAppendEnd=0;}onManifestLoading(){this.bufferCodecEventsTotal=0,this.details=null;}onManifestParsed(e,t){var i;let r=2;(t.audio&&!t.video||!t.altAudio)&&(r=1),this.bufferCodecEventsTotal=r,this.log(`${r} bufferCodec event(s) expected.`),(i=this.transferData)!=null&&i.mediaSource&&this.sourceBufferCount&&r&&this.bufferCreated();}onMediaAttaching(e,t){let i=this.media=t.media;this.transferData=this.overrides=void 0;let r=Fi(this.appendSource);if(r){let n=!!t.mediaSource;(n||t.overrides)&&(this.transferData=t,this.overrides=t.overrides);let a=this.mediaSource=t.mediaSource||new r;if(this.assignMediaSource(a),n)this._objectUrl=i.src,this.attachTransferred();else {let o=this._objectUrl=self.URL.createObjectURL(a);if(this.appendSource)try{i.removeAttribute("src");let l=self.ManagedMediaSource;i.disableRemotePlayback=i.disableRemotePlayback||l&&a instanceof l,ng(i),nS(i,o),i.load();}catch{i.src=o;}else i.src=o;}i.addEventListener("emptied",this._onMediaEmptied);}}assignMediaSource(e){var t,i;this.log(`${((t=this.transferData)==null?void 0:t.mediaSource)===e?"transferred":"created"} media source: ${(i=e.constructor)==null?void 0:i.name}`),e.addEventListener("sourceopen",this._onMediaSourceOpen),e.addEventListener("sourceended",this._onMediaSourceEnded),e.addEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(e.addEventListener("startstreaming",this._onStartStreaming),e.addEventListener("endstreaming",this._onEndStreaming));}attachTransferred(){let e=this.media,t=this.transferData;if(!t||!e)return;let i=this.tracks,r=t.tracks,n=r?Object.keys(r):null,a=n?n.length:0,o=()=>{Promise.resolve().then(()=>{this.media&&this.mediaSourceOpenOrEnded&&this._onMediaSourceOpen();});};if(r&&n&&a){if(!this.tracksReady){this.hls.config.startFragPrefetch=true,this.log("attachTransferred: waiting for SourceBuffer track info");return}if(this.log(`attachTransferred: (bufferCodecEventsTotal ${this.bufferCodecEventsTotal})
1373
+ ${this.list("audiovideo")}}`}list(e){var t,i;return (t=this.queues)!=null&&t[e]||(i=this.tracks)!=null&&i[e]?`${e}: (${this.listSbInfo(e)}) ${this.listOps(e)}`:""}listSbInfo(e){var t;let i=(t=this.tracks)==null?void 0:t[e],r=i?.buffer;return r?`SourceBuffer${r.updating?" updating":""}${i.ended?" ended":""}${i.ending?" ending":""}`:"none"}listOps(e){var t;return ((t=this.queues)==null?void 0:t[e].map(i=>i.label).join(", "))||""}},ng=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,Ap="HlsJsTrackRemovedError",Qc=class extends Error{constructor(e){super(e),this.name=Ap;}},Xc=class extends ht{constructor(e,t){super("buffer-controller",e.logger),this.hls=void 0,this.fragmentTracker=void 0,this.details=null,this._objectUrl=null,this.operationQueue=null,this.bufferCodecEventsTotal=0,this.media=null,this.mediaSource=null,this.lastMpegAudioChunk=null,this.blockedAudioAppend=null,this.lastVideoAppendEnd=0,this.appendSource=void 0,this.transferData=void 0,this.overrides=void 0,this.appendErrors={audio:0,video:0,audiovideo:0},this.tracks={},this.sourceBuffers=[[null,null],[null,null]],this._onEndStreaming=i=>{var r;this.hls&&((r=this.mediaSource)==null?void 0:r.readyState)==="open"&&this.hls.pauseBuffering();},this._onStartStreaming=i=>{this.hls&&this.hls.resumeBuffering();},this._onMediaSourceOpen=i=>{let{media:r,mediaSource:n}=this;i&&this.log("Media source opened"),!(!r||!n)&&(n.removeEventListener("sourceopen",this._onMediaSourceOpen),r.removeEventListener("emptied",this._onMediaEmptied),this.updateDuration(),this.hls.trigger(g.MEDIA_ATTACHED,{media:r,mediaSource:n}),this.mediaSource!==null&&this.checkPendingTracks());},this._onMediaSourceClose=()=>{this.log("Media source closed");},this._onMediaSourceEnded=()=>{this.log("Media source ended");},this._onMediaEmptied=()=>{let{mediaSrc:i,_objectUrl:r}=this;i!==r&&this.error(`Media element src was set while attaching MediaSource (${r} > ${i})`);},this.hls=e,this.fragmentTracker=t,this.appendSource=Zv(Fi(e.config.preferManagedMediaSource)),this.initTracks(),this.registerListeners();}hasSourceTypes(){return Object.keys(this.tracks).length>0}destroy(){this.unregisterListeners(),this.details=null,this.lastMpegAudioChunk=this.blockedAudioAppend=null,this.transferData=this.overrides=void 0,this.operationQueue&&(this.operationQueue.destroy(),this.operationQueue=null),this.hls=this.fragmentTracker=null,this._onMediaSourceOpen=this._onMediaSourceClose=null,this._onMediaSourceEnded=null,this._onStartStreaming=this._onEndStreaming=null;}registerListeners(){let{hls:e}=this;e.on(g.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(g.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(g.MANIFEST_LOADING,this.onManifestLoading,this),e.on(g.MANIFEST_PARSED,this.onManifestParsed,this),e.on(g.BUFFER_RESET,this.onBufferReset,this),e.on(g.BUFFER_APPENDING,this.onBufferAppending,this),e.on(g.BUFFER_CODECS,this.onBufferCodecs,this),e.on(g.BUFFER_EOS,this.onBufferEos,this),e.on(g.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(g.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(g.FRAG_PARSED,this.onFragParsed,this),e.on(g.FRAG_CHANGED,this.onFragChanged,this),e.on(g.ERROR,this.onError,this);}unregisterListeners(){let{hls:e}=this;e.off(g.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(g.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(g.MANIFEST_LOADING,this.onManifestLoading,this),e.off(g.MANIFEST_PARSED,this.onManifestParsed,this),e.off(g.BUFFER_RESET,this.onBufferReset,this),e.off(g.BUFFER_APPENDING,this.onBufferAppending,this),e.off(g.BUFFER_CODECS,this.onBufferCodecs,this),e.off(g.BUFFER_EOS,this.onBufferEos,this),e.off(g.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(g.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(g.FRAG_PARSED,this.onFragParsed,this),e.off(g.FRAG_CHANGED,this.onFragChanged,this),e.off(g.ERROR,this.onError,this);}transferMedia(){let{media:e,mediaSource:t}=this;if(!e)return null;let i={};if(this.operationQueue){let n=this.isUpdating();n||this.operationQueue.removeBlockers();let a=this.isQueued();(n||a)&&this.warn(`Transfering MediaSource with${a?" operations in queue":""}${n?" updating SourceBuffer(s)":""} ${this.operationQueue}`),this.operationQueue.destroy();}let r=this.transferData;return !this.sourceBufferCount&&r&&r.mediaSource===t?ye(i,r.tracks):this.sourceBuffers.forEach(n=>{let[a]=n;a&&(i[a]=ye({},this.tracks[a]),this.removeBuffer(a)),n[0]=n[1]=null;}),{media:e,mediaSource:t,tracks:i}}initTracks(){let e={};this.sourceBuffers=[[null,null],[null,null]],this.tracks=e,this.resetQueue(),this.resetAppendErrors(),this.lastMpegAudioChunk=this.blockedAudioAppend=null,this.lastVideoAppendEnd=0;}onManifestLoading(){this.bufferCodecEventsTotal=0,this.details=null;}onManifestParsed(e,t){var i;let r=2;(t.audio&&!t.video||!t.altAudio)&&(r=1),this.bufferCodecEventsTotal=r,this.log(`${r} bufferCodec event(s) expected.`),(i=this.transferData)!=null&&i.mediaSource&&this.sourceBufferCount&&r&&this.bufferCreated();}onMediaAttaching(e,t){let i=this.media=t.media;this.transferData=this.overrides=void 0;let r=Fi(this.appendSource);if(r){let n=!!t.mediaSource;(n||t.overrides)&&(this.transferData=t,this.overrides=t.overrides);let a=this.mediaSource=t.mediaSource||new r;if(this.assignMediaSource(a),n)this._objectUrl=i.src,this.attachTransferred();else {let o=this._objectUrl=self.URL.createObjectURL(a);if(this.appendSource)try{i.removeAttribute("src");let l=self.ManagedMediaSource;i.disableRemotePlayback=i.disableRemotePlayback||l&&a instanceof l,ag(i),aS(i,o),i.load();}catch{i.src=o;}else i.src=o;}i.addEventListener("emptied",this._onMediaEmptied);}}assignMediaSource(e){var t,i;this.log(`${((t=this.transferData)==null?void 0:t.mediaSource)===e?"transferred":"created"} media source: ${(i=e.constructor)==null?void 0:i.name}`),e.addEventListener("sourceopen",this._onMediaSourceOpen),e.addEventListener("sourceended",this._onMediaSourceEnded),e.addEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(e.addEventListener("startstreaming",this._onStartStreaming),e.addEventListener("endstreaming",this._onEndStreaming));}attachTransferred(){let e=this.media,t=this.transferData;if(!t||!e)return;let i=this.tracks,r=t.tracks,n=r?Object.keys(r):null,a=n?n.length:0,o=()=>{Promise.resolve().then(()=>{this.media&&this.mediaSourceOpenOrEnded&&this._onMediaSourceOpen();});};if(r&&n&&a){if(!this.tracksReady){this.hls.config.startFragPrefetch=true,this.log("attachTransferred: waiting for SourceBuffer track info");return}if(this.log(`attachTransferred: (bufferCodecEventsTotal ${this.bufferCodecEventsTotal})
1374
1374
  required tracks: ${Ae(i,(l,d)=>l==="initSegment"?void 0:d)};
1375
- transfer tracks: ${Ae(r,(l,d)=>l==="initSegment"?void 0:d)}}`),!bg(r,i)){t.mediaSource=null,t.tracks=void 0;let l=e.currentTime,d=this.details,c=Math.max(l,d?.fragments[0].start||0);if(c-l>1){this.log(`attachTransferred: waiting for playback to reach new tracks start time ${l} -> ${c}`);return}this.warn(`attachTransferred: resetting MediaSource for incompatible tracks ("${Object.keys(r)}"->"${Object.keys(i)}") start time: ${c} currentTime: ${l}`),this.onMediaDetaching(g.MEDIA_DETACHING,{}),this.onMediaAttaching(g.MEDIA_ATTACHING,t),e.currentTime=c;return}this.transferData=void 0,n.forEach(l=>{let d=l,c=r[d];if(c){let u=c.buffer;if(u){let h=this.fragmentTracker,f=c.id;if(h.hasFragments(f)||h.hasParts(f)){let E=re.getBuffered(u);h.detectEvictedFragments(d,E,f,null,true);}let m=ic(d),p=[d,u];this.sourceBuffers[m]=p,u.updating&&this.operationQueue&&this.operationQueue.prependBlocker(d),this.trackSourceBuffer(d,c);}}}),o(),this.bufferCreated();}else this.log("attachTransferred: MediaSource w/o SourceBuffers"),o();}get mediaSourceOpenOrEnded(){var e;let t=(e=this.mediaSource)==null?void 0:e.readyState;return t==="open"||t==="ended"}onMediaDetaching(e,t){let i=!!t.transferMedia;this.transferData=this.overrides=void 0;let{media:r,mediaSource:n,_objectUrl:a}=this;if(n){if(this.log(`media source ${i?"transferring":"detaching"}`),i)this.sourceBuffers.forEach(([o])=>{o&&this.removeBuffer(o);}),this.resetQueue();else {if(this.mediaSourceOpenOrEnded){let o=n.readyState==="open";try{let l=n.sourceBuffers;for(let d=l.length;d--;)o&&l[d].abort(),n.removeSourceBuffer(l[d]);o&&n.endOfStream();}catch(l){this.warn(`onMediaDetaching: ${l.message} while calling endOfStream`);}}this.sourceBufferCount&&this.onBufferReset();}n.removeEventListener("sourceopen",this._onMediaSourceOpen),n.removeEventListener("sourceended",this._onMediaSourceEnded),n.removeEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(n.removeEventListener("startstreaming",this._onStartStreaming),n.removeEventListener("endstreaming",this._onEndStreaming)),this.mediaSource=null,this._objectUrl=null;}r&&(r.removeEventListener("emptied",this._onMediaEmptied),i||(a&&self.URL.revokeObjectURL(a),this.mediaSrc===a?(r.removeAttribute("src"),this.appendSource&&ng(r),r.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.media=null),this.hls.trigger(g.MEDIA_DETACHED,t);}onBufferReset(){this.sourceBuffers.forEach(([e])=>{e&&this.resetBuffer(e);}),this.initTracks();}resetBuffer(e){var t;let i=(t=this.tracks[e])==null?void 0:t.buffer;if(this.removeBuffer(e),i)try{var r;(r=this.mediaSource)!=null&&r.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(i);}catch(n){this.warn(`onBufferReset ${e}`,n);}delete this.tracks[e];}removeBuffer(e){this.removeBufferListeners(e),this.sourceBuffers[ic(e)]=[null,null];let t=this.tracks[e];t&&(t.buffer=void 0);}resetQueue(){this.operationQueue&&this.operationQueue.destroy(),this.operationQueue=new zc(this.tracks);}onBufferCodecs(e,t){var i;let r=this.tracks,n=Object.keys(t);this.log(`BUFFER_CODECS: "${n}" (current SB count ${this.sourceBufferCount})`);let a="audiovideo"in t&&(r.audio||r.video)||r.audiovideo&&("audio"in t||"video"in t),o=!a&&this.sourceBufferCount&&this.media&&n.some(l=>!r[l]);if(a||o){this.warn(`Unsupported transition between "${Object.keys(r)}" and "${n}" SourceBuffers`);return}n.forEach(l=>{var d,c;let u=t[l],{id:h,codec:f,levelCodec:m,container:p,metadata:E,supplemental:v}=u,T=r[l],S=(d=this.transferData)==null||(d=d.tracks)==null?void 0:d[l],A=S!=null&&S.buffer?S:T,b=A?.pendingCodec||A?.codec,D=A?.levelCodec;T||(T=r[l]={buffer:void 0,listeners:[],codec:f,supplemental:v,container:p,levelCodec:m,metadata:E,id:h});let I=Po(b,D),k=I?.replace(rg,"$1"),R=Po(f,m),L=(c=R)==null?void 0:c.replace(rg,"$1");R&&I&&k!==L&&(l.slice(0,5)==="audio"&&(R=Ho(R,this.appendSource)),this.log(`switching codec ${b} to ${R}`),R!==(T.pendingCodec||T.codec)&&(T.pendingCodec=R),T.container=p,this.appendChangeType(l,p,R));}),(this.tracksReady||this.sourceBufferCount)&&(t.tracks=this.sourceBufferTracks),!this.sourceBufferCount&&(this.bufferCodecEventsTotal>1&&!this.tracks.video&&!t.video&&((i=t.audio)==null?void 0:i.id)==="main"&&(this.log("Main audio-only"),this.bufferCodecEventsTotal=1),this.mediaSourceOpenOrEnded&&this.checkPendingTracks());}get sourceBufferTracks(){return Object.keys(this.tracks).reduce((e,t)=>{let i=this.tracks[t];return e[t]={id:i.id,container:i.container,codec:i.codec,levelCodec:i.levelCodec},e},{})}appendChangeType(e,t,i){let r=`${t};codecs=${i}`,n={label:`change-type=${r}`,execute:()=>{let a=this.tracks[e];if(a){let o=a.buffer;o!=null&&o.changeType&&(this.log(`changing ${e} sourceBuffer type to ${r}`),o.changeType(r),a.codec=i,a.container=t);}this.shiftAndExecuteNext(e);},onStart:()=>{},onComplete:()=>{},onError:a=>{this.warn(`Failed to change ${e} SourceBuffer type`,a);}};this.append(n,e,this.isPending(this.tracks[e]));}blockAudio(e){var t;let i=e.start,r=i+e.duration*.05;if(((t=this.fragmentTracker.getAppendedFrag(i,W.MAIN))==null?void 0:t.gap)===true)return;let a={label:"block-audio",execute:()=>{var o;let l=this.tracks.video;(this.lastVideoAppendEnd>r||l!=null&&l.buffer&&re.isBuffered(l.buffer,r)||((o=this.fragmentTracker.getAppendedFrag(r,W.MAIN))==null?void 0:o.gap)===true)&&(this.blockedAudioAppend=null,this.shiftAndExecuteNext("audio"));},onStart:()=>{},onComplete:()=>{},onError:o=>{this.warn("Error executing block-audio operation",o);}};this.blockedAudioAppend={op:a,frag:e},this.append(a,"audio",true);}unblockAudio(){let{blockedAudioAppend:e,operationQueue:t}=this;e&&t&&(this.blockedAudioAppend=null,t.unblockAudio(e.op));}onBufferAppending(e,t){let{tracks:i}=this,{data:r,type:n,parent:a,frag:o,part:l,chunkMeta:d,offset:c}=t,u=d.buffering[n],{sn:h,cc:f}=o,m=self.performance.now();u.start=m;let p=o.stats.buffering,E=l?l.stats.buffering:null;p.start===0&&(p.start=m),E&&E.start===0&&(E.start=m);let v=i.audio,T=false;n==="audio"&&v?.container==="audio/mpeg"&&(T=!this.lastMpegAudioChunk||d.id===1||this.lastMpegAudioChunk.sn!==d.sn,this.lastMpegAudioChunk=d);let S=i.video,A=S?.buffer;if(A&&h!=="initSegment"){let I=l||o,k=this.blockedAudioAppend;if(n==="audio"&&a!=="main"&&!this.blockedAudioAppend&&!(S.ending||S.ended)){let L=I.start+I.duration*.05,M=A.buffered,B=this.currentOp("video");!M.length&&!B?this.blockAudio(I):!B&&!re.isBuffered(A,L)&&this.lastVideoAppendEnd<L&&this.blockAudio(I);}else if(n==="video"){let R=I.end;if(k){let L=k.frag.start;(R>L||R<this.lastVideoAppendEnd||re.isBuffered(A,L))&&this.unblockAudio();}this.lastVideoAppendEnd=R;}}let b=(l||o).start,D={label:`append-${n}`,execute:()=>{var I;u.executeStart=self.performance.now();let k=(I=this.tracks[n])==null?void 0:I.buffer;k&&(T?this.updateTimestampOffset(k,b,.1,n,h,f):c!==void 0&&G(c)&&this.updateTimestampOffset(k,c,1e-6,n,h,f)),this.appendExecutor(r,n);},onStart:()=>{},onComplete:()=>{let I=self.performance.now();u.executeEnd=u.end=I,p.first===0&&(p.first=I),E&&E.first===0&&(E.first=I);let k={};this.sourceBuffers.forEach(([R,L])=>{R&&(k[R]=re.getBuffered(L));}),this.appendErrors[n]=0,n==="audio"||n==="video"?this.appendErrors.audiovideo=0:(this.appendErrors.audio=0,this.appendErrors.video=0),this.hls.trigger(g.BUFFER_APPENDED,{type:n,frag:o,part:l,chunkMeta:d,parent:o.type,timeRanges:k});},onError:I=>{var k;let R={type:z.MEDIA_ERROR,parent:o.type,details:x.BUFFER_APPEND_ERROR,sourceBufferName:n,frag:o,part:l,chunkMeta:d,error:I,err:I,fatal:false},L=(k=this.media)==null?void 0:k.error;if(I.code===DOMException.QUOTA_EXCEEDED_ERR||I.name=="QuotaExceededError"||"quota"in I)R.details=x.BUFFER_FULL_ERROR;else if(I.code===DOMException.INVALID_STATE_ERR&&this.mediaSourceOpenOrEnded&&!L)R.errorAction=ir(true);else if(I.name===Sp&&this.sourceBufferCount===0)R.errorAction=ir(true);else {let M=++this.appendErrors[n];this.warn(`Failed ${M}/${this.hls.config.appendErrorMaxRetry} times to append segment in "${n}" sourceBuffer (${L||"no media error"})`),(M>=this.hls.config.appendErrorMaxRetry||L)&&(R.fatal=true);}this.hls.trigger(g.ERROR,R);}};this.log(`queuing "${n}" append sn: ${h}${l?" p: "+l.index:""} of ${o.type===W.MAIN?"level":"track"} ${o.level} cc: ${f}`),this.append(D,n,this.isPending(this.tracks[n]));}getFlushOp(e,t,i){return this.log(`queuing "${e}" remove ${t}-${i}`),{label:"remove",execute:()=>{this.removeExecutor(e,t,i);},onStart:()=>{},onComplete:()=>{this.hls.trigger(g.BUFFER_FLUSHED,{type:e});},onError:r=>{this.warn(`Failed to remove ${t}-${i} from "${e}" SourceBuffer`,r);}}}onBufferFlushing(e,t){let{type:i,startOffset:r,endOffset:n}=t;i?this.append(this.getFlushOp(i,r,n),i):this.sourceBuffers.forEach(([a])=>{a&&this.append(this.getFlushOp(a,r,n),a);});}onFragParsed(e,t){let{frag:i,part:r}=t,n=[],a=r?r.elementaryStreams:i.elementaryStreams;a[Se.AUDIOVIDEO]?n.push("audiovideo"):(a[Se.AUDIO]&&n.push("audio"),a[Se.VIDEO]&&n.push("video"));let o=()=>{let l=self.performance.now();i.stats.buffering.end=l,r&&(r.stats.buffering.end=l);let d=r?r.stats:i.stats;this.hls.trigger(g.FRAG_BUFFERED,{frag:i,part:r,stats:d,id:i.type});};n.length===0&&this.warn(`Fragments must have at least one ElementaryStreamType set. type: ${i.type} level: ${i.level} sn: ${i.sn}`),this.blockBuffers(o,n).catch(l=>{this.warn(`Fragment buffered callback ${l}`),this.stepOperationQueue(this.sourceBufferTypes);});}onFragChanged(e,t){this.trimBuffers();}get bufferedToEnd(){return this.sourceBufferCount>0&&!this.sourceBuffers.some(([e])=>{if(e){let t=this.tracks[e];if(t)return !t.ended||t.ending}return false})}onBufferEos(e,t){var i;this.sourceBuffers.forEach(([a])=>{if(a){let o=this.tracks[a];(!t.type||t.type===a)&&(o.ending=true,o.ended||(o.ended=true,this.log(`${a} buffer reached EOS`)));}});let r=((i=this.overrides)==null?void 0:i.endOfStream)!==false;this.sourceBufferCount>0&&!this.sourceBuffers.some(([a])=>{var o;return a&&!((o=this.tracks[a])!=null&&o.ended)})?r?(this.log("Queueing EOS"),this.blockUntilOpen(()=>{this.tracksEnded();let{mediaSource:a}=this;if(!a||a.readyState!=="open"){a&&this.log(`Could not call mediaSource.endOfStream(). mediaSource.readyState: ${a.readyState}`);return}this.log("Calling mediaSource.endOfStream()"),a.endOfStream(),this.hls.trigger(g.BUFFERED_TO_END,void 0);})):(this.tracksEnded(),this.hls.trigger(g.BUFFERED_TO_END,void 0)):t.type==="video"&&this.unblockAudio();}tracksEnded(){this.sourceBuffers.forEach(([e])=>{if(e!==null){let t=this.tracks[e];t&&(t.ending=false);}});}onLevelUpdated(e,{details:t}){t.fragments.length&&(this.details=t,this.updateDuration());}updateDuration(){this.blockUntilOpen(()=>{let e=this.getDurationAndRange();e&&this.updateMediaSource(e);});}onError(e,t){if(t.details===x.BUFFER_APPEND_ERROR&&t.frag){var i;let r=(i=t.errorAction)==null?void 0:i.nextAutoLevel;G(r)&&r!==t.frag.level&&this.resetAppendErrors();}}resetAppendErrors(){this.appendErrors={audio:0,video:0,audiovideo:0};}trimBuffers(){let{hls:e,details:t,media:i}=this;if(!i||t===null||!this.sourceBufferCount)return;let r=e.config,n=i.currentTime,a=t.levelTargetDuration,o=t.live&&r.liveBackBufferLength!==null?r.liveBackBufferLength:r.backBufferLength;if(G(o)&&o>=0){let d=Math.max(o,a),c=Math.floor(n/a)*a-d;this.flushBackBuffer(n,a,c);}let l=r.frontBufferFlushThreshold;if(G(l)&&l>0){let d=Math.max(r.maxBufferLength,l),c=Math.max(d,a),u=Math.floor(n/a)*a+c;this.flushFrontBuffer(n,a,u);}}flushBackBuffer(e,t,i){this.sourceBuffers.forEach(([r,n])=>{if(n){let o=re.getBuffered(n);if(o.length>0&&i>o.start(0)){var a;this.hls.trigger(g.BACK_BUFFER_REACHED,{bufferEnd:i});let l=this.tracks[r];if((a=this.details)!=null&&a.live)this.hls.trigger(g.LIVE_BACK_BUFFER_REACHED,{bufferEnd:i});else if(l!=null&&l.ended){this.log(`Cannot flush ${r} back buffer while SourceBuffer is in ended state`);return}this.hls.trigger(g.BUFFER_FLUSHING,{startOffset:0,endOffset:i,type:r});}}});}flushFrontBuffer(e,t,i){this.sourceBuffers.forEach(([r,n])=>{if(n){let a=re.getBuffered(n),o=a.length;if(o<2)return;let l=a.start(o-1),d=a.end(o-1);if(i>l||e>=l&&e<=d)return;this.hls.trigger(g.BUFFER_FLUSHING,{startOffset:l,endOffset:1/0,type:r});}});}getDurationAndRange(){var e;let{details:t,mediaSource:i}=this;if(!t||!this.media||i?.readyState!=="open")return null;let r=t.edge;if(t.live&&this.hls.config.liveDurationInfinity){if(t.fragments.length&&i.setLiveSeekableRange){let d=Math.max(0,t.fragmentStart),c=Math.max(d,r);return {duration:1/0,start:d,end:c}}return {duration:1/0}}let n=(e=this.overrides)==null?void 0:e.duration;if(n)return G(n)?{duration:n}:null;let a=this.media.duration,o=G(i.duration)?i.duration:0;return r>o&&r>a||!G(a)?{duration:r}:null}updateMediaSource({duration:e,start:t,end:i}){let r=this.mediaSource;!this.media||!r||r.readyState!=="open"||(r.duration!==e&&(G(e)&&this.log(`Updating MediaSource duration to ${e.toFixed(3)}`),r.duration=e),t!==void 0&&i!==void 0&&(this.log(`MediaSource duration is set to ${r.duration}. Setting seekable range to ${t}-${i}.`),r.setLiveSeekableRange(t,i)));}get tracksReady(){let e=this.pendingTrackCount;return e>0&&(e>=this.bufferCodecEventsTotal||this.isPending(this.tracks.audiovideo))}checkPendingTracks(){let{bufferCodecEventsTotal:e,pendingTrackCount:t,tracks:i}=this;if(this.log(`checkPendingTracks (pending: ${t} codec events expected: ${e}) ${Ae(i)}`),this.tracksReady){var r;let n=(r=this.transferData)==null?void 0:r.tracks;n&&Object.keys(n).length?this.attachTransferred():this.createSourceBuffers();}}bufferCreated(){if(this.sourceBufferCount){let e={};this.sourceBuffers.forEach(([t,i])=>{if(t){let r=this.tracks[t];e[t]={buffer:i,container:r.container,codec:r.codec,supplemental:r.supplemental,levelCodec:r.levelCodec,id:r.id,metadata:r.metadata};}}),this.hls.trigger(g.BUFFER_CREATED,{tracks:e}),this.log(`SourceBuffers created. Running queue: ${this.operationQueue}`),this.sourceBuffers.forEach(([t])=>{this.executeNext(t);});}else {let e=new Error("could not create source buffer for media codec(s)");this.hls.trigger(g.ERROR,{type:z.MEDIA_ERROR,details:x.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:true,error:e,reason:e.message});}}createSourceBuffers(){let{tracks:e,sourceBuffers:t,mediaSource:i}=this;if(!i)throw new Error("createSourceBuffers called when mediaSource was null");for(let n in e){let a=n,o=e[a];if(this.isPending(o)){let l=this.getTrackCodec(o,a),d=`${o.container};codecs=${l}`;o.codec=l,this.log(`creating sourceBuffer(${d})${this.currentOp(a)?" Queued":""} ${Ae(o)}`);try{let c=i.addSourceBuffer(d),u=ic(a),h=[a,c];t[u]=h,o.buffer=c;}catch(c){var r;this.error(`error while trying to add sourceBuffer: ${c.message}`),this.shiftAndExecuteNext(a),(r=this.operationQueue)==null||r.removeBlockers(),delete this.tracks[a],this.hls.trigger(g.ERROR,{type:z.MEDIA_ERROR,details:x.BUFFER_ADD_CODEC_ERROR,fatal:false,error:c,sourceBufferName:a,mimeType:d,parent:o.id});return}this.trackSourceBuffer(a,o);}}this.bufferCreated();}getTrackCodec(e,t){let i=e.supplemental,r=e.codec;i&&(t==="video"||t==="audiovideo")&&gn(i,"video")&&(r=vT(r,i));let n=Po(r,e.levelCodec);return n?t.slice(0,5)==="audio"?Ho(n,this.appendSource):n:""}trackSourceBuffer(e,t){let i=t.buffer;if(!i)return;let r=this.getTrackCodec(t,e);this.tracks[e]={buffer:i,codec:r,container:t.container,levelCodec:t.levelCodec,supplemental:t.supplemental,metadata:t.metadata,id:t.id,listeners:[]},this.removeBufferListeners(e),this.addBufferListener(e,"updatestart",this.onSBUpdateStart),this.addBufferListener(e,"updateend",this.onSBUpdateEnd),this.addBufferListener(e,"error",this.onSBUpdateError),this.appendSource&&this.addBufferListener(e,"bufferedchange",(n,a)=>{let o=a.removedRanges;o!=null&&o.length&&this.hls.trigger(g.BUFFER_FLUSHED,{type:n});});}get mediaSrc(){var e,t;let i=((e=this.media)==null||(t=e.querySelector)==null?void 0:t.call(e,"source"))||this.media;return i?.src}onSBUpdateStart(e){let t=this.currentOp(e);t&&t.onStart();}onSBUpdateEnd(e){var t;if(((t=this.mediaSource)==null?void 0:t.readyState)==="closed"){this.resetBuffer(e);return}let i=this.currentOp(e);i&&(i.onComplete(),this.shiftAndExecuteNext(e));}onSBUpdateError(e,t){var i;let r=new Error(`${e} SourceBuffer error. MediaSource readyState: ${(i=this.mediaSource)==null?void 0:i.readyState}`);this.error(`${r}`,t),this.hls.trigger(g.ERROR,{type:z.MEDIA_ERROR,details:x.BUFFER_APPENDING_ERROR,sourceBufferName:e,error:r,fatal:false});let n=this.currentOp(e);n&&n.onError(r);}updateTimestampOffset(e,t,i,r,n,a){let o=t-e.timestampOffset;Math.abs(o)>=i&&(this.log(`Updating ${r} SourceBuffer timestampOffset to ${t} (sn: ${n} cc: ${a})`),e.timestampOffset=t);}removeExecutor(e,t,i){let{media:r,mediaSource:n}=this,a=this.tracks[e],o=a?.buffer;if(!r||!n||!o){this.warn(`Attempting to remove from the ${e} SourceBuffer, but it does not exist`),this.shiftAndExecuteNext(e);return}let l=G(r.duration)?r.duration:1/0,d=G(n.duration)?n.duration:1/0,c=Math.max(0,t),u=Math.min(i,l,d);u>c&&(!a.ending||a.ended)?(a.ended=false,this.log(`Removing [${c},${u}] from the ${e} SourceBuffer`),o.remove(c,u)):this.shiftAndExecuteNext(e);}appendExecutor(e,t){let i=this.tracks[t],r=i?.buffer;if(!r)throw new Qc(`Attempting to append to the ${t} SourceBuffer, but it does not exist`);i.ending=false,i.ended=false,r.appendBuffer(e);}blockUntilOpen(e){if(this.isUpdating()||this.isQueued())this.blockBuffers(e).catch(t=>{this.warn(`SourceBuffer blocked callback ${t}`),this.stepOperationQueue(this.sourceBufferTypes);});else try{e();}catch(t){this.warn(`Callback run without blocking ${this.operationQueue} ${t}`);}}isUpdating(){return this.sourceBuffers.some(([e,t])=>e&&t.updating)}isQueued(){return this.sourceBuffers.some(([e])=>e&&!!this.currentOp(e))}isPending(e){return !!e&&!e.buffer}blockBuffers(e,t=this.sourceBufferTypes){if(!t.length)return this.log("Blocking operation requested, but no SourceBuffers exist"),Promise.resolve().then(e);let{operationQueue:i}=this,r=t.map(a=>this.appendBlocker(a));return t.length>1&&!!this.blockedAudioAppend&&this.unblockAudio(),Promise.all(r).then(a=>{i===this.operationQueue&&(e(),this.stepOperationQueue(this.sourceBufferTypes));})}stepOperationQueue(e){e.forEach(t=>{var i;let r=(i=this.tracks[t])==null?void 0:i.buffer;!r||r.updating||this.shiftAndExecuteNext(t);});}append(e,t,i){this.operationQueue&&this.operationQueue.append(e,t,i);}appendBlocker(e){if(this.operationQueue)return this.operationQueue.appendBlocker(e)}currentOp(e){return this.operationQueue?this.operationQueue.current(e):null}executeNext(e){e&&this.operationQueue&&this.operationQueue.executeNext(e);}shiftAndExecuteNext(e){this.operationQueue&&this.operationQueue.shiftAndExecuteNext(e);}get pendingTrackCount(){return Object.keys(this.tracks).reduce((e,t)=>e+(this.isPending(this.tracks[t])?1:0),0)}get sourceBufferCount(){return this.sourceBuffers.reduce((e,[t])=>e+(t?1:0),0)}get sourceBufferTypes(){return this.sourceBuffers.map(([e])=>e).filter(e=>!!e)}addBufferListener(e,t,i){let r=this.tracks[e];if(!r)return;let n=r.buffer;if(!n)return;let a=i.bind(this,e);r.listeners.push({event:t,listener:a}),n.addEventListener(t,a);}removeBufferListeners(e){let t=this.tracks[e];if(!t)return;let i=t.buffer;i&&(t.listeners.forEach(r=>{i.removeEventListener(r.event,r.listener);}),t.listeners.length=0);}};function ng(s){let e=s.querySelectorAll("source");[].slice.call(e).forEach(t=>{s.removeChild(t);});}function nS(s,e){let t=self.document.createElement("source");t.type="video/mp4",t.src=e,s.appendChild(t);}function ic(s){return s==="audio"?1:0}var Zc=class s{constructor(e){this.hls=void 0,this.autoLevelCapping=void 0,this.firstLevel=void 0,this.media=void 0,this.restrictedLevels=void 0,this.timer=void 0,this.clientRect=void 0,this.streamController=void 0,this.hls=e,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.firstLevel=-1,this.media=null,this.restrictedLevels=[],this.timer=void 0,this.clientRect=null,this.registerListeners();}setStreamController(e){this.streamController=e;}destroy(){this.hls&&this.unregisterListener(),this.timer&&this.stopCapping(),this.media=null,this.clientRect=null,this.hls=this.streamController=null;}registerListeners(){let{hls:e}=this;e.on(g.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.on(g.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(g.MANIFEST_PARSED,this.onManifestParsed,this),e.on(g.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(g.BUFFER_CODECS,this.onBufferCodecs,this),e.on(g.MEDIA_DETACHING,this.onMediaDetaching,this);}unregisterListener(){let{hls:e}=this;e.off(g.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.off(g.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(g.MANIFEST_PARSED,this.onManifestParsed,this),e.off(g.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(g.BUFFER_CODECS,this.onBufferCodecs,this),e.off(g.MEDIA_DETACHING,this.onMediaDetaching,this);}onFpsDropLevelCapping(e,t){let i=this.hls.levels[t.droppedLevel];this.isLevelAllowed(i)&&this.restrictedLevels.push({bitrate:i.bitrate,height:i.height,width:i.width});}onMediaAttaching(e,t){this.media=t.media instanceof HTMLVideoElement?t.media:null,this.clientRect=null,this.timer&&this.hls.levels.length&&this.detectPlayerSize();}onManifestParsed(e,t){let i=this.hls;this.restrictedLevels=[],this.firstLevel=t.firstLevel,i.config.capLevelToPlayerSize&&t.video&&this.startCapping();}onLevelsUpdated(e,t){this.timer&&G(this.autoLevelCapping)&&this.detectPlayerSize();}onBufferCodecs(e,t){this.hls.config.capLevelToPlayerSize&&t.video&&this.startCapping();}onMediaDetaching(){this.stopCapping(),this.media=null;}detectPlayerSize(){if(this.media){if(this.mediaHeight<=0||this.mediaWidth<=0){this.clientRect=null;return}let e=this.hls.levels;if(e.length){let t=this.hls,i=this.getMaxLevel(e.length-1);i!==this.autoLevelCapping&&t.logger.log(`Setting autoLevelCapping to ${i}: ${e[i].height}p@${e[i].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`),t.autoLevelCapping=i,t.autoLevelEnabled&&t.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=t.autoLevelCapping;}}}getMaxLevel(e){let t=this.hls.levels;if(!t.length)return -1;let i=t.filter((r,n)=>this.isLevelAllowed(r)&&n<=e);return this.clientRect=null,s.getMaxLevelByMediaSize(i,this.mediaWidth,this.mediaHeight)}startCapping(){this.timer||(this.autoLevelCapping=Number.POSITIVE_INFINITY,self.clearInterval(this.timer),this.timer=self.setInterval(this.detectPlayerSize.bind(this),1e3),this.detectPlayerSize());}stopCapping(){this.restrictedLevels=[],this.firstLevel=-1,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer&&(self.clearInterval(this.timer),this.timer=void 0);}getDimensions(){if(this.clientRect)return this.clientRect;let e=this.media,t={width:0,height:0};if(e){let i=e.getBoundingClientRect();t.width=i.width,t.height=i.height,!t.width&&!t.height&&(t.width=i.right-i.left||e.width||0,t.height=i.bottom-i.top||e.height||0);}return this.clientRect=t,t}get mediaWidth(){return this.getDimensions().width*this.contentScaleFactor}get mediaHeight(){return this.getDimensions().height*this.contentScaleFactor}get contentScaleFactor(){let e=1;if(!this.hls.config.ignoreDevicePixelRatio)try{e=self.devicePixelRatio;}catch{}return Math.min(e,this.hls.config.maxDevicePixelRatio)}isLevelAllowed(e){return !this.restrictedLevels.some(i=>e.bitrate===i.bitrate&&e.width===i.width&&e.height===i.height)}static getMaxLevelByMediaSize(e,t,i){if(!(e!=null&&e.length))return -1;let r=(o,l)=>l?o.width!==l.width||o.height!==l.height:true,n=e.length-1,a=Math.max(t,i);for(let o=0;o<e.length;o+=1){let l=e[o];if((l.width>=a||l.height>=a)&&r(l,e[o+1])){n=o;break}}return n}},aS={MANIFEST:"m",AUDIO:"a",VIDEO:"v",MUXED:"av",INIT:"i",CAPTION:"c",TIMED_TEXT:"tt",KEY:"k",OTHER:"o"},ct=aS,oS={HLS:"h"},lS=oS,yi=class s{constructor(e,t){Array.isArray(e)&&(e=e.map(i=>i instanceof s?i:new s(i))),this.value=e,this.params=t;}},dS="Dict";function cS(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 uS(s,e,t,i){return new Error(`failed to ${s} "${cS(e)}" as ${t}`,{cause:i})}function ci(s,e,t){return uS("serialize",s,e,t)}var rl=class{constructor(e){this.description=e;}},ag="Bare Item",hS="Boolean";function fS(s){if(typeof s!="boolean")throw ci(s,hS);return s?"?1":"?0"}function mS(s){return btoa(String.fromCharCode(...s))}var gS="Byte Sequence";function pS(s){if(ArrayBuffer.isView(s)===false)throw ci(s,gS);return `:${mS(s)}:`}var ES="Integer";function vS(s){return s<-999999999999999||999999999999999<s}function Ap(s){if(vS(s))throw ci(s,ES);return s.toString()}function TS(s){return `@${Ap(s.getTime()/1e3)}`}function bp(s,e){if(s<0)return -bp(-s,e);let t=Math.pow(10,e);if(Math.abs(s*t%1-.5)<Number.EPSILON){let r=Math.floor(s*t);return (r%2===0?r:r+1)/t}else return Math.round(s*t)/t}var yS="Decimal";function SS(s){let e=bp(s,3);if(Math.floor(Math.abs(e)).toString().length>12)throw ci(s,yS);let t=e.toString();return t.includes(".")?t:`${t}.0`}var AS="String",bS=/[\x00-\x1f\x7f]+/;function _S(s){if(bS.test(s))throw ci(s,AS);return `"${s.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function IS(s){return s.description||s.toString().slice(7,-1)}var LS="Token";function og(s){let e=IS(s);if(/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(e)===false)throw ci(e,LS);return e}function Jc(s){switch(typeof s){case "number":if(!G(s))throw ci(s,ag);return Number.isInteger(s)?Ap(s):SS(s);case "string":return _S(s);case "symbol":return og(s);case "boolean":return fS(s);case "object":if(s instanceof Date)return TS(s);if(s instanceof Uint8Array)return pS(s);if(s instanceof rl)return og(s);default:throw ci(s,ag)}}var xS="Key";function eu(s){if(/^[a-z*][a-z0-9\-_.*]*$/.test(s)===false)throw ci(s,xS);return s}function Wu(s){return s==null?"":Object.entries(s).map(([e,t])=>t===true?`;${eu(e)}`:`;${eu(e)}=${Jc(t)}`).join("")}function _p(s){return s instanceof yi?`${Jc(s.value)}${Wu(s.params)}`:Jc(s)}function RS(s){return `(${s.value.map(_p).join(" ")})${Wu(s.params)}`}function kS(s,e={whitespace:true}){if(typeof s!="object"||s==null)throw ci(s,dS);let t=s instanceof Map?s.entries():Object.entries(s),i=e?.whitespace?" ":"";return Array.from(t).map(([r,n])=>{n instanceof yi||(n=new yi(n));let a=eu(r);return n.value===true?a+=Wu(n.params):(a+="=",Array.isArray(n.value)?a+=RS(n):a+=_p(n)),a}).join(`,${i}`)}function Ip(s,e){return kS(s,e)}var ai="CMCD-Object",Me="CMCD-Request",ss="CMCD-Session",Pi="CMCD-Status",DS={br:ai,ab:ai,d:ai,ot:ai,tb:ai,tpb:ai,lb:ai,tab:ai,lab:ai,url:ai,pb:Me,bl:Me,tbl:Me,dl:Me,ltc:Me,mtp:Me,nor:Me,nrr:Me,rc:Me,sn:Me,sta:Me,su:Me,ttfb:Me,ttfbb:Me,ttlb:Me,cmsdd:Me,cmsds:Me,smrt:Me,df:Me,cs:Me,ts:Me,cid:ss,pr:ss,sf:ss,sid:ss,st:ss,v:ss,msd:ss,bs:Pi,bsd:Pi,cdn:Pi,rtp:Pi,bg:Pi,pt:Pi,ec:Pi,e:Pi},CS={REQUEST:Me};function MS(s){return Object.keys(s).reduce((e,t)=>{var i;return (i=s[t])===null||i===void 0||i.forEach(r=>e[r]=t),e},{})}function PS(s,e){let t={};if(!s)return t;let i=Object.keys(s),r=e?MS(e):{};return i.reduce((n,a)=>{var o;let l=DS[a]||r[a]||CS.REQUEST,d=(o=n[l])!==null&&o!==void 0?o:n[l]={};return d[a]=s[a],n},t)}function wS(s){return ["ot","sf","st","e","sta"].includes(s)}function OS(s){return typeof s=="number"?G(s):s!=null&&s!==""&&s!==false}var Lp="event";function FS(s,e){let t=new URL(s),i=new URL(e);if(t.origin!==i.origin)return s;let 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("/")+t.search+t.hash}var No=s=>Math.round(s),tu=(s,e)=>Array.isArray(s)?s.map(t=>tu(t,e)):s instanceof yi&&typeof s.value=="string"?new yi(tu(s.value,e),s.params):(e.baseUrl&&(s=FS(s,e.baseUrl)),e.version===1?encodeURIComponent(s):s),Lo=s=>No(s/100)*100,NS=(s,e)=>{let t=s;return e.version>=2&&(s instanceof yi&&typeof s.value=="string"?t=new yi([s]):typeof s=="string"&&(t=[s])),tu(t,e)},US={br:No,d:No,bl:Lo,dl:Lo,mtp:Lo,nor:NS,rtp:Lo,tb:No},xp="request",Rp="response",Yu=["ab","bg","bl","br","bs","bsd","cdn","cid","cs","df","ec","lab","lb","ltc","msd","mtp","pb","pr","pt","sf","sid","sn","st","sta","tab","tb","tbl","tpb","ts","v"],BS=["e"],$S=/^[a-zA-Z0-9-.]+-[a-zA-Z0-9-.]+$/;function ml(s){return $S.test(s)}function GS(s){return Yu.includes(s)||BS.includes(s)||ml(s)}var kp=["d","dl","nor","ot","rtp","su"];function HS(s){return Yu.includes(s)||kp.includes(s)||ml(s)}var KS=["cmsdd","cmsds","rc","smrt","ttfb","ttfbb","ttlb","url"];function VS(s){return Yu.includes(s)||kp.includes(s)||KS.includes(s)||ml(s)}var WS=["bl","br","bs","cid","d","dl","mtp","nor","nrr","ot","pr","rtp","sf","sid","st","su","tb","v"];function YS(s){return WS.includes(s)||ml(s)}var qS={[Rp]:VS,[Lp]:GS,[xp]:HS};function Dp(s,e={}){let t={};if(s==null||typeof s!="object")return t;let i=e.version||s.v||1,r=e.reportingMode||xp,n=i===1?YS:qS[r],a=Object.keys(s).filter(n),o=e.filter;typeof o=="function"&&(a=a.filter(o));let l=r===Rp||r===Lp;l&&!a.includes("ts")&&a.push("ts"),i>1&&!a.includes("v")&&a.push("v");let d=ye({},US,e.formatters),c={version:i,reportingMode:r,baseUrl:e.baseUrl};return a.sort().forEach(u=>{let h=s[u],f=d[u];if(typeof f=="function"&&(h=f(h,c)),u==="v"){if(i===1)return;h=i;}u=="pr"&&h===1||(l&&u==="ts"&&!G(h)&&(h=Date.now()),OS(h)&&(wS(u)&&typeof h=="string"&&(h=new rl(h)),t[u]=h));}),t}function jS(s,e={}){let t={};if(!s)return t;let i=Dp(s,e),r=PS(i,e?.customHeaderMap);return Object.entries(r).reduce((n,[a,o])=>{let l=Ip(o,{whitespace:false});return l&&(n[a]=l),n},t)}function zS(s,e,t){return ye(s,jS(e,t))}var QS="CMCD";function XS(s,e={}){return s?Ip(Dp(s,e),{whitespace:false}):""}function ZS(s,e={}){if(!s)return "";let t=XS(s,e);return encodeURIComponent(t)}function JS(s,e={}){if(!s)return "";let t=ZS(s,e);return `${QS}=${t}`}var lg=/CMCD=[^&#]+/;function eA(s,e,t){let i=JS(e,t);if(!i)return s;if(lg.test(s))return s.replace(lg,i);let r=s.includes("?")?"&":"?";return `${s}${r}${i}`}var iu=class{constructor(e){this.hls=void 0,this.config=void 0,this.media=void 0,this.sid=void 0,this.cid=void 0,this.useHeaders=false,this.includeKeys=void 0,this.initialized=false,this.starved=false,this.buffering=true,this.audioBuffer=void 0,this.videoBuffer=void 0,this.onWaiting=()=>{this.initialized&&(this.starved=true),this.buffering=true;},this.onPlaying=()=>{this.initialized||(this.initialized=true),this.buffering=false;},this.applyPlaylistData=r=>{try{this.apply(r,{ot:ct.MANIFEST,su:!this.initialized});}catch(n){this.hls.logger.warn("Could not generate manifest CMCD data.",n);}},this.applyFragmentData=r=>{try{let{frag:n,part:a}=r,o=this.hls.levels[n.level],l=this.getObjectType(n),d={d:(a||n).duration*1e3,ot:l};(l===ct.VIDEO||l===ct.AUDIO||l==ct.MUXED)&&(d.br=o.bitrate/1e3,d.tb=this.getTopBandwidth(l)/1e3,d.bl=this.getBufferLength(l));let c=a?this.getNextPart(a):this.getNextFrag(n);c!=null&&c.url&&c.url!==n.url&&(d.nor=c.url),this.apply(r,d);}catch(n){this.hls.logger.warn("Could not generate segment CMCD data.",n);}},this.hls=e;let t=this.config=e.config,{cmcd:i}=t;i!=null&&(t.pLoader=this.createPlaylistLoader(),t.fLoader=this.createFragmentLoader(),this.sid=i.sessionId||e.sessionId,this.cid=i.contentId,this.useHeaders=i.useHeaders===true,this.includeKeys=i.includeKeys,this.registerListeners());}registerListeners(){let e=this.hls;e.on(g.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(g.MEDIA_DETACHED,this.onMediaDetached,this),e.on(g.BUFFER_CREATED,this.onBufferCreated,this);}unregisterListeners(){let e=this.hls;e.off(g.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(g.MEDIA_DETACHED,this.onMediaDetached,this),e.off(g.BUFFER_CREATED,this.onBufferCreated,this);}destroy(){this.unregisterListeners(),this.onMediaDetached(),this.hls=this.config=this.audioBuffer=this.videoBuffer=null,this.onWaiting=this.onPlaying=this.media=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={}){ye(t,this.createData());let i=t.ot===ct.INIT||t.ot===ct.VIDEO||t.ot===ct.MUXED;this.starved&&i&&(t.bs=true,t.su=true,this.starved=false),t.su==null&&(t.su=this.buffering);let{includeKeys:r}=this;r&&(t=Object.keys(t).reduce((a,o)=>(r.includes(o)&&(a[o]=t[o]),a),{}));let n={baseUrl:e.url};this.useHeaders?(e.headers||(e.headers={}),zS(e.headers,t,n)):e.url=eA(e.url,t,n);}getNextFrag(e){var t;let i=(t=this.hls.levels[e.level])==null?void 0:t.details;if(i){let r=e.sn-i.startSN;return i.fragments[r+1]}}getNextPart(e){var t;let{index:i,fragment:r}=e,n=(t=this.hls.levels[r.level])==null||(t=t.details)==null?void 0:t.partList;if(n){let{sn:a}=r;for(let o=n.length-1;o>=0;o--){let l=n[o];if(l.index===i&&l.fragment.sn===a)return n[o+1]}}}getObjectType(e){let{type:t}=e;if(t==="subtitle")return ct.TIMED_TEXT;if(e.sn==="initSegment")return ct.INIT;if(t==="audio")return ct.AUDIO;if(t==="main")return this.hls.audioTracks.length?ct.VIDEO:ct.MUXED}getTopBandwidth(e){let t=0,i,r=this.hls;if(e===ct.AUDIO)i=r.audioTracks;else {let n=r.maxAutoLevel,a=n>-1?n+1:r.levels.length;i=r.levels.slice(0,a);}return i.forEach(n=>{n.bitrate>t&&(t=n.bitrate);}),t>0?t:NaN}getBufferLength(e){let t=this.media,i=e===ct.AUDIO?this.audioBuffer:this.videoBuffer;return !i||!t?NaN:re.bufferInfo(i,t.currentTime,this.config.maxBufferHole).len*1e3}createPlaylistLoader(){let{pLoader:e}=this.config,t=this.applyPlaylistData,i=e||this.config.loader;return class{constructor(n){this.loader=void 0,this.loader=new i(n);}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy();}abort(){this.loader.abort();}load(n,a,o){t(n),this.loader.load(n,a,o);}}}createFragmentLoader(){let{fLoader:e}=this.config,t=this.applyFragmentData,i=e||this.config.loader;return class{constructor(n){this.loader=void 0,this.loader=new i(n);}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy();}abort(){this.loader.abort();}load(n,a,o){t(n),this.loader.load(n,a,o);}}}},tA=3e5,su=class extends ht{constructor(e){super("content-steering",e.logger),this.hls=void 0,this.loader=null,this.uri=null,this.pathwayId=".",this._pathwayPriority=null,this.timeToLoad=300,this.reloadTimer=-1,this.updated=0,this.started=false,this.enabled=true,this.levels=null,this.audioTracks=null,this.subtitleTracks=null,this.penalizedPathways={},this.hls=e,this.registerListeners();}registerListeners(){let e=this.hls;e.on(g.MANIFEST_LOADING,this.onManifestLoading,this),e.on(g.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(g.MANIFEST_PARSED,this.onManifestParsed,this),e.on(g.ERROR,this.onError,this);}unregisterListeners(){let e=this.hls;e&&(e.off(g.MANIFEST_LOADING,this.onManifestLoading,this),e.off(g.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(g.MANIFEST_PARSED,this.onManifestParsed,this),e.off(g.ERROR,this.onError,this));}pathways(){return (this.levels||[]).reduce((e,t)=>(e.indexOf(t.pathwayId)===-1&&e.push(t.pathwayId),e),[])}get pathwayPriority(){return this._pathwayPriority}set pathwayPriority(e){this.updatePathwayPriority(e);}startLoad(){if(this.started=true,this.clearTimeout(),this.enabled&&this.uri){if(this.updated){let e=this.timeToLoad*1e3-(performance.now()-this.updated);if(e>0){this.scheduleRefresh(this.uri,e);return}}this.loadSteeringManifest(this.uri);}}stopLoad(){this.started=false,this.loader&&(this.loader.destroy(),this.loader=null),this.clearTimeout();}clearTimeout(){this.reloadTimer!==-1&&(self.clearTimeout(this.reloadTimer),this.reloadTimer=-1);}destroy(){this.unregisterListeners(),this.stopLoad(),this.hls=null,this.levels=this.audioTracks=this.subtitleTracks=null;}removeLevel(e){let t=this.levels;t&&(this.levels=t.filter(i=>i!==e));}onManifestLoading(){this.stopLoad(),this.enabled=true,this.timeToLoad=300,this.updated=0,this.uri=null,this.pathwayId=".",this.levels=this.audioTracks=this.subtitleTracks=null;}onManifestLoaded(e,t){let{contentSteering:i}=t;i!==null&&(this.pathwayId=i.pathwayId,this.uri=i.uri,this.started&&this.startLoad());}onManifestParsed(e,t){this.audioTracks=t.audioTracks,this.subtitleTracks=t.subtitleTracks;}onError(e,t){let{errorAction:i}=t;if(i?.action===ze.SendAlternateToPenaltyBox&&i.flags===yt.MoveAllAlternatesMatchingHost){let r=this.levels,n=this._pathwayPriority,a=this.pathwayId;if(t.context){let{groupId:o,pathwayId:l,type:d}=t.context;o&&r?a=this.getPathwayForGroupId(o,d,a):l&&(a=l);}a in this.penalizedPathways||(this.penalizedPathways[a]=performance.now()),!n&&r&&(n=this.pathways()),n&&n.length>1&&(this.updatePathwayPriority(n),i.resolved=this.pathwayId!==a),t.details===x.BUFFER_APPEND_ERROR&&!t.fatal?i.resolved=true:i.resolved||this.warn(`Could not resolve ${t.details} ("${t.error.message}") with content-steering for Pathway: ${a} levels: ${r&&r.length} priorities: ${Ae(n)} penalized: ${Ae(this.penalizedPathways)}`);}}filterParsedLevels(e){this.levels=e;let t=this.getLevelsForPathway(this.pathwayId);if(t.length===0){let i=e[0].pathwayId;this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${i}"`),t=this.getLevelsForPathway(i),this.pathwayId=i;}return t.length!==e.length&&this.log(`Found ${t.length}/${e.length} levels in Pathway "${this.pathwayId}"`),t}getLevelsForPathway(e){return this.levels===null?[]:this.levels.filter(t=>e===t.pathwayId)}updatePathwayPriority(e){this._pathwayPriority=e;let t,i=this.penalizedPathways,r=performance.now();Object.keys(i).forEach(n=>{r-i[n]>tA&&delete i[n];});for(let n=0;n<e.length;n++){let a=e[n];if(a in i)continue;if(a===this.pathwayId)return;let o=this.hls.nextLoadLevel,l=this.hls.levels[o];if(t=this.getLevelsForPathway(a),t.length>0){this.log(`Setting Pathway to "${a}"`),this.pathwayId=a,ep(t),this.hls.trigger(g.LEVELS_UPDATED,{levels:t});let d=this.hls.levels[o];l&&d&&this.levels&&(d.attrs["STABLE-VARIANT-ID"]!==l.attrs["STABLE-VARIANT-ID"]&&d.bitrate!==l.bitrate&&this.log(`Unstable Pathways change from bitrate ${l.bitrate} to ${d.bitrate}`),this.hls.nextLoadLevel=o);break}}}getPathwayForGroupId(e,t,i){let r=this.getLevelsForPathway(i).concat(this.levels||[]);for(let n=0;n<r.length;n++)if(t===ce.AUDIO_TRACK&&r[n].hasAudioGroup(e)||t===ce.SUBTITLE_TRACK&&r[n].hasSubtitleGroup(e))return r[n].pathwayId;return i}clonePathways(e){let t=this.levels;if(!t)return;let i={},r={};e.forEach(n=>{let{ID:a,"BASE-ID":o,"URI-REPLACEMENT":l}=n;if(t.some(c=>c.pathwayId===a))return;let d=this.getLevelsForPathway(o).map(c=>{let u=new Re(c.attrs);u["PATHWAY-ID"]=a;let h=u.AUDIO&&`${u.AUDIO}_clone_${a}`,f=u.SUBTITLES&&`${u.SUBTITLES}_clone_${a}`;h&&(i[u.AUDIO]=h,u.AUDIO=h),f&&(r[u.SUBTITLES]=f,u.SUBTITLES=f);let m=Cp(c.uri,u["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",l),p=new ds({attrs:u,audioCodec:c.audioCodec,bitrate:c.bitrate,height:c.height,name:c.name,url:m,videoCodec:c.videoCodec,width:c.width});if(c.audioGroups)for(let E=1;E<c.audioGroups.length;E++)p.addGroupId("audio",`${c.audioGroups[E]}_clone_${a}`);if(c.subtitleGroups)for(let E=1;E<c.subtitleGroups.length;E++)p.addGroupId("text",`${c.subtitleGroups[E]}_clone_${a}`);return p});t.push(...d),dg(this.audioTracks,i,l,a),dg(this.subtitleTracks,r,l,a);});}loadSteeringManifest(e){let 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=false,this.log(`Failed to parse Steering Manifest URI: ${e}`);return}if(r.protocol!=="data:"){let c=(this.hls.bandwidthEstimate||t.abrEwmaDefaultEstimate)|0;r.searchParams.set("_HLS_pathway",this.pathwayId),r.searchParams.set("_HLS_throughput",""+c);}let 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},d={onSuccess:(c,u,h,f)=>{this.log(`Loaded steering manifest: "${r}"`);let m=c.data;if(m?.VERSION!==1){this.log(`Steering VERSION ${m.VERSION} not supported!`);return}this.updated=performance.now(),this.timeToLoad=m.TTL;let{"RELOAD-URI":p,"PATHWAY-CLONES":E,"PATHWAY-PRIORITY":v}=m;if(p)try{this.uri=new self.URL(p,r).href;}catch{this.enabled=false,this.log(`Failed to parse Steering Manifest RELOAD-URI: ${p}`);return}this.scheduleRefresh(this.uri||h.url),E&&this.clonePathways(E);let T={steeringManifest:m,url:r.toString()};this.hls.trigger(g.STEERING_MANIFEST_LOADED,T),v&&this.updatePathwayPriority(v);},onError:(c,u,h,f)=>{if(this.log(`Error loading steering manifest: ${c.code} ${c.text} (${u.url})`),this.stopLoad(),c.code===410){this.enabled=false,this.log(`Steering manifest ${u.url} no longer available`);return}let m=this.timeToLoad*1e3;if(c.code===429){let p=this.loader;if(typeof p?.getResponseHeader=="function"){let E=p.getResponseHeader("Retry-After");E&&(m=parseFloat(E)*1e3);}this.log(`Steering manifest ${u.url} rate limited`);return}this.scheduleRefresh(this.uri||u.url,m);},onTimeout:(c,u,h)=>{this.log(`Timeout loading steering manifest (${u.url})`),this.scheduleRefresh(this.uri||u.url);}};this.log(`Requesting steering manifest: ${r}`),this.loader.load(n,l,d);}scheduleRefresh(e,t=this.timeToLoad*1e3){this.clearTimeout(),this.reloadTimer=self.setTimeout(()=>{var i;let 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 dg(s,e,t,i){s&&Object.keys(e).forEach(r=>{let n=s.filter(a=>a.groupId===r).map(a=>{let o=ye({},a);return o.details=void 0,o.attrs=new Re(o.attrs),o.url=o.attrs.URI=Cp(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 Cp(s,e,t,i){let{HOST:r,PARAMS:n,[t]:a}=i,o;e&&(o=a?.[e],o&&(s=o));let l=new self.URL(s);return r&&!o&&(l.host=r),n&&Object.keys(n).sort().forEach(d=>{d&&l.searchParams.set(d,n[d]);}),l.href}var nl=class s extends ht{constructor(e){super("eme",e.logger),this.hls=void 0,this.config=void 0,this.media=null,this.keyFormatPromise=null,this.keySystemAccessPromises={},this._requestLicenseFailureCount=0,this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},this.mediaKeys=null,this.setMediaKeysQueue=s.CDMCleanupPromise?[s.CDMCleanupPromise]:[],this.bannedKeyIds={},this.onMediaEncrypted=t=>{let{initDataType:i,initData:r}=t,n=`"${t.type}" event: init data type: "${i}"`;if(this.debug(n),r!==null){if(!this.keyFormatPromise){let a=Object.keys(this.keySystemAccessPromises);a.length||(a=dn(this.config));let o=a.map(jd).filter(l=>!!l);this.keyFormatPromise=this.getKeyFormatPromise(o);}this.keyFormatPromise.then(a=>{let o=Oo(a);if(i!=="sinf"||o!==ke.FAIRPLAY){this.log(`Ignoring "${t.type}" event with init data type: "${i}" for selected key-system ${o}`);return}let l;try{let f=He(new Uint8Array(r)),m=Uu(JSON.parse(f).sinf),p=Cg(m);if(!p)throw new Error("'schm' box missing or not cbcs/cenc with schi > tenc");l=new Uint8Array(p.subarray(8,24));}catch(f){this.warn(`${n} Failed to parse sinf: ${f}`);return}let d=rt(l),{keyIdToKeySessionPromise:c,mediaKeySessions:u}=this,h=c[d];for(let f=0;f<u.length;f++){let m=u[f],p=m.decryptdata;if(!p.keyId)continue;let E=rt(p.keyId);if(Qo(l,p.keyId)||p.uri.replace(/-/g,"").indexOf(d)!==-1){if(h=c[E],!h)continue;if(p.pssh)break;delete c[E],p.pssh=new Uint8Array(r),p.keyId=l,h=c[d]=h.then(()=>this.generateRequestWithPreferredKeySession(m,i,r,"encrypted-event-key-match")),h.catch(v=>this.handleError(v));break}}h||this.handleError(new Error(`Key ID ${d} not encountered in playlist. Key-system sessions ${u.length}.`));}).catch(a=>this.handleError(a));}},this.onWaitingForKey=t=>{this.log(`"${t.type}" event`);},this.hls=e,this.config=e.config,this.registerListeners();}destroy(){this.onDestroying(),this.onMediaDetached();let e=this.config;e.requestMediaKeySystemAccessFunc=null,e.licenseXhrSetup=e.licenseResponseCallback=void 0,e.drmSystems=e.drmSystemOptions={},this.hls=this.config=this.keyIdToKeySessionPromise=null,this.onMediaEncrypted=this.onWaitingForKey=null;}registerListeners(){this.hls.on(g.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(g.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(g.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(g.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.on(g.DESTROYING,this.onDestroying,this);}unregisterListeners(){this.hls.off(g.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(g.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(g.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(g.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.off(g.DESTROYING,this.onDestroying,this);}getLicenseServerUrl(e){let{drmSystems:t,widevineLicenseUrl:i}=this.config,r=t?.[e];if(r)return r.licenseUrl;if(e===ke.WIDEVINE&&i)return i}getLicenseServerUrlOrThrow(e){let t=this.getLicenseServerUrl(e);if(t===void 0)throw new Error(`no license server URL configured for key-system "${e}"`);return t}getServerCertificateUrl(e){let{drmSystems:t}=this.config,i=t?.[e];if(i)return i.serverCertificateUrl;this.log(`No Server Certificate in config.drmSystems["${e}"]`);}attemptKeySystemAccess(e){let t=this.hls.levels,i=(a,o,l)=>!!a&&l.indexOf(a)===o,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)=>{let l=d=>{let c=d.shift();this.getMediaKeysPromise(c,r,n).then(u=>a({keySystem:c,mediaKeys:u})).catch(u=>{d.length?l(d):u instanceof st?o(u):o(new st({type:z.KEY_SYSTEM_ERROR,details:x.KEY_SYSTEM_NO_ACCESS,error:u,fatal:true},u.message));});};l(e);})}requestMediaKeySystemAccess(e,t){let{requestMediaKeySystemAccessFunc:i}=this.config;if(typeof i!="function"){let r=`Configured requestMediaKeySystemAccess is not a function ${i}`;return Yg===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){var r;let n=JT(e,t,i,this.config.drmSystemOptions||{}),a=this.keySystemAccessPromises[e],o=(r=a)==null?void 0:r.keySystemAccess;if(!o){this.log(`Requesting encrypted media "${e}" key-system access with config: ${Ae(n)}`),o=this.requestMediaKeySystemAccess(e,n);let l=a=this.keySystemAccessPromises[e]={keySystemAccess:o};return o.catch(d=>{this.log(`Failed to obtain access to key-system "${e}": ${d}`);}),o.then(d=>{this.log(`Access for key-system "${d.keySystem}" obtained`);let c=this.fetchServerCertificate(e);this.log(`Create media-keys for "${e}"`);let u=l.mediaKeys=d.createMediaKeys().then(h=>(this.log(`Media-keys created for "${e}"`),l.hasMediaKeys=true,c.then(f=>f?this.setMediaKeysServerCertificate(h,e,f):h)));return u.catch(h=>{this.error(`Failed to create media-keys for "${e}"}: ${h}`);}),u})}return o.then(()=>a.mediaKeys)}createMediaKeySessionContext({decryptdata:e,keySystem:t,mediaKeys:i}){this.log(`Creating key-system session "${t}" keyId: ${rt(e.keyId||[])} keyUri: ${e.uri}`);let r=i.createSession(),n={decryptdata:e,keySystem:t,mediaKeys:i,mediaKeysSession:r,keyStatus:"status-pending"};return this.mediaKeySessions.push(n),n}renewKeySession(e){let t=e.decryptdata;if(t.pssh){let i=this.createMediaKeySessionContext(e),r=xo(t),n="cenc";this.keyIdToKeySessionPromise[r]=this.generateRequestWithPreferredKeySession(i,n,t.pssh.buffer,"expired");}else this.warn("Could not renew expired session. Missing pssh initData.");this.removeSession(e);}updateKeySession(e,t){let i=e.mediaKeysSession;return this.log(`Updating key-session "${i.sessionId}" for keyId ${rt(e.decryptdata.keyId||[])}
1376
- } (data length: ${t.byteLength})`),i.update(t)}getSelectedKeySystemFormats(){return Object.keys(this.keySystemAccessPromises).map(e=>({keySystem:e,hasMediaKeys:this.keySystemAccessPromises[e].hasMediaKeys})).filter(({hasMediaKeys:e})=>!!e).map(({keySystem:e})=>jd(e)).filter(e=>!!e)}getKeySystemAccess(e){return this.getKeySystemSelectionPromise(e).then(({keySystem:t,mediaKeys:i})=>this.attemptSetMediaKeys(t,i))}selectKeySystem(e){return new Promise((t,i)=>{this.getKeySystemSelectionPromise(e).then(({keySystem:r})=>{let n=jd(r);n?t(n):i(new Error(`Unable to find format for key-system "${r}"`));}).catch(i);})}selectKeySystemFormat(e){let t=Object.keys(e.levelkeys||{});return this.keyFormatPromise||(this.log(`Selecting key-system from fragment (sn: ${e.sn} ${e.type}: ${e.level}) key formats ${t.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(t)),this.keyFormatPromise}getKeyFormatPromise(e){let t=dn(this.config),i=e.map(Oo).filter(r=>!!r&&t.indexOf(r)!==-1);return this.selectKeySystem(i)}getKeyStatus(e){let{mediaKeySessions:t}=this;for(let i=0;i<t.length;i++){let r=iA(e,t[i]);if(r)return r}}loadKey(e){let t=e.keyInfo.decryptdata,i=xo(t),r=this.bannedKeyIds[i];if(r||this.getKeyStatus(t)==="internal-error"){let o=cg(r||"internal-error",t);return this.handleError(o,e.frag),Promise.reject(o)}let n=`(keyId: ${i} format: "${t.keyFormat}" method: ${t.method} uri: ${t.uri})`;this.log(`Starting session for key ${n}`);let a=this.keyIdToKeySessionPromise[i];if(!a){let o=this.getKeySystemForKeyPromise(t).then(({keySystem:l,mediaKeys:d})=>(this.throwIfDestroyed(),this.log(`Handle encrypted media sn: ${e.frag.sn} ${e.frag.type}: ${e.frag.level} using key ${n}`),this.attemptSetMediaKeys(l,d).then(()=>(this.throwIfDestroyed(),this.createMediaKeySessionContext({keySystem:l,mediaKeys:d,decryptdata:t}))))).then(l=>{let d="cenc",c=t.pssh?t.pssh.buffer:null;return this.generateRequestWithPreferredKeySession(l,d,c,"playlist-key")});return o.catch(l=>this.handleError(l,e.frag)),this.keyIdToKeySessionPromise[i]=o,o}return a.catch(o=>{if(o instanceof st){let l=ve({},o.data);this.getKeyStatus(t)==="internal-error"&&(l.decryptdata=t);let d=new st(l,o.message);this.handleError(d,e.frag);}}),a}throwIfDestroyed(e="Invalid state"){if(!this.hls)throw new Error("invalid state")}handleError(e,t){if(this.hls)if(e instanceof st){t&&(e.data.frag=t);let i=e.data.decryptdata;this.error(`${e.message}${i?` (${rt(i.keyId||[])})`:""}`),this.hls.trigger(g.ERROR,e.data);}else this.error(e.message),this.hls.trigger(g.ERROR,{type:z.KEY_SYSTEM_ERROR,details:x.KEY_SYSTEM_NO_KEYS,error:e,fatal:true});}getKeySystemForKeyPromise(e){let t=xo(e),i=this.keyIdToKeySessionPromise[t];if(!i){let r=Oo(e.keyFormat),n=r?[r]:dn(this.config);return this.attemptKeySystemAccess(n)}return i}getKeySystemSelectionPromise(e){if(e.length||(e=dn(this.config)),e.length===0)throw new st({type:z.KEY_SYSTEM_ERROR,details:x.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:true},`Missing key-system license configuration options ${Ae({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(e)}attemptSetMediaKeys(e,t){if(this.mediaKeys===t)return Promise.resolve();let i=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${e}"`);let r=Promise.all(i).then(()=>{if(!this.media)throw this.mediaKeys=null,new Error("Attempted to set mediaKeys without media element attached");return this.media.setMediaKeys(t)});return this.mediaKeys=t,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;let a=(n=this.config.drmSystems)==null||(n=n[e.keySystem])==null?void 0:n.generateRequest;if(a)try{let m=a.call(this.hls,t,i,e);if(!m)throw new Error("Invalid response from configured generateRequest filter");t=m.initDataType,i=m.initData?m.initData:null,e.decryptdata.pssh=i?new Uint8Array(i):null;}catch(m){if(this.warn(m.message),this.hls&&this.hls.config.debug)throw m}if(i===null)return this.log(`Skipping key-session request for "${r}" (no initData)`),Promise.resolve(e);let o=xo(e.decryptdata),l=e.decryptdata.uri;this.log(`Generating key-session request for "${r}" keyId: ${o} URI: ${l} (init data type: ${t} length: ${i.byteLength})`);let d=new Bu,c=e._onmessage=m=>{let p=e.mediaKeysSession;if(!p){d.emit("error",new Error("invalid state"));return}let{messageType:E,message:v}=m;this.log(`"${E}" message event for session "${p.sessionId}" message size: ${v.byteLength}`),E==="license-request"||E==="license-renewal"?this.renewLicense(e,v).catch(T=>{d.eventNames().length?d.emit("error",T):this.handleError(T);}):E==="license-release"?e.keySystem===ke.FAIRPLAY&&this.updateKeySession(e,kc("acknowledged")).then(()=>this.removeSession(e)).catch(T=>this.handleError(T)):this.warn(`unhandled media key message type "${E}"`);},u=(m,p)=>{p.keyStatus=m;let E;m.startsWith("usable")?d.emit("resolved"):m==="internal-error"||m==="output-restricted"||m==="output-downscaled"?E=cg(m,p.decryptdata):m==="expired"?E=new Error(`key expired (keyId: ${o})`):m==="released"?E=new Error("key released"):m==="status-pending"||this.warn(`unhandled key status change "${m}" (keyId: ${o})`),E&&(d.eventNames().length?d.emit("error",E):this.handleError(E));},h=e._onkeystatuseschange=m=>{if(!e.mediaKeysSession){d.emit("error",new Error("invalid state"));return}let E=this.getKeyStatuses(e);if(!Object.keys(E).some(A=>E[A]!=="status-pending"))return;if(E[o]==="expired"){this.log(`Expired key ${Ae(E)} in key-session "${e.mediaKeysSession.sessionId}"`),this.renewKeySession(e);return}let T=E[o];if(T)u(T,e);else {var S;e.keyStatusTimeouts||(e.keyStatusTimeouts={}),(S=e.keyStatusTimeouts)[o]||(S[o]=self.setTimeout(()=>{if(!e.mediaKeysSession||!this.mediaKeys)return;let b=this.getKeyStatus(e.decryptdata);if(b&&b!=="status-pending")return this.log(`No status for keyId ${o} in key-session "${e.mediaKeysSession.sessionId}". Using session key-status ${b} from other session.`),u(b,e);this.log(`key status for ${o} in key-session "${e.mediaKeysSession.sessionId}" timed out after 1000ms`),T="internal-error",u(T,e);},1e3)),this.log(`No status for keyId ${o} (${Ae(E)}).`);}};nt(e.mediaKeysSession,"message",c),nt(e.mediaKeysSession,"keystatuseschange",h);let f=new Promise((m,p)=>{d.on("error",p),d.on("resolved",m);});return e.mediaKeysSession.generateRequest(t,i).then(()=>{this.log(`Request generated for key-session "${e.mediaKeysSession.sessionId}" keyId: ${o} URI: ${l}`);}).catch(m=>{throw new st({type:z.KEY_SYSTEM_ERROR,details:x.KEY_SYSTEM_NO_SESSION,error:m,decryptdata:e.decryptdata,fatal:false},`Error generating key-session request: ${m}`)}).then(()=>f).catch(m=>(d.removeAllListeners(),this.removeSession(e).then(()=>{throw m}))).then(()=>(d.removeAllListeners(),e))}getKeyStatuses(e){let t={};return e.mediaKeysSession.keyStatuses.forEach((i,r)=>{if(typeof r=="string"&&typeof i=="object"){let o=r;r=i,i=o;}let n="buffer"in r?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):new Uint8Array(r);e.keySystem===ke.PLAYREADY&&n.length===16&&Vg(n);let a=rt(n);i==="internal-error"&&(this.bannedKeyIds[a]=i),this.log(`key status change "${i}" for keyStatuses keyId: ${a} key-session "${e.mediaKeysSession.sessionId}"`),t[a]=i;}),t}fetchServerCertificate(e){let 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)=>{let l={responseType:"arraybuffer",url:n},d=t.certLoadPolicy.default,c={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},u={onSuccess:(h,f,m,p)=>{a(h.data);},onError:(h,f,m,p)=>{o(new st({type:z.KEY_SYSTEM_ERROR,details:x.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:true,networkDetails:m,response:ve({url:l.url,data:void 0},h)},`"${e}" certificate request failed (${n}). Status: ${h.code} (${h.text})`));},onTimeout:(h,f,m)=>{o(new st({type:z.KEY_SYSTEM_ERROR,details:x.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:true,networkDetails:m,response:{url:l.url,data:void 0}},`"${e}" certificate request timed out (${n})`));},onAbort:(h,f,m)=>{o(new Error("aborted"));}};r.load(l,c,u);})):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.byteLength}) on "${t}"`),r(e);}).catch(a=>{n(new st({type:z.KEY_SYSTEM_ERROR,details:x.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:a,fatal:true},a.message));});})}renewLicense(e,t){return this.requestLicense(e,new Uint8Array(t)).then(i=>this.updateKeySession(e,new Uint8Array(i)).catch(r=>{throw new st({type:z.KEY_SYSTEM_ERROR,details:x.KEY_SYSTEM_SESSION_UPDATE_FAILED,decryptdata:e.decryptdata,error:r,fatal:false},r.message)}))}unpackPlayReadyKeyMessage(e,t){let i=String.fromCharCode.apply(null,new Uint16Array(t.buffer));if(!i.includes("PlayReadyKeyMessage"))return e.setRequestHeader("Content-Type","text/xml; charset=utf-8"),t;let r=new DOMParser().parseFromString(i,"application/xml"),n=r.querySelectorAll("HttpHeader");if(n.length>0){let c;for(let u=0,h=n.length;u<h;u++){var a,o;c=n[u];let f=(a=c.querySelector("name"))==null?void 0:a.textContent,m=(o=c.querySelector("value"))==null?void 0:o.textContent;f&&m&&e.setRequestHeader(f,m);}}let l=r.querySelector("Challenge"),d=l?.textContent;if(!d)throw new Error("Cannot find <Challenge> in key message");return kc(atob(d))}setupLicenseXHR(e,t,i,r){let n=this.config.licenseXhrSetup;return n?Promise.resolve().then(()=>{if(!i.decryptdata)throw new Error("Key removed");return n.call(this.hls,e,t,i,r)}).catch(a=>{if(!i.decryptdata)throw a;return e.open("POST",t,true),n.call(this.hls,e,t,i,r)}).then(a=>(e.readyState||e.open("POST",t,true),{xhr:e,licenseChallenge:a||r})):(e.open("POST",t,true),Promise.resolve({xhr:e,licenseChallenge:r}))}requestLicense(e,t){let i=this.config.keyLoadPolicy.default;return new Promise((r,n)=>{let a=this.getLicenseServerUrlOrThrow(e.keySystem);this.log(`Sending license request to URL: ${a}`);let o=new XMLHttpRequest;o.responseType="arraybuffer",o.onreadystatechange=()=>{if(!this.hls||!e.mediaKeysSession)return n(new Error("invalid state"));if(o.readyState===4)if(o.status===200){this._requestLicenseFailureCount=0;let l=o.response;this.log(`License received ${l instanceof ArrayBuffer?l.byteLength:l}`);let d=this.config.licenseResponseCallback;if(d)try{l=d.call(this.hls,o,a,e);}catch(c){this.error(c);}r(l);}else {let l=i.errorRetry,d=l?l.maxNumRetry:0;if(this._requestLicenseFailureCount++,this._requestLicenseFailureCount>d||o.status>=400&&o.status<500)n(new st({type:z.KEY_SYSTEM_ERROR,details:x.KEY_SYSTEM_LICENSE_REQUEST_FAILED,decryptdata:e.decryptdata,fatal:true,networkDetails:o,response:{url:a,data:void 0,code:o.status,text:o.statusText}},`License Request XHR failed (${a}). Status: ${o.status} (${o.statusText})`));else {let c=d-this._requestLicenseFailureCount+1;this.warn(`Retrying license request, ${c} 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:d})=>{e.keySystem==ke.PLAYREADY&&(d=this.unpackPlayReadyKeyMessage(l,d)),l.send(d);}).catch(n);})}onDestroying(){this.unregisterListeners(),this._clear();}onMediaAttached(e,t){if(!this.config.emeEnabled)return;let i=t.media;this.media=i,nt(i,"encrypted",this.onMediaEncrypted),nt(i,"waitingforkey",this.onWaitingForKey);}onMediaDetached(){let e=this.media;e&&(ut(e,"encrypted",this.onMediaEncrypted),ut(e,"waitingforkey",this.onWaitingForKey),this.media=null,this.mediaKeys=null);}_clear(){var e;if(this._requestLicenseFailureCount=0,this.keyIdToKeySessionPromise={},this.bannedKeyIds={},!this.mediaKeys&&!this.mediaKeySessions.length)return;let t=this.media,i=this.mediaKeySessions.slice();this.mediaKeySessions=[],this.mediaKeys=null,Tn.clearKeyUriToKeyIdMap();let r=i.length;s.CDMCleanupPromise=Promise.all(i.map(n=>this.removeSession(n)).concat((t==null||(e=t.setMediaKeys(null))==null?void 0:e.catch(n=>{this.log(`Could not clear media keys: ${n}`),this.hls&&this.hls.trigger(g.ERROR,{type:z.OTHER_ERROR,details:x.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR,fatal:false,error:new Error(`Could not clear media keys: ${n}`)});}))||Promise.resolve())).catch(n=>{this.log(`Could not close sessions and clear media keys: ${n}`),this.hls&&this.hls.trigger(g.ERROR,{type:z.OTHER_ERROR,details:x.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:false,error:new Error(`Could not close sessions and clear media keys: ${n}`)});}).then(()=>{r&&this.log("finished closing key sessions and clearing media keys");});}onManifestLoading(){this.keyFormatPromise=null,this.bannedKeyIds={};}onManifestLoaded(e,{sessionKeys:t}){if(!(!t||!this.config.emeEnabled)&&!this.keyFormatPromise){let 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){let{mediaKeysSession:t,licenseXhr:i,decryptdata:r}=e;if(t){this.log(`Remove licenses and keys and close session "${t.sessionId}" keyId: ${rt(r?.keyId||[])}`),e._onmessage&&(t.removeEventListener("message",e._onmessage),e._onmessage=void 0),e._onkeystatuseschange&&(t.removeEventListener("keystatuseschange",e._onkeystatuseschange),e._onkeystatuseschange=void 0),i&&i.readyState!==XMLHttpRequest.DONE&&i.abort(),e.mediaKeysSession=e.decryptdata=e.licenseXhr=void 0;let n=this.mediaKeySessions.indexOf(e);n>-1&&this.mediaKeySessions.splice(n,1);let{keyStatusTimeouts:a}=e;a&&Object.keys(a).forEach(d=>self.clearTimeout(a[d]));let{drmSystemOptions:o}=this.config;return (ty(o)?new Promise((d,c)=>{self.setTimeout(()=>c(new Error("MediaKeySession.remove() timeout")),8e3),t.remove().then(d).catch(c);}):Promise.resolve()).catch(d=>{this.log(`Could not remove session: ${d}`),this.hls&&this.hls.trigger(g.ERROR,{type:z.OTHER_ERROR,details:x.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR,fatal:false,error:new Error(`Could not remove session: ${d}`)});}).then(()=>t.close()).catch(d=>{this.log(`Could not close session: ${d}`),this.hls&&this.hls.trigger(g.ERROR,{type:z.OTHER_ERROR,details:x.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:false,error:new Error(`Could not close session: ${d}`)});})}return Promise.resolve()}};nl.CDMCleanupPromise=void 0;function xo(s){if(!s)throw new Error("Could not read keyId of undefined decryptdata");if(s.keyId===null)throw new Error("keyId is null");return rt(s.keyId)}function iA(s,e){if(s.keyId&&e.mediaKeysSession.keyStatuses.has(s.keyId))return e.mediaKeysSession.keyStatuses.get(s.keyId);if(s.matches(e.decryptdata))return e.keyStatus}var st=class extends Error{constructor(e,t){super(t),this.data=void 0,e.error||(e.error=new Error(t)),this.data=e,e.err=e.error;}};function cg(s,e){let t=s==="output-restricted",i=t?x.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:x.KEY_SYSTEM_STATUS_INTERNAL_ERROR;return new st({type:z.KEY_SYSTEM_ERROR,details:i,fatal:false,decryptdata:e},t?"HDCP level output restricted":`key status changed to "${s}"`)}var ru=class{constructor(e){this.hls=void 0,this.isVideoPlaybackQualityAvailable=false,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(g.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.on(g.MEDIA_DETACHING,this.onMediaDetaching,this);}unregisterListeners(){this.hls.off(g.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.off(g.MEDIA_DETACHING,this.onMediaDetaching,this);}destroy(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=false,this.media=null;}onMediaAttaching(e,t){let i=this.hls.config;if(i.capLevelOnFPSDrop){let r=t.media instanceof self.HTMLVideoElement?t.media:null;this.media=r,r&&typeof r.getVideoPlaybackQuality=="function"&&(this.isVideoPlaybackQualityAvailable=true),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),i.fpsDroppedMonitoringPeriod);}}onMediaDetaching(){this.media=null;}checkFPS(e,t,i){let r=performance.now();if(t){if(this.lastTime){let n=r-this.lastTime,a=i-this.lastDroppedFrames,o=t-this.lastDecodedFrames,l=1e3*a/n,d=this.hls;if(d.trigger(g.FPS_DROP,{currentDropped:a,currentDecoded:o,totalDroppedFrames:i}),l>0&&a>d.config.fpsDroppedMonitoringThreshold*o){let c=d.currentLevel;d.logger.warn("drop FPS ratio greater than max allowed value for currentLevel: "+c),c>0&&(d.autoLevelCapping===-1||d.autoLevelCapping>=c)&&(c=c-1,d.trigger(g.FPS_DROP_LEVEL_CAPPING,{level:c,droppedLevel:d.currentLevel}),d.autoLevelCapping=c,this.streamController.nextLevelSwitch());}}this.lastTime=r,this.lastDroppedFrames=i,this.lastDecodedFrames=t;}}checkFPSInterval(){let e=this.media;if(e)if(this.isVideoPlaybackQualityAvailable){let t=e.getVideoPlaybackQuality();this.checkFPS(e,t.totalVideoFrames,t.droppedVideoFrames);}else this.checkFPS(e,e.webkitDecodedFrameCount,e.webkitDroppedFrameCount);}};function Mp(s,e){let t;try{t=new Event("addtrack");}catch{t=document.createEvent("Event"),t.initEvent("addtrack",false,false);}t.track=s,e.dispatchEvent(t);}function Pp(s,e){let t=s.mode;if(t==="disabled"&&(s.mode="hidden"),s.cues&&!s.cues.getCueById(e.id))try{if(s.addCue(e),!s.cues.getCueById(e.id))throw new Error(`addCue is failed for: ${e}`)}catch(i){Te.debug(`[texttrack-utils]: ${i}`);try{let r=new self.TextTrackCue(e.startTime,e.endTime,e.text);r.id=e.id,s.addCue(r);}catch(r){Te.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${r}`);}}t==="disabled"&&(s.mode=t);}function er(s,e){let t=s.mode;if(t==="disabled"&&(s.mode="hidden"),s.cues)for(let i=s.cues.length;i--;)e&&s.cues[i].removeEventListener("enter",e),s.removeCue(s.cues[i]);t==="disabled"&&(s.mode=t);}function nu(s,e,t,i){let r=s.mode;if(r==="disabled"&&(s.mode="hidden"),s.cues&&s.cues.length>0){let n=rA(s.cues,e,t);for(let a=0;a<n.length;a++)(!i||i(n[a]))&&s.removeCue(n[a]);}r==="disabled"&&(s.mode=r);}function sA(s,e){if(e<=s[0].startTime)return 0;let t=s.length-1;if(e>s[t].endTime)return -1;let i=0,r=t,n;for(;i<=r;)if(n=Math.floor((r+i)/2),e<s[n].startTime)r=n-1;else if(e>s[n].startTime&&i<t)i=n+1;else return n;return s[i].startTime-e<e-s[r].startTime?i:r}function rA(s,e,t){let i=[],r=sA(s,e);if(r>-1)for(let n=r,a=s.length;n<a;n++){let o=s[n];if(o.startTime>=e&&o.endTime<=t)i.push(o);else if(o.startTime>t)return i}return i}function Uo(s){let e=[];for(let t=0;t<s.length;t++){let i=s[t];(i.kind==="subtitles"||i.kind==="captions")&&i.label&&e.push(s[t]);}return e}var au=class extends In{constructor(e){super(e,"subtitle-track-controller"),this.media=null,this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=true,this.queuedDefaultTrack=-1,this.useTextTrackPolling=false,this.subtitlePollingInterval=-1,this._subtitleDisplay=true,this.asyncPollTrackChange=()=>this.pollTrackChange(0),this.onTextTracksChanged=()=>{if(this.useTextTrackPolling||self.clearInterval(this.subtitlePollingInterval),!this.media||!this.hls.config.renderTextTracksNatively)return;let t=null,i=Uo(this.media.textTracks);for(let n=0;n<i.length;n++)if(i[n].mode==="hidden")t=i[n];else if(i[n].mode==="showing"){t=i[n];break}let r=this.findTrackForTextTrack(t);this.subtitleTrack!==r&&this.setSubtitleTrack(r);},this.registerListeners();}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,this.onTextTracksChanged=this.asyncPollTrackChange=null,super.destroy();}get subtitleDisplay(){return this._subtitleDisplay}set subtitleDisplay(e){this._subtitleDisplay=e,this.trackId>-1&&this.toggleTrackModes();}registerListeners(){let{hls:e}=this;e.on(g.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(g.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(g.MANIFEST_LOADING,this.onManifestLoading,this),e.on(g.MANIFEST_PARSED,this.onManifestParsed,this),e.on(g.LEVEL_LOADING,this.onLevelLoading,this),e.on(g.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(g.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(g.ERROR,this.onError,this);}unregisterListeners(){let{hls:e}=this;e.off(g.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(g.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(g.MANIFEST_LOADING,this.onManifestLoading,this),e.off(g.MANIFEST_PARSED,this.onManifestParsed,this),e.off(g.LEVEL_LOADING,this.onLevelLoading,this),e.off(g.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(g.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(g.ERROR,this.onError,this);}onMediaAttached(e,t){this.media=t.media,this.media&&(this.queuedDefaultTrack>-1&&(this.subtitleTrack=this.queuedDefaultTrack,this.queuedDefaultTrack=-1),this.useTextTrackPolling=!(this.media.textTracks&&"onchange"in this.media.textTracks),this.useTextTrackPolling?this.pollTrackChange(500):this.media.textTracks.addEventListener("change",this.asyncPollTrackChange));}pollTrackChange(e){self.clearInterval(this.subtitlePollingInterval),this.subtitlePollingInterval=self.setInterval(this.onTextTracksChanged,e);}onMediaDetaching(e,t){let i=this.media;if(!i)return;let r=!!t.transferMedia;if(self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||i.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId),this.subtitleTrack=-1,this.media=null,r)return;Uo(i.textTracks).forEach(a=>{er(a);});}onManifestLoading(){this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=true;}onManifestParsed(e,t){this.tracks=t.subtitleTracks;}onSubtitleTrackLoaded(e,t){let{id:i,groupId:r,details:n}=t,a=this.tracksInGroup[i];if(!a||a.groupId!==r){this.warn(`Subtitle track with id:${i} and group:${r} not found in active group ${a?.groupId}`);return}let o=a.details;a.details=t.details,this.log(`Subtitle track ${i} "${a.name}" lang:${a.lang} group:${r} loaded [${n.startSN}-${n.endSN}]`),i===this.trackId&&this.playlistLoaded(i,t,o);}onLevelLoading(e,t){this.switchLevel(t.level);}onLevelSwitching(e,t){this.switchLevel(t.level);}switchLevel(e){let t=this.hls.levels[e];if(!t)return;let i=t.subtitleGroups||null,r=this.groupIds,n=this.currentTrack;if(!i||r?.length!==i?.length||i!=null&&i.some(a=>r?.indexOf(a)===-1)){this.groupIds=i,this.trackId=-1,this.currentTrack=null;let a=this.tracks.filter(c=>!i||i.indexOf(c.groupId)!==-1);if(a.length)this.selectDefaultTrack&&!a.some(c=>c.default)&&(this.selectDefaultTrack=false),a.forEach((c,u)=>{c.id=u;});else if(!n&&!this.tracksInGroup.length)return;this.tracksInGroup=a;let o=this.hls.config.subtitlePreference;if(!n&&o){this.selectDefaultTrack=false;let c=di(o,a);if(c>-1)n=a[c];else {let u=di(o,this.tracks);n=this.tracks[u];}}let l=this.findTrackId(n);l===-1&&n&&(l=this.findTrackId(null));let d={subtitleTracks:a};this.log(`Updating subtitle tracks, ${a.length} track(s) found in "${i?.join(",")}" group-id`),this.hls.trigger(g.SUBTITLE_TRACKS_UPDATED,d),l!==-1&&this.trackId===-1&&this.setSubtitleTrack(l);}}findTrackId(e){let t=this.tracksInGroup,i=this.selectDefaultTrack;for(let r=0;r<t.length;r++){let n=t[r];if(!(i&&!n.default||!i&&!e)&&(!e||os(n,e)))return r}if(e){for(let r=0;r<t.length;r++){let n=t[r];if(Ln(e.attrs,n.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return r}for(let r=0;r<t.length;r++){let n=t[r];if(Ln(e.attrs,n.attrs,["LANGUAGE"]))return r}}return -1}findTrackForTextTrack(e){if(e){let t=this.tracksInGroup;for(let i=0;i<t.length;i++){let r=t[i];if(qc(r,e))return i}}return -1}onError(e,t){t.fatal||!t.context||t.context.type===ce.SUBTITLE_TRACK&&t.context.id===this.trackId&&(!this.groupIds||this.groupIds.indexOf(t.context.groupId)!==-1)&&this.checkRetry(t);}get allSubtitleTracks(){return this.tracks}get subtitleTracks(){return this.tracksInGroup}get subtitleTrack(){return this.trackId}set subtitleTrack(e){this.selectDefaultTrack=false,this.setSubtitleTrack(e);}setSubtitleOption(e){if(this.hls.config.subtitlePreference=e,e){if(e.id===-1)return this.setSubtitleTrack(-1),null;let t=this.allSubtitleTracks;if(this.selectDefaultTrack=false,t.length){let i=this.currentTrack;if(i&&os(e,i))return i;let r=di(e,this.tracksInGroup);if(r>-1){let n=this.tracksInGroup[r];return this.setSubtitleTrack(r),n}else {if(i)return null;{let n=di(e,t);if(n>-1)return t[n]}}}}return null}loadPlaylist(e){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentTrack)&&this.scheduleLoading(this.currentTrack,e);}loadingPlaylist(e,t){super.loadingPlaylist(e,t);let i=e.id,r=e.groupId,n=this.getUrlWithDirectives(e.url,t),a=e.details,o=a?.age;this.log(`Loading subtitle ${i} "${e.name}" lang:${e.lang} group:${r}${t?.msn!==void 0?" at sn "+t.msn+" part "+t.part:""}${o&&a.live?" age "+o.toFixed(1)+(a.type&&" "+a.type||""):""} ${n}`),this.hls.trigger(g.SUBTITLE_TRACK_LOADING,{url:n,id:i,groupId:r,deliveryDirectives:t||null,track:e});}toggleTrackModes(){let{media:e}=this;if(!e)return;let t=Uo(e.textTracks),i=this.currentTrack,r;if(i&&(r=t.filter(n=>qc(i,n))[0],r||this.warn(`Unable to find subtitle TextTrack with name "${i.name}" and language "${i.lang}"`)),[].slice.call(t).forEach(n=>{n.mode!=="disabled"&&n!==r&&(n.mode="disabled");}),r){let n=this.subtitleDisplay?"showing":"hidden";r.mode!==n&&(r.mode=n);}}setSubtitleTrack(e){let t=this.tracksInGroup;if(!this.media){this.queuedDefaultTrack=e;return}if(e<-1||e>=t.length||!G(e)){this.warn(`Invalid subtitle track id: ${e}`);return}this.selectDefaultTrack=false;let i=this.currentTrack,r=t[e]||null;if(this.trackId=e,this.currentTrack=r,this.toggleTrackModes(),!r){this.hls.trigger(g.SUBTITLE_TRACK_SWITCH,{id:e});return}let n=!!r.details&&!r.details.live;if(e===this.trackId&&r===i&&n)return;this.log(`Switching to subtitle-track ${e}`+(r?` "${r.name}" lang:${r.lang} group:${r.groupId}`:""));let{id:a,groupId:o="",name:l,type:d,url:c}=r;this.hls.trigger(g.SUBTITLE_TRACK_SWITCH,{id:a,groupId:o,name:l,type:d,url:c});let u=this.switchParams(r.url,i?.details,r.details);this.loadPlaylist(u);}};function nA(){try{return crypto.randomUUID()}catch{try{let e=URL.createObjectURL(new Blob),t=e.toString();return URL.revokeObjectURL(e),t.slice(t.lastIndexOf("/")+1)}catch{let t=new Date().getTime();return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,r=>{let n=(t+Math.random()*16)%16|0;return t=Math.floor(t/16),(r=="x"?n:n&3|8).toString(16)})}}}function hn(s){let e=5381,t=s.length;for(;t;)e=e*33^s.charCodeAt(--t);return (e>>>0).toString()}var nr=.025,al=function(s){return s[s.Point=0]="Point",s[s.Range=1]="Range",s}({});function aA(s,e,t){return `${s.identifier}-${t+1}-${hn(e)}`}var ou=class{constructor(e,t){this.base=void 0,this._duration=null,this._timelineStart=null,this.appendInPlaceDisabled=void 0,this.appendInPlaceStarted=void 0,this.dateRange=void 0,this.hasPlayed=false,this.cumulativeDuration=0,this.resumeOffset=NaN,this.playoutLimit=NaN,this.restrictions={skip:false,jump:false},this.snapOptions={out:false,in:false},this.assetList=[],this.assetListLoader=void 0,this.assetListResponse=null,this.resumeAnchor=void 0,this.error=void 0,this.resetOnResume=void 0,this.base=t,this.dateRange=e,this.setDateRange(e);}setDateRange(e){this.dateRange=e,this.resumeOffset=e.attr.optionalFloat("X-RESUME-OFFSET",this.resumeOffset),this.playoutLimit=e.attr.optionalFloat("X-PLAYOUT-LIMIT",this.playoutLimit),this.restrictions=e.attr.enumeratedStringList("X-RESTRICT",this.restrictions),this.snapOptions=e.attr.enumeratedStringList("X-SNAP",this.snapOptions);}reset(){var e;this.appendInPlaceStarted=false,(e=this.assetListLoader)==null||e.destroy(),this.assetListLoader=void 0,this.supplementsPrimary||(this.assetListResponse=null,this.assetList=[],this._duration=null);}isAssetPastPlayoutLimit(e){var t;if(e>0&&e>=this.assetList.length)return true;let i=this.playoutLimit;return e<=0||isNaN(i)?false:i===0?true:(((t=this.assetList[e])==null?void 0:t.startOffset)||0)>i}findAssetIndex(e){return this.assetList.indexOf(e)}get identifier(){return this.dateRange.id}get startDate(){return this.dateRange.startDate}get startTime(){let e=this.dateRange.startTime;if(this.snapOptions.out){let t=this.dateRange.tagAnchor;if(t)return sc(e,t)}return e}get startOffset(){return this.cue.pre?0:this.startTime}get startIsAligned(){if(this.startTime===0||this.snapOptions.out)return true;let e=this.dateRange.tagAnchor;if(e){let t=this.dateRange.startTime,i=sc(t,e);return t-i<.1}return false}get resumptionOffset(){let e=this.resumeOffset,t=G(e)?e:this.duration;return this.cumulativeDuration+t}get resumeTime(){let e=this.startOffset+this.resumptionOffset;if(this.snapOptions.in){let t=this.resumeAnchor;if(t)return sc(e,t)}return e}get appendInPlace(){return this.appendInPlaceStarted?true:this.appendInPlaceDisabled?false:!!(!this.cue.once&&!this.cue.pre&&this.startIsAligned&&(isNaN(this.playoutLimit)&&isNaN(this.resumeOffset)||this.resumeOffset&&this.duration&&Math.abs(this.resumeOffset-this.duration)<nr))}set appendInPlace(e){if(this.appendInPlaceStarted){this.resetOnResume=!e;return}this.appendInPlaceDisabled=!e;}get timelineStart(){return this._timelineStart!==null?this._timelineStart:this.startTime}set timelineStart(e){this._timelineStart=e;}get duration(){let e=this.playoutLimit,t;return this._duration!==null?t=this._duration:this.dateRange.duration?t=this.dateRange.duration:t=this.dateRange.plannedDuration||0,!isNaN(e)&&e<t&&(t=e),t}set duration(e){this._duration=e;}get cue(){return this.dateRange.cue}get timelineOccupancy(){return this.dateRange.attr["X-TIMELINE-OCCUPIES"]==="RANGE"?al.Range:al.Point}get supplementsPrimary(){return this.dateRange.attr["X-TIMELINE-STYLE"]==="PRIMARY"}get contentMayVary(){return this.dateRange.attr["X-CONTENT-MAY-VARY"]!=="NO"}get assetUrl(){return this.dateRange.attr["X-ASSET-URI"]}get assetListUrl(){return this.dateRange.attr["X-ASSET-LIST"]}get baseUrl(){return this.base.url}get assetListLoaded(){return this.assetList.length>0||this.assetListResponse!==null}toString(){return oA(this)}};function sc(s,e){return s-e.start<e.duration/2&&!(Math.abs(s-(e.start+e.duration))<nr)?e.start:e.start+e.duration}function wp(s,e,t){let i=new self.URL(s,t);return i.protocol!=="data:"&&i.searchParams.set("_HLS_primary_id",e),i}function rc(s,e){for(;(t=s.assetList[++e])!=null&&t.error;)var t;return e}function oA(s){return `["${s.identifier}" ${s.cue.pre?"<pre>":s.cue.post?"<post>":""}${s.timelineStart.toFixed(2)}-${s.resumeTime.toFixed(2)}]`}function Js(s){let e=s.timelineStart,t=s.duration||0;return `["${s.identifier}" ${e.toFixed(2)}-${(e+t).toFixed(2)}]`}var lu=class{constructor(e,t,i,r){this.hls=void 0,this.interstitial=void 0,this.assetItem=void 0,this.tracks=null,this.hasDetails=false,this.mediaAttached=null,this._currentTime=void 0,this._bufferedEosTime=void 0,this.checkPlayout=()=>{this.reachedPlayout(this.currentTime)&&this.hls&&this.hls.trigger(g.PLAYOUT_LIMIT_REACHED,{});};let n=this.hls=new e(t);this.interstitial=i,this.assetItem=r;let a=()=>{this.hasDetails=true;};n.once(g.LEVEL_LOADED,a),n.once(g.AUDIO_TRACK_LOADED,a),n.once(g.SUBTITLE_TRACK_LOADED,a),n.on(g.MEDIA_ATTACHING,(o,{media:l})=>{this.removeMediaListeners(),this.mediaAttached=l,this.interstitial.playoutLimit&&(l.addEventListener("timeupdate",this.checkPlayout),this.appendInPlace&&n.on(g.BUFFER_APPENDED,()=>{let c=this.bufferedEnd;this.reachedPlayout(c)&&(this._bufferedEosTime=c,n.trigger(g.BUFFERED_TO_END,void 0));}));});}get appendInPlace(){return this.interstitial.appendInPlace}loadSource(){let e=this.hls;if(e)if(e.url)e.levels.length&&!e.started&&e.startLoad(-1,true);else {let t=this.assetItem.uri;try{t=wp(t,e.config.primarySessionId||"").href;}catch{}e.loadSource(t);}}bufferedInPlaceToEnd(e){var t;if(!this.appendInPlace)return false;if((t=this.hls)!=null&&t.bufferedToEnd)return true;if(!e)return false;let i=Math.min(this._bufferedEosTime||1/0,this.duration),r=this.timelineOffset,n=re.bufferInfo(e,r,0);return this.getAssetTime(n.end)>=i-.02}reachedPlayout(e){let i=this.interstitial.playoutLimit;return this.startOffset+e>=i}get destroyed(){var e;return !((e=this.hls)!=null&&e.userConfig)}get assetId(){return this.assetItem.identifier}get interstitialId(){return this.assetItem.parentIdentifier}get media(){var e;return ((e=this.hls)==null?void 0:e.media)||null}get bufferedEnd(){let e=this.media||this.mediaAttached;if(!e)return this._bufferedEosTime?this._bufferedEosTime:this.currentTime;let t=re.bufferInfo(e,e.currentTime,.001);return this.getAssetTime(t.end)}get currentTime(){let e=this.media||this.mediaAttached;return e?this.getAssetTime(e.currentTime):this._currentTime||0}get duration(){let e=this.assetItem.duration;if(!e)return 0;let t=this.interstitial.playoutLimit;if(t){let i=t-this.startOffset;if(i>0&&i<e)return i}return e}get remaining(){let e=this.duration;return e?Math.max(0,e-this.currentTime):0}get startOffset(){return this.assetItem.startOffset}get timelineOffset(){var e;return ((e=this.hls)==null?void 0:e.config.timelineOffset)||0}set timelineOffset(e){let t=this.timelineOffset;if(e!==t){let i=e-t;if(Math.abs(i)>1/9e4&&this.hls){if(this.hasDetails)throw new Error("Cannot set timelineOffset after playlists are loaded");this.hls.config.timelineOffset=e;}}}getAssetTime(e){let t=this.timelineOffset,i=this.duration;return Math.min(Math.max(0,e-t),i)}removeMediaListeners(){let e=this.mediaAttached;e&&(this._currentTime=e.currentTime,this.bufferSnapShot(),e.removeEventListener("timeupdate",this.checkPlayout));}bufferSnapShot(){if(this.mediaAttached){var e;(e=this.hls)!=null&&e.bufferedToEnd&&(this._bufferedEosTime=this.bufferedEnd);}}destroy(){this.removeMediaListeners(),this.hls&&this.hls.destroy(),this.hls=null,this.tracks=this.mediaAttached=this.checkPlayout=null;}attachMedia(e){var t;this.loadSource(),(t=this.hls)==null||t.attachMedia(e);}detachMedia(){var e;this.removeMediaListeners(),this.mediaAttached=null,(e=this.hls)==null||e.detachMedia();}resumeBuffering(){var e;(e=this.hls)==null||e.resumeBuffering();}pauseBuffering(){var e;(e=this.hls)==null||e.pauseBuffering();}transferMedia(){var e;return this.bufferSnapShot(),((e=this.hls)==null?void 0:e.transferMedia())||null}resetDetails(){let e=this.hls;if(e&&this.hasDetails){e.stopLoad();let t=i=>delete i.details;e.levels.forEach(t),e.allAudioTracks.forEach(t),e.allSubtitleTracks.forEach(t),this.hasDetails=false;}}on(e,t,i){var r;(r=this.hls)==null||r.on(e,t);}once(e,t,i){var r;(r=this.hls)==null||r.once(e,t);}off(e,t,i){var r;(r=this.hls)==null||r.off(e,t);}toString(){var e;return `HlsAssetPlayer: ${Js(this.assetItem)} ${(e=this.hls)==null?void 0:e.sessionId} ${this.appendInPlace?"append-in-place":""}`}},ug=.033,du=class extends ht{constructor(e,t){super("interstitials-sched",t),this.onScheduleUpdate=void 0,this.eventMap={},this.events=null,this.items=null,this.durations={primary:0,playout:0,integrated:0},this.onScheduleUpdate=e;}destroy(){this.reset(),this.onScheduleUpdate=null;}reset(){this.eventMap={},this.setDurations(0,0,0),this.events&&this.events.forEach(e=>e.reset()),this.events=this.items=null;}resetErrorsInRange(e,t){return this.events?this.events.reduce((i,r)=>e<=r.startOffset&&t>r.startOffset?(delete r.error,i+1):i,0):0}get duration(){let e=this.items;return e?e[e.length-1].end:0}get length(){return this.items?this.items.length:0}getEvent(e){return e&&this.eventMap[e]||null}hasEvent(e){return e in this.eventMap}findItemIndex(e,t){if(e.event)return this.findEventIndex(e.event.identifier);let i=-1;e.nextEvent?i=this.findEventIndex(e.nextEvent.identifier)-1:e.previousEvent&&(i=this.findEventIndex(e.previousEvent.identifier)+1);let r=this.items;if(r)for(r[i]||(t===void 0&&(t=e.start),i=this.findItemIndexAtTime(t));i>=0&&(n=r[i])!=null&&n.event;){var n;i--;}return i}findItemIndexAtTime(e,t){let i=this.items;if(i)for(let r=0;r<i.length;r++){let n=i[r];if(t&&t!=="primary"&&(n=n[t]),e===n.start||e>n.start&&e<n.end)return r}return -1}findJumpRestrictedIndex(e,t){let i=this.items;if(i)for(let r=e;r<=t&&i[r];r++){let n=i[r].event;if(n!=null&&n.restrictions.jump&&!n.appendInPlace)return r}return -1}findEventIndex(e){let t=this.items;if(t)for(let r=t.length;r--;){var i;if(((i=t[r].event)==null?void 0:i.identifier)===e)return r}return -1}findAssetIndex(e,t){let i=e.assetList,r=i.length;if(r>1)for(let n=0;n<r;n++){let a=i[n];if(!a.error){let o=a.timelineStart;if(t===o||t>o&&(t<o+(a.duration||0)||n===r-1))return n}}return 0}get assetIdAtEnd(){var e;let t=(e=this.items)==null||(e=e[this.length-1])==null?void 0:e.event;if(t){let i=t.assetList,r=i[i.length-1];if(r)return r.identifier}return null}parseInterstitialDateRanges(e,t){let i=e.main.details,{dateRanges:r}=i,n=this.events,a=this.parseDateRanges(r,{url:i.url},t),o=Object.keys(r),l=n?n.filter(d=>!o.includes(d.identifier)):[];a.length&&a.sort((d,c)=>{let u=d.cue.pre,h=d.cue.post,f=c.cue.pre,m=c.cue.post;if(u&&!f)return -1;if(f&&!u||h&&!m)return 1;if(m&&!h)return -1;if(!u&&!f&&!h&&!m){let p=d.startTime,E=c.startTime;if(p!==E)return p-E}return d.dateRange.tagOrder-c.dateRange.tagOrder}),this.events=a,l.forEach(d=>{this.removeEvent(d);}),this.updateSchedule(e,l);}updateSchedule(e,t=[],i=false){let r=this.events||[];if(r.length||t.length||this.length<2){let n=this.items,a=this.parseSchedule(r,e);(i||t.length||n?.length!==a.length||a.some((l,d)=>Math.abs(l.playout.start-n[d].playout.start)>.005||Math.abs(l.playout.end-n[d].playout.end)>.005))&&(this.items=a,this.onScheduleUpdate(t,n));}}parseDateRanges(e,t,i){let r=[],n=Object.keys(e);for(let a=0;a<n.length;a++){let o=n[a],l=e[o];if(l.isInterstitial){let d=this.eventMap[o];d?d.setDateRange(l):(d=new ou(l,t),this.eventMap[o]=d,i===false&&(d.appendInPlace=i)),r.push(d);}}return r}parseSchedule(e,t){let i=[],r=t.main.details,n=r.live?1/0:r.edge,a=0;if(e=e.filter(l=>!l.error&&!(l.cue.once&&l.hasPlayed)),e.length){this.resolveOffsets(e,t);let l=0,d=0;if(e.forEach((c,u)=>{let h=c.cue.pre,f=c.cue.post,m=e[u-1]||null,p=c.appendInPlace,E=f?n:c.startOffset,v=c.duration,T=c.timelineOccupancy===al.Range?v:0,S=c.resumptionOffset,A=m?.startTime===E,b=E+c.cumulativeDuration,D=p?b+v:E+S;if(h||!f&&E<=0){let k=d;d+=T,c.timelineStart=b;let R=a;a+=v,i.push({event:c,start:b,end:D,playout:{start:R,end:a},integrated:{start:k,end:d}});}else if(E<=n){if(!A){let L=E-l;if(L>ug){let M=l,B=d;d+=L;let H=a;a+=L;let j={previousEvent:e[u-1]||null,nextEvent:c,start:M,end:M+L,playout:{start:H,end:a},integrated:{start:B,end:d}};i.push(j);}else L>0&&m&&(m.cumulativeDuration+=L,i[i.length-1].end=E);}f&&(D=b),c.timelineStart=b;let k=d;d+=T;let R=a;a+=v,i.push({event:c,start:b,end:D,playout:{start:R,end:a},integrated:{start:k,end:d}});}else return;let I=c.resumeTime;f||I>n?l=n:l=I;}),l<n){var o;let c=l,u=d,h=n-l;d+=h;let f=a;a+=h,i.push({previousEvent:((o=i[i.length-1])==null?void 0:o.event)||null,nextEvent:null,start:l,end:c+h,playout:{start:f,end:a},integrated:{start:u,end:d}});}this.setDurations(n,a,d);}else i.push({previousEvent:null,nextEvent:null,start:0,end:n,playout:{start:0,end:n},integrated:{start:0,end:n}}),this.setDurations(n,n,n);return i}setDurations(e,t,i){this.durations={primary:e,playout:t,integrated:i};}resolveOffsets(e,t){let i=t.main.details,r=i.live?1/0:i.edge,n=0,a=-1;e.forEach((o,l)=>{let d=o.cue.pre,c=o.cue.post,u=d?0:c?r:o.startTime;this.updateAssetDurations(o),a===u?o.cumulativeDuration=n:(n=0,a=u),!c&&o.snapOptions.in&&(o.resumeAnchor=cs(null,i.fragments,o.startOffset+o.resumptionOffset,0,0)||void 0),o.appendInPlace&&!o.appendInPlaceStarted&&(this.primaryCanResumeInPlaceAt(o,t)||(o.appendInPlace=false)),!o.appendInPlace&&l+1<e.length&&e[l+1].startTime-e[l].resumeTime<ug&&(e[l+1].appendInPlace=false,e[l+1].appendInPlace&&this.warn(`Could not change append strategy for abutting event ${o}`));let f=G(o.resumeOffset)?o.resumeOffset:o.duration;n+=f;});}primaryCanResumeInPlaceAt(e,t){let i=e.resumeTime,r=e.startTime+e.resumptionOffset;return Math.abs(i-r)>nr?(this.log(`"${e.identifier}" resumption ${i} not aligned with estimated timeline end ${r}`),false):!Object.keys(t).some(a=>{let o=t[a].details,l=o.edge;if(i>=l)return this.log(`"${e.identifier}" resumption ${i} past ${a} playlist end ${l}`),false;let d=cs(null,o.fragments,i);if(!d)return this.log(`"${e.identifier}" resumption ${i} does not align with any fragments in ${a} playlist (${o.fragStart}-${o.fragmentEnd})`),true;let c=a==="audio"?.175:0;return Math.abs(d.start-i)<nr+c||Math.abs(d.end-i)<nr+c?false:(this.log(`"${e.identifier}" resumption ${i} not aligned with ${a} fragment bounds (${d.start}-${d.end} sn: ${d.sn} cc: ${d.cc})`),true)})}updateAssetDurations(e){if(!e.assetListLoaded)return;let t=e.timelineStart,i=0,r=false,n=false;for(let a=0;a<e.assetList.length;a++){let o=e.assetList[a],l=t+i;o.startOffset=i,o.timelineStart=l,r||(r=o.duration===null),n||(n=!!o.error);let d=o.error?0:o.duration||0;i+=d;}r&&!n?e.duration=Math.max(i,e.duration):e.duration=i;}removeEvent(e){e.reset(),delete this.eventMap[e.identifier];}};function $t(s){return `[${s.event?'"'+s.event.identifier+'"':"primary"}: ${s.start.toFixed(2)}-${s.end.toFixed(2)}]`}var cu=class{constructor(e){this.hls=void 0,this.hls=e;}destroy(){this.hls=null;}loadAssetList(e,t){let i=e.assetListUrl,r;try{r=wp(i,this.hls.sessionId,e.baseUrl);}catch(h){let f=this.assignAssetListError(e,x.ASSET_LIST_LOAD_ERROR,h,i);this.hls.trigger(g.ERROR,f);return}t&&r.protocol!=="data:"&&r.searchParams.set("_HLS_start_offset",""+t);let n=this.hls.config,a=n.loader,o=new a(n),l={responseType:"json",url:r.href},d=n.interstitialAssetListLoadPolicy.default,c={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},u={onSuccess:(h,f,m,p)=>{let E=h.data,v=E?.ASSETS;if(!Array.isArray(v)){let T=this.assignAssetListError(e,x.ASSET_LIST_PARSING_ERROR,new Error("Invalid interstitial asset list"),m.url,f,p);this.hls.trigger(g.ERROR,T);return}e.assetListResponse=E,this.hls.trigger(g.ASSET_LIST_LOADED,{event:e,assetListResponse:E,networkDetails:p});},onError:(h,f,m,p)=>{let E=this.assignAssetListError(e,x.ASSET_LIST_LOAD_ERROR,new Error(`Error loading X-ASSET-LIST: HTTP status ${h.code} ${h.text} (${f.url})`),f.url,p,m);this.hls.trigger(g.ERROR,E);},onTimeout:(h,f,m)=>{let p=this.assignAssetListError(e,x.ASSET_LIST_LOAD_TIMEOUT,new Error(`Timeout loading X-ASSET-LIST (${f.url})`),f.url,h,m);this.hls.trigger(g.ERROR,p);}};return o.load(l,c,u),this.hls.trigger(g.ASSET_LIST_LOADING,{event:e}),o}assignAssetListError(e,t,i,r,n,a){return e.error=i,{type:z.NETWORK_ERROR,details:t,fatal:false,interstitial:e,url:r,error:i,networkDetails:a,stats:n}}};function hg(s){s?.play().catch(()=>{});}function Ro(s,e){return `[${s}] Advancing timeline position to ${e}`}var uu=class extends ht{constructor(e,t){super("interstitials",e.logger),this.HlsPlayerClass=void 0,this.hls=void 0,this.assetListLoader=void 0,this.mediaSelection=null,this.altSelection=null,this.media=null,this.detachedData=null,this.requiredTracks=null,this.manager=null,this.playerQueue=[],this.bufferedPos=-1,this.timelinePos=-1,this.schedule=void 0,this.playingItem=null,this.bufferingItem=null,this.waitingItem=null,this.endedItem=null,this.playingAsset=null,this.endedAsset=null,this.bufferingAsset=null,this.shouldPlay=false,this.onPlay=()=>{this.shouldPlay=true;},this.onPause=()=>{this.shouldPlay=false;},this.onSeeking=()=>{let i=this.currentTime;if(i===void 0||this.playbackDisabled||!this.schedule)return;let r=i-this.timelinePos;if(Math.abs(r)<1/7056e5)return;let a=r<=-0.01;this.timelinePos=i,this.bufferedPos=i;let o=this.playingItem;if(!o){this.checkBuffer();return}if(a&&this.schedule.resetErrorsInRange(i,i-r)&&this.updateSchedule(true),this.checkBuffer(),a&&i<o.start||i>=o.end){var l;let f=this.findItemIndex(o),m=this.schedule.findItemIndexAtTime(i);if(m===-1&&(m=f+(a?-1:1),this.log(`seeked ${a?"back ":""}to position not covered by schedule ${i} (resolving from ${f} to ${m})`)),!this.isInterstitial(o)&&(l=this.media)!=null&&l.paused&&(this.shouldPlay=false),!a&&m>f){let p=this.schedule.findJumpRestrictedIndex(f+1,m);if(p>f){this.setSchedulePosition(p);return}}this.setSchedulePosition(m);return}let d=this.playingAsset;if(!d){if(this.playingLastItem&&this.isInterstitial(o)){let f=o.event.assetList[0];f&&(this.endedItem=this.playingItem,this.playingItem=null,this.setScheduleToAssetAtTime(i,f));}return}let c=d.timelineStart,u=d.duration||0;if(a&&i<c||i>=c+u){var h;(h=o.event)!=null&&h.appendInPlace&&(this.clearInterstitial(o.event,o),this.flushFrontBuffer(i)),this.setScheduleToAssetAtTime(i,d);}},this.onTimeupdate=()=>{let i=this.currentTime;if(i===void 0||this.playbackDisabled)return;if(i>this.timelinePos)this.timelinePos=i,i>this.bufferedPos&&this.checkBuffer();else return;let r=this.playingItem;if(!r||this.playingLastItem)return;if(i>=r.end){this.timelinePos=r.end;let o=this.findItemIndex(r);this.setSchedulePosition(o+1);}let n=this.playingAsset;if(!n)return;let a=n.timelineStart+(n.duration||0);i>=a&&this.setScheduleToAssetAtTime(i,n);},this.onScheduleUpdate=(i,r)=>{let n=this.schedule;if(!n)return;let a=this.playingItem,o=n.events||[],l=n.items||[],d=n.durations,c=i.map(p=>p.identifier),u=!!(o.length||c.length);(u||r)&&this.log(`INTERSTITIALS_UPDATED (${o.length}): ${o}
1377
- Schedule: ${l.map(p=>$t(p))} pos: ${this.timelinePos}`),c.length&&this.log(`Removed events ${c}`);let h=null,f=null;a&&(h=this.updateItem(a,this.timelinePos),this.itemsMatch(a,h)?this.playingItem=h:this.waitingItem=this.endedItem=null),this.waitingItem=this.updateItem(this.waitingItem),this.endedItem=this.updateItem(this.endedItem);let m=this.bufferingItem;if(m&&(f=this.updateItem(m,this.bufferedPos),this.itemsMatch(m,f)?this.bufferingItem=f:m.event&&(this.bufferingItem=this.playingItem,this.clearInterstitial(m.event,null))),i.forEach(p=>{p.assetList.forEach(E=>{this.clearAssetPlayer(E.identifier,null);});}),this.playerQueue.forEach(p=>{if(p.interstitial.appendInPlace){let E=p.assetItem.timelineStart,v=p.timelineOffset-E;if(v)try{p.timelineOffset=E;}catch(T){Math.abs(v)>nr&&this.warn(`${T} ("${p.assetId}" ${p.timelineOffset}->${E})`);}}}),u||r){if(this.hls.trigger(g.INTERSTITIALS_UPDATED,{events:o.slice(0),schedule:l.slice(0),durations:d,removedIds:c}),this.isInterstitial(a)&&c.includes(a.event.identifier)){this.warn(`Interstitial "${a.event.identifier}" removed while playing`),this.primaryFallback(a.event);return}a&&this.trimInPlace(h,a),m&&f!==h&&this.trimInPlace(f,m),this.checkBuffer();}},this.hls=e,this.HlsPlayerClass=t,this.assetListLoader=new cu(e),this.schedule=new du(this.onScheduleUpdate,e.logger),this.registerListeners();}registerListeners(){let e=this.hls;e&&(e.on(g.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(g.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(g.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(g.MANIFEST_LOADING,this.onManifestLoading,this),e.on(g.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(g.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(g.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.on(g.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(g.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.on(g.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.on(g.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.on(g.BUFFER_APPENDED,this.onBufferAppended,this),e.on(g.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(g.BUFFERED_TO_END,this.onBufferedToEnd,this),e.on(g.MEDIA_ENDED,this.onMediaEnded,this),e.on(g.ERROR,this.onError,this),e.on(g.DESTROYING,this.onDestroying,this));}unregisterListeners(){let e=this.hls;e&&(e.off(g.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(g.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(g.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(g.MANIFEST_LOADING,this.onManifestLoading,this),e.off(g.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(g.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(g.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.off(g.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(g.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.off(g.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.off(g.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.off(g.BUFFER_CODECS,this.onBufferCodecs,this),e.off(g.BUFFER_APPENDED,this.onBufferAppended,this),e.off(g.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(g.BUFFERED_TO_END,this.onBufferedToEnd,this),e.off(g.MEDIA_ENDED,this.onMediaEnded,this),e.off(g.ERROR,this.onError,this),e.off(g.DESTROYING,this.onDestroying,this));}startLoad(){this.resumeBuffering();}stopLoad(){this.pauseBuffering();}resumeBuffering(){var e;(e=this.getBufferingPlayer())==null||e.resumeBuffering();}pauseBuffering(){var e;(e=this.getBufferingPlayer())==null||e.pauseBuffering();}destroy(){this.unregisterListeners(),this.stopLoad(),this.assetListLoader&&this.assetListLoader.destroy(),this.emptyPlayerQueue(),this.clearScheduleState(),this.schedule&&this.schedule.destroy(),this.media=this.detachedData=this.mediaSelection=this.requiredTracks=this.altSelection=this.schedule=this.manager=null,this.hls=this.HlsPlayerClass=this.log=null,this.assetListLoader=null,this.onPlay=this.onPause=this.onSeeking=this.onTimeupdate=null,this.onScheduleUpdate=null;}onDestroying(){let e=this.primaryMedia||this.media;e&&this.removeMediaListeners(e);}removeMediaListeners(e){ut(e,"play",this.onPlay),ut(e,"pause",this.onPause),ut(e,"seeking",this.onSeeking),ut(e,"timeupdate",this.onTimeupdate);}onMediaAttaching(e,t){let i=this.media=t.media;nt(i,"seeking",this.onSeeking),nt(i,"timeupdate",this.onTimeupdate),nt(i,"play",this.onPlay),nt(i,"pause",this.onPause);}onMediaAttached(e,t){let i=this.effectivePlayingItem,r=this.detachedData;if(this.detachedData=null,i===null)this.checkStart();else if(!r){this.clearScheduleState();let n=this.findItemIndex(i);this.setSchedulePosition(n);}}clearScheduleState(){this.log("clear schedule state"),this.playingItem=this.bufferingItem=this.waitingItem=this.endedItem=this.playingAsset=this.endedAsset=this.bufferingAsset=null;}onMediaDetaching(e,t){let i=!!t.transferMedia,r=this.media;if(this.media=null,!i&&(r&&this.removeMediaListeners(r),this.detachedData)){let n=this.getBufferingPlayer();n&&(this.log(`Removing schedule state for detachedData and ${n}`),this.playingAsset=this.endedAsset=this.bufferingAsset=this.bufferingItem=this.waitingItem=this.detachedData=null,n.detachMedia()),this.shouldPlay=false;}}get interstitialsManager(){if(!this.hls)return null;if(this.manager)return this.manager;let e=this,t=()=>e.bufferingItem||e.waitingItem,i=u=>u&&e.getAssetPlayer(u.identifier),r=(u,h,f,m,p)=>{if(u){let E=u[h].start,v=u.event;if(v){if(h==="playout"||v.timelineOccupancy!==al.Point){let T=i(f);T?.interstitial===v&&(E+=T.assetItem.startOffset+T[p]);}}else {let T=m==="bufferedPos"?a():e[m];E+=T-u.start;}return E}return 0},n=(u,h)=>{var f;if(u!==0&&h!=="primary"&&(f=e.schedule)!=null&&f.length){var m;let p=e.schedule.findItemIndexAtTime(u),E=(m=e.schedule.items)==null?void 0:m[p];if(E){let v=E[h].start-E.start;return u+v}}return u},a=()=>{let u=e.bufferedPos;return u===Number.MAX_VALUE?o("primary"):Math.max(u,0)},o=u=>{var h,f;return (h=e.primaryDetails)!=null&&h.live?e.primaryDetails.edge:((f=e.schedule)==null?void 0:f.durations[u])||0},l=(u,h)=>{var f,m;let p=e.effectivePlayingItem;if(p!=null&&(f=p.event)!=null&&f.restrictions.skip||!e.schedule)return;e.log(`seek to ${u} "${h}"`);let E=e.effectivePlayingItem,v=e.schedule.findItemIndexAtTime(u,h),T=(m=e.schedule.items)==null?void 0:m[v],S=e.getBufferingPlayer(),A=S?.interstitial,b=A?.appendInPlace,D=E&&e.itemsMatch(E,T);if(E&&(b||D)){let I=i(e.playingAsset),k=I?.media||e.primaryMedia;if(k){let R=h==="primary"?k.currentTime:r(E,h,e.playingAsset,"timelinePos","currentTime"),L=u-R,M=(b?R:k.currentTime)+L;if(M>=0&&(!I||b||M<=I.duration)){k.currentTime=M;return}}}if(T){let I=u;if(h!=="primary"){let R=T[h].start,L=u-R;I=T.start+L;}let k=!e.isInterstitial(T);if((!e.isInterstitial(E)||E.event.appendInPlace)&&(k||T.event.appendInPlace)){let R=e.media||(b?S?.media:null);R&&(R.currentTime=I);}else if(E){let R=e.findItemIndex(E);if(v>R){let M=e.schedule.findJumpRestrictedIndex(R+1,v);if(M>R){e.setSchedulePosition(M);return}}let L=0;if(k)e.timelinePos=I,e.checkBuffer();else {let M=T.event.assetList,B=u-(T[h]||T).start;for(let H=M.length;H--;){let j=M[H];if(j.duration&&B>=j.startOffset&&B<j.startOffset+j.duration){L=H;break}}}e.setSchedulePosition(v,L);}}},d=()=>{let u=e.effectivePlayingItem;if(e.isInterstitial(u))return u;let h=t();return e.isInterstitial(h)?h:null},c={get bufferedEnd(){let u=t(),h=e.bufferingItem;if(h&&h===u){var f;return r(h,"playout",e.bufferingAsset,"bufferedPos","bufferedEnd")-h.playout.start||((f=e.bufferingAsset)==null?void 0:f.startOffset)||0}return 0},get currentTime(){let u=d(),h=e.effectivePlayingItem;return h&&h===u?r(h,"playout",e.effectivePlayingAsset,"timelinePos","currentTime")-h.playout.start:0},set currentTime(u){let h=d(),f=e.effectivePlayingItem;f&&f===h&&l(u+f.playout.start,"playout");},get duration(){let u=d();return u?u.playout.end-u.playout.start:0},get assetPlayers(){var u;let h=(u=d())==null?void 0:u.event.assetList;return h?h.map(f=>e.getAssetPlayer(f.identifier)):[]},get playingIndex(){var u;let h=(u=d())==null?void 0:u.event;return h&&e.effectivePlayingAsset?h.findAssetIndex(e.effectivePlayingAsset):-1},get scheduleItem(){return d()}};return this.manager={get events(){var u;return ((u=e.schedule)==null||(u=u.events)==null?void 0:u.slice(0))||[]},get schedule(){var u;return ((u=e.schedule)==null||(u=u.items)==null?void 0:u.slice(0))||[]},get interstitialPlayer(){return d()?c:null},get playerQueue(){return e.playerQueue.slice(0)},get bufferingAsset(){return e.bufferingAsset},get bufferingItem(){return t()},get bufferingIndex(){let u=t();return e.findItemIndex(u)},get playingAsset(){return e.effectivePlayingAsset},get playingItem(){return e.effectivePlayingItem},get playingIndex(){let u=e.effectivePlayingItem;return e.findItemIndex(u)},primary:{get bufferedEnd(){return a()},get currentTime(){let u=e.timelinePos;return u>0?u:0},set currentTime(u){l(u,"primary");},get duration(){return o("primary")},get seekableStart(){var u;return ((u=e.primaryDetails)==null?void 0:u.fragmentStart)||0}},integrated:{get bufferedEnd(){return r(t(),"integrated",e.bufferingAsset,"bufferedPos","bufferedEnd")},get currentTime(){return r(e.effectivePlayingItem,"integrated",e.effectivePlayingAsset,"timelinePos","currentTime")},set currentTime(u){l(u,"integrated");},get duration(){return o("integrated")},get seekableStart(){var u;return n(((u=e.primaryDetails)==null?void 0:u.fragmentStart)||0,"integrated")}},skip:()=>{let u=e.effectivePlayingItem,h=u?.event;if(h&&!h.restrictions.skip){let f=e.findItemIndex(u);if(h.appendInPlace){let m=u.playout.start+u.event.duration;l(m+.001,"playout");}else e.advanceAfterAssetEnded(h,f,1/0);}}}}get effectivePlayingItem(){return this.waitingItem||this.playingItem||this.endedItem}get effectivePlayingAsset(){return this.playingAsset||this.endedAsset}get playingLastItem(){var e;let t=this.playingItem,i=(e=this.schedule)==null?void 0:e.items;return !this.playbackStarted||!t||!i?false:this.findItemIndex(t)===i.length-1}get playbackStarted(){return this.effectivePlayingItem!==null}get currentTime(){var e,t;if(this.mediaSelection===null)return;let i=this.waitingItem||this.playingItem;if(this.isInterstitial(i)&&!i.event.appendInPlace)return;let r=this.media;!r&&(e=this.bufferingItem)!=null&&(e=e.event)!=null&&e.appendInPlace&&(r=this.primaryMedia);let n=(t=r)==null?void 0:t.currentTime;if(!(n===void 0||!G(n)))return n}get primaryMedia(){var e;return this.media||((e=this.detachedData)==null?void 0:e.media)||null}isInterstitial(e){return !!(e!=null&&e.event)}retreiveMediaSource(e,t){let i=this.getAssetPlayer(e);i&&this.transferMediaFromPlayer(i,t);}transferMediaFromPlayer(e,t){let i=e.interstitial.appendInPlace,r=e.media;if(i&&r===this.primaryMedia){if(this.bufferingAsset=null,(!t||this.isInterstitial(t)&&!t.event.appendInPlace)&&t&&r){this.detachedData={media:r};return}let n=e.transferMedia();this.log(`transfer MediaSource from ${e} ${Ae(n)}`),this.detachedData=n;}else t&&r&&(this.shouldPlay||(this.shouldPlay=!r.paused));}transferMediaTo(e,t){var i,r;if(e.media===t)return;let n=null,a=this.hls,o=e!==a,l=o&&e.interstitial.appendInPlace,d=(i=this.detachedData)==null?void 0:i.mediaSource,c;if(a.media)l&&(n=a.transferMedia(),this.detachedData=n),c="Primary";else if(d){let m=this.getBufferingPlayer();m?(n=m.transferMedia(),c=`${m}`):c="detached MediaSource";}else c="detached media";if(!n){if(d)n=this.detachedData,this.log(`using detachedData: MediaSource ${Ae(n)}`);else if(!this.detachedData||a.media===t){let m=this.playerQueue;m.length>1&&m.forEach(p=>{if(o&&p.interstitial.appendInPlace!==l){let E=p.interstitial;this.clearInterstitial(p.interstitial,null),E.appendInPlace=false,E.appendInPlace&&this.warn(`Could not change append strategy for queued assets ${E}`);}}),this.hls.detachMedia(),this.detachedData={media:t};}}let u=n&&"mediaSource"in n&&((r=n.mediaSource)==null?void 0:r.readyState)!=="closed",h=u&&n?n:t;this.log(`${u?"transfering MediaSource":"attaching media"} to ${o?e:"Primary"} from ${c} (media.currentTime: ${t.currentTime})`);let f=this.schedule;if(h===n&&f){let m=o&&e.assetId===f.assetIdAtEnd;h.overrides={duration:f.duration,endOfStream:!o||m,cueRemoval:!o};}e.attachMedia(h);}onInterstitialCueEnter(){this.onTimeupdate();}checkStart(){let e=this.schedule,t=e?.events;if(!t||this.playbackDisabled||!this.media)return;this.bufferedPos===-1&&(this.bufferedPos=0);let i=this.timelinePos,r=this.effectivePlayingItem;if(i===-1){let n=this.hls.startPosition;if(this.log(Ro("checkStart",n)),this.timelinePos=n,t.length&&t[0].cue.pre){let a=e.findEventIndex(t[0].identifier);this.setSchedulePosition(a);}else if(n>=0||!this.primaryLive){let a=this.timelinePos=n>0?n:0,o=e.findItemIndexAtTime(a);this.setSchedulePosition(o);}}else if(r&&!this.playingItem){let n=e.findItemIndex(r);this.setSchedulePosition(n);}}advanceAssetBuffering(e,t){let i=e.event,r=i.findAssetIndex(t),n=rc(i,r);if(!i.isAssetPastPlayoutLimit(n))this.bufferedToEvent(e,n);else if(this.schedule){var a;let o=(a=this.schedule.items)==null?void 0:a[this.findItemIndex(e)+1];o&&this.bufferedToItem(o);}}advanceAfterAssetEnded(e,t,i){let r=rc(e,i);if(e.isAssetPastPlayoutLimit(r)){if(this.schedule){let n=this.schedule.items;if(n){let a=t+1,o=n.length;if(a>=o){this.setSchedulePosition(-1);return}let l=e.resumeTime;this.timelinePos<l&&(this.log(Ro("advanceAfterAssetEnded",l)),this.timelinePos=l,e.appendInPlace&&this.advanceInPlace(l),this.checkBuffer(this.bufferedPos<l)),this.setSchedulePosition(a);}}}else {if(e.appendInPlace){let n=e.assetList[r];n&&this.advanceInPlace(n.timelineStart);}this.setSchedulePosition(t,r);}}setScheduleToAssetAtTime(e,t){let i=this.schedule;if(!i)return;let r=t.parentIdentifier,n=i.getEvent(r);if(n){let a=i.findEventIndex(r),o=i.findAssetIndex(n,e);this.advanceAfterAssetEnded(n,a,o-1);}}setSchedulePosition(e,t){var i;let r=(i=this.schedule)==null?void 0:i.items;if(!r||this.playbackDisabled)return;let n=e>=0?r[e]:null;this.log(`setSchedulePosition ${e}, ${t} (${n&&$t(n)}) pos: ${this.timelinePos}`);let a=this.waitingItem||this.playingItem,o=this.playingLastItem;if(this.isInterstitial(a)){let c=a.event,u=this.playingAsset,h=u?.identifier,f=h?this.getAssetPlayer(h):null;if(f&&h&&(!this.eventItemsMatch(a,n)||t!==void 0&&h!==c.assetList[t].identifier)){var l;let m=c.findAssetIndex(u);if(this.log(`INTERSTITIAL_ASSET_ENDED ${m+1}/${c.assetList.length} ${Js(u)}`),this.endedAsset=u,this.playingAsset=null,this.hls.trigger(g.INTERSTITIAL_ASSET_ENDED,{asset:u,assetListIndex:m,event:c,schedule:r.slice(0),scheduleIndex:e,player:f}),a!==this.playingItem){this.itemsMatch(a,this.playingItem)&&!this.playingAsset&&this.advanceAfterAssetEnded(c,this.findItemIndex(this.playingItem),m);return}this.retreiveMediaSource(h,n),f.media&&!((l=this.detachedData)!=null&&l.mediaSource)&&f.detachMedia();}if(!this.eventItemsMatch(a,n)&&(this.endedItem=a,this.playingItem=null,this.log(`INTERSTITIAL_ENDED ${c} ${$t(a)}`),c.hasPlayed=true,this.hls.trigger(g.INTERSTITIAL_ENDED,{event:c,schedule:r.slice(0),scheduleIndex:e}),c.cue.once)){var d;this.updateSchedule();let m=(d=this.schedule)==null?void 0:d.items;if(n&&m){let p=this.findItemIndex(n);this.advanceSchedule(p,m,t,a,o);}return}}this.advanceSchedule(e,r,t,a,o);}advanceSchedule(e,t,i,r,n){let a=this.schedule;if(!a)return;let o=t[e]||null,l=this.primaryMedia,d=this.playerQueue;if(d.length&&d.forEach(c=>{let u=c.interstitial,h=a.findEventIndex(u.identifier);(h<e||h>e+1)&&this.clearInterstitial(u,o);}),this.isInterstitial(o)){this.timelinePos=Math.min(Math.max(this.timelinePos,o.start),o.end);let c=o.event;if(i===void 0){i=a.findAssetIndex(c,this.timelinePos);let m=rc(c,i-1);if(c.isAssetPastPlayoutLimit(m)||c.appendInPlace&&this.timelinePos===o.end){this.advanceAfterAssetEnded(c,e,i);return}i=m;}let u=this.waitingItem;this.assetsBuffered(o,l)||this.setBufferingItem(o);let h=this.preloadAssets(c,i);if(this.eventItemsMatch(o,u||r)||(this.waitingItem=o,this.log(`INTERSTITIAL_STARTED ${$t(o)} ${c.appendInPlace?"append in place":""}`),this.hls.trigger(g.INTERSTITIAL_STARTED,{event:c,schedule:t.slice(0),scheduleIndex:e})),!c.assetListLoaded){this.log(`Waiting for ASSET-LIST to complete loading ${c}`);return}if(c.assetListLoader&&(c.assetListLoader.destroy(),c.assetListLoader=void 0),!l){this.log(`Waiting for attachMedia to start Interstitial ${c}`);return}this.waitingItem=this.endedItem=null,this.playingItem=o;let f=c.assetList[i];if(!f){this.advanceAfterAssetEnded(c,e,i||0);return}if(h||(h=this.getAssetPlayer(f.identifier)),h===null||h.destroyed){let m=c.assetList.length;this.warn(`asset ${i+1}/${m} player destroyed ${c}`),h=this.createAssetPlayer(c,f,i),h.loadSource();}if(!this.eventItemsMatch(o,this.bufferingItem)&&c.appendInPlace&&this.isAssetBuffered(f))return;this.startAssetPlayer(h,i,t,e,l),this.shouldPlay&&hg(h.media);}else o?(this.resumePrimary(o,e,r),this.shouldPlay&&hg(this.hls.media)):n&&this.isInterstitial(r)&&(this.endedItem=null,this.playingItem=r,r.event.appendInPlace||this.attachPrimary(a.durations.primary,null));}get playbackDisabled(){return this.hls.config.enableInterstitialPlayback===false}get primaryDetails(){var e;return (e=this.mediaSelection)==null?void 0:e.main.details}get primaryLive(){var e;return !!((e=this.primaryDetails)!=null&&e.live)}resumePrimary(e,t,i){var r,n;if(this.playingItem=e,this.playingAsset=this.endedAsset=null,this.waitingItem=this.endedItem=null,this.bufferedToItem(e),this.log(`resuming ${$t(e)}`),!((r=this.detachedData)!=null&&r.mediaSource)){let o=this.timelinePos;(o<e.start||o>=e.end)&&(o=this.getPrimaryResumption(e,t),this.log(Ro("resumePrimary",o)),this.timelinePos=o),this.attachPrimary(o,e);}if(!i)return;let a=(n=this.schedule)==null?void 0:n.items;a&&(this.log(`INTERSTITIALS_PRIMARY_RESUMED ${$t(e)}`),this.hls.trigger(g.INTERSTITIALS_PRIMARY_RESUMED,{schedule:a.slice(0),scheduleIndex:t}),this.checkBuffer());}getPrimaryResumption(e,t){let i=e.start;if(this.primaryLive){let r=this.primaryDetails;if(t===0)return this.hls.startPosition;if(r&&(i<r.fragmentStart||i>r.edge))return this.hls.liveSyncPosition||-1}return i}isAssetBuffered(e){let t=this.getAssetPlayer(e.identifier);return t!=null&&t.hls?t.hls.bufferedToEnd:re.bufferInfo(this.primaryMedia,this.timelinePos,0).end+1>=e.timelineStart+(e.duration||0)}attachPrimary(e,t,i){t?this.setBufferingItem(t):this.bufferingItem=this.playingItem,this.bufferingAsset=null;let r=this.primaryMedia;if(!r)return;let n=this.hls;n.media?this.checkBuffer():(this.transferMediaTo(n,r),i&&this.startLoadingPrimaryAt(e,i)),i||(this.log(Ro("attachPrimary",e)),this.timelinePos=e,this.startLoadingPrimaryAt(e,i));}startLoadingPrimaryAt(e,t){var i;let r=this.hls;!r.loadingEnabled||!r.media||Math.abs((((i=r.mainForwardBufferInfo)==null?void 0:i.start)||r.media.currentTime)-e)>.5?r.startLoad(e,t):r.bufferingEnabled||r.resumeBuffering();}onManifestLoading(){var e;this.stopLoad(),(e=this.schedule)==null||e.reset(),this.emptyPlayerQueue(),this.clearScheduleState(),this.shouldPlay=false,this.bufferedPos=this.timelinePos=-1,this.mediaSelection=this.altSelection=this.manager=this.requiredTracks=null,this.hls.off(g.BUFFER_CODECS,this.onBufferCodecs,this),this.hls.on(g.BUFFER_CODECS,this.onBufferCodecs,this);}onLevelUpdated(e,t){if(t.level===-1||!this.schedule)return;let i=this.hls.levels[t.level];if(!i.details)return;let r=ve(ve({},this.mediaSelection||this.altSelection),{},{main:i});this.mediaSelection=r,this.schedule.parseInterstitialDateRanges(r,this.hls.config.interstitialAppendInPlace),!this.effectivePlayingItem&&this.schedule.items&&this.checkStart();}onAudioTrackUpdated(e,t){let i=this.hls.audioTracks[t.id],r=this.mediaSelection;if(!r){this.altSelection=ve(ve({},this.altSelection),{},{audio:i});return}let n=ve(ve({},r),{},{audio:i});this.mediaSelection=n;}onSubtitleTrackUpdated(e,t){let i=this.hls.subtitleTracks[t.id],r=this.mediaSelection;if(!r){this.altSelection=ve(ve({},this.altSelection),{},{subtitles:i});return}let n=ve(ve({},r),{},{subtitles:i});this.mediaSelection=n;}onAudioTrackSwitching(e,t){let i=Am(t);this.playerQueue.forEach(({hls:r})=>r&&(r.setAudioOption(t)||r.setAudioOption(i)));}onSubtitleTrackSwitch(e,t){let i=Am(t);this.playerQueue.forEach(({hls:r})=>r&&(r.setSubtitleOption(t)||t.id!==-1&&r.setSubtitleOption(i)));}onBufferCodecs(e,t){let i=t.tracks;i&&(this.requiredTracks=i);}onBufferAppended(e,t){this.checkBuffer();}onBufferFlushed(e,t){let i=this.playingItem;if(i&&!this.itemsMatch(i,this.bufferingItem)&&!this.isInterstitial(i)){let r=this.timelinePos;this.bufferedPos=r,this.checkBuffer();}}onBufferedToEnd(e){if(!this.schedule)return;let t=this.schedule.events;if(this.bufferedPos<Number.MAX_VALUE&&t){for(let r=0;r<t.length;r++){let n=t[r];if(n.cue.post){var i;let a=this.schedule.findEventIndex(n.identifier),o=(i=this.schedule.items)==null?void 0:i[a];this.isInterstitial(o)&&this.eventItemsMatch(o,this.bufferingItem)&&this.bufferedToItem(o,0);break}}this.bufferedPos=Number.MAX_VALUE;}}onMediaEnded(e){let t=this.playingItem;if(!this.playingLastItem&&t){let i=this.findItemIndex(t);this.setSchedulePosition(i+1);}else this.shouldPlay=false;}updateItem(e,t){var i;let r=(i=this.schedule)==null?void 0:i.items;if(e&&r){let n=this.findItemIndex(e,t);return r[n]||null}return null}trimInPlace(e,t){if(this.isInterstitial(e)&&e.event.appendInPlace&&t.end-e.end>.25){e.event.assetList.forEach((n,a)=>{e.event.isAssetPastPlayoutLimit(a)&&this.clearAssetPlayer(n.identifier,null);});let i=e.end+.25,r=re.bufferInfo(this.primaryMedia,i,0);(r.end>i||(r.nextStart||0)>i)&&(this.log(`trim buffered interstitial ${$t(e)} (was ${$t(t)})`),this.attachPrimary(i,null,true),this.flushFrontBuffer(i));}}itemsMatch(e,t){return !!t&&(e===t||e.event&&t.event&&this.eventItemsMatch(e,t)||!e.event&&!t.event&&this.findItemIndex(e)===this.findItemIndex(t))}eventItemsMatch(e,t){var i;return !!t&&(e===t||e.event.identifier===((i=t.event)==null?void 0:i.identifier))}findItemIndex(e,t){return e&&this.schedule?this.schedule.findItemIndex(e,t):-1}updateSchedule(e=false){var t;let i=this.mediaSelection;i&&((t=this.schedule)==null||t.updateSchedule(i,[],e));}checkBuffer(e){var t;let i=(t=this.schedule)==null?void 0:t.items;if(!i)return;let r=re.bufferInfo(this.primaryMedia,this.timelinePos,0);e&&(this.bufferedPos=this.timelinePos),e||(e=r.len<1),this.updateBufferedPos(r.end,i,e);}updateBufferedPos(e,t,i){let r=this.schedule,n=this.bufferingItem;if(this.bufferedPos>e||!r)return;if(t.length===1&&this.itemsMatch(t[0],n)){this.bufferedPos=e;return}let a=this.playingItem,o=this.findItemIndex(a),l=r.findItemIndexAtTime(e);if(this.bufferedPos<e){var d;let c=this.findItemIndex(n),u=Math.min(c+1,t.length-1),h=t[u];if((l===-1&&n&&e>=n.end||(d=h.event)!=null&&d.appendInPlace&&e+.01>=h.start)&&(l=u),this.isInterstitial(n)){let f=n.event;if(u-o>1&&f.appendInPlace===false||f.assetList.length===0&&f.assetListLoader)return}if(this.bufferedPos=e,l>c&&l>o)this.bufferedToItem(h);else {let f=this.primaryDetails;this.primaryLive&&f&&e>f.edge-f.targetduration&&h.start<f.edge+this.hls.config.interstitialLiveLookAhead&&this.isInterstitial(h)&&this.preloadAssets(h.event,0);}}else i&&a&&!this.itemsMatch(a,n)&&(l===o?this.bufferedToItem(a):l===o+1&&this.bufferedToItem(t[l]));}assetsBuffered(e,t){return e.event.assetList.length===0?false:!e.event.assetList.some(r=>{let n=this.getAssetPlayer(r.identifier);return !(n!=null&&n.bufferedInPlaceToEnd(t))})}setBufferingItem(e){let t=this.bufferingItem,i=this.schedule;if(!this.itemsMatch(e,t)&&i){let{items:r,events:n}=i;if(!r||!n)return t;let a=this.isInterstitial(e),o=this.getBufferingPlayer();this.bufferingItem=e,this.bufferedPos=Math.max(e.start,Math.min(e.end,this.timelinePos));let l=o?o.remaining:t?t.end-this.timelinePos:0;if(this.log(`INTERSTITIALS_BUFFERED_TO_BOUNDARY ${$t(e)}`+(t?` (${l.toFixed(2)} remaining)`:"")),!this.playbackDisabled)if(a){let d=i.findAssetIndex(e.event,this.bufferedPos);e.event.assetList.forEach((c,u)=>{let h=this.getAssetPlayer(c.identifier);h&&(u===d&&h.loadSource(),h.resumeBuffering());});}else this.hls.resumeBuffering(),this.playerQueue.forEach(d=>d.pauseBuffering());this.hls.trigger(g.INTERSTITIALS_BUFFERED_TO_BOUNDARY,{events:n.slice(0),schedule:r.slice(0),bufferingIndex:this.findItemIndex(e),playingIndex:this.findItemIndex(this.playingItem)});}else this.bufferingItem!==e&&(this.bufferingItem=e);return t}bufferedToItem(e,t=0){let i=this.setBufferingItem(e);if(!this.playbackDisabled){if(this.isInterstitial(e))this.bufferedToEvent(e,t);else if(i!==null){this.bufferingAsset=null;let r=this.detachedData;r?r.mediaSource?this.attachPrimary(e.start,e,true):this.preloadPrimary(e):this.preloadPrimary(e);}}}preloadPrimary(e){let t=this.findItemIndex(e),i=this.getPrimaryResumption(e,t);this.startLoadingPrimaryAt(i);}bufferedToEvent(e,t){let i=e.event,r=i.assetList.length===0&&!i.assetListLoader,n=i.cue.once;if(r||!n){let a=this.preloadAssets(i,t);if(a!=null&&a.interstitial.appendInPlace){let o=this.primaryMedia;o&&this.bufferAssetPlayer(a,o);}}}preloadAssets(e,t){let i=e.assetUrl,r=e.assetList.length,n=r===0&&!e.assetListLoader,a=e.cue.once;if(n){let l=e.timelineStart;if(e.appendInPlace){var o;let h=this.playingItem;!this.isInterstitial(h)&&(h==null||(o=h.nextEvent)==null?void 0:o.identifier)===e.identifier&&this.flushFrontBuffer(l+.25);}let d,c=0;if(!this.playingItem&&this.primaryLive&&(c=this.hls.startPosition,c===-1&&(c=this.hls.liveSyncPosition||0)),c&&!(e.cue.pre||e.cue.post)){let h=c-l;h>0&&(d=Math.round(h*1e3)/1e3);}if(this.log(`Load interstitial asset ${t+1}/${i?1:r} ${e}${d?` live-start: ${c} start-offset: ${d}`:""}`),i)return this.createAsset(e,0,0,l,e.duration,i);let u=this.assetListLoader.loadAssetList(e,d);u&&(e.assetListLoader=u);}else if(!a&&r){for(let d=t;d<r;d++){let c=e.assetList[d],u=this.getAssetPlayerQueueIndex(c.identifier);(u===-1||this.playerQueue[u].destroyed)&&!c.error&&this.createAssetPlayer(e,c,d);}let l=e.assetList[t];if(l){let d=this.getAssetPlayer(l.identifier);return d&&d.loadSource(),d}}return null}flushFrontBuffer(e){let t=this.requiredTracks;if(!t)return;this.log(`Removing front buffer starting at ${e}`),Object.keys(t).forEach(r=>{this.hls.trigger(g.BUFFER_FLUSHING,{startOffset:e,endOffset:1/0,type:r});});}getAssetPlayerQueueIndex(e){let t=this.playerQueue;for(let i=0;i<t.length;i++)if(e===t[i].assetId)return i;return -1}getAssetPlayer(e){let t=this.getAssetPlayerQueueIndex(e);return this.playerQueue[t]||null}getBufferingPlayer(){let{playerQueue:e,primaryMedia:t}=this;if(t){for(let i=0;i<e.length;i++)if(e[i].media===t)return e[i]}return null}createAsset(e,t,i,r,n,a){let o={parentIdentifier:e.identifier,identifier:aA(e,a,t),duration:n,startOffset:i,timelineStart:r,uri:a};return this.createAssetPlayer(e,o,t)}createAssetPlayer(e,t,i){let r=this.hls,n=r.userConfig,a=n.videoPreference,o=r.loadLevelObj||r.levels[r.currentLevel];(a||o)&&(a=ye({},a),o.videoCodec&&(a.videoCodec=o.videoCodec),o.videoRange&&(a.allowedVideoRanges=[o.videoRange]));let l=r.audioTracks[r.audioTrack],d=r.subtitleTracks[r.subtitleTrack],c=0;if(this.primaryLive||e.appendInPlace){let A=this.timelinePos-t.timelineStart;if(A>1){let b=t.duration;b&&A<b&&(c=A);}}let u=t.identifier,h=ve(ve({},n),{},{maxMaxBufferLength:Math.min(180,r.config.maxMaxBufferLength),autoStartLoad:true,startFragPrefetch:true,primarySessionId:r.sessionId,assetPlayerId:u,abrEwmaDefaultEstimate:r.bandwidthEstimate,interstitialsController:void 0,startPosition:c,liveDurationInfinity:false,testBandwidth:false,videoPreference:a,audioPreference:l||n.audioPreference,subtitlePreference:d||n.subtitlePreference});e.appendInPlace&&(e.appendInPlaceStarted=true,t.timelineStart&&(h.timelineOffset=t.timelineStart));let f=h.cmcd;f!=null&&f.sessionId&&f.contentId&&(h.cmcd=ye({},f,{contentId:hn(t.uri)})),this.getAssetPlayer(u)&&this.warn(`Duplicate date range identifier ${e} and asset ${u}`);let m=new lu(this.HlsPlayerClass,h,e,t);this.playerQueue.push(m),e.assetList[i]=t;let p=true,E=A=>{if(A.live){var b;let k=new Error(`Interstitials MUST be VOD assets ${e}`),R={fatal:true,type:z.OTHER_ERROR,details:x.INTERSTITIAL_ASSET_ITEM_ERROR,error:k},L=((b=this.schedule)==null?void 0:b.findEventIndex(e.identifier))||-1;this.handleAssetItemError(R,e,L,i,k.message);return}let D=A.edge-A.fragmentStart,I=t.duration;(p||I===null||D>I)&&(p=false,this.log(`Interstitial asset "${u}" duration change ${I} > ${D}`),t.duration=D,this.updateSchedule());};m.on(g.LEVEL_UPDATED,(A,{details:b})=>E(b)),m.on(g.LEVEL_PTS_UPDATED,(A,{details:b})=>E(b)),m.on(g.EVENT_CUE_ENTER,()=>this.onInterstitialCueEnter());let v=(A,b)=>{let D=this.getAssetPlayer(u);if(D&&b.tracks){D.off(g.BUFFER_CODECS,v),D.tracks=b.tracks;let I=this.primaryMedia;this.bufferingAsset===D.assetItem&&I&&!D.media&&this.bufferAssetPlayer(D,I);}};m.on(g.BUFFER_CODECS,v);let T=()=>{var A;let b=this.getAssetPlayer(u);if(this.log(`buffered to end of asset ${b}`),!b||!this.schedule)return;let D=this.schedule.findEventIndex(e.identifier),I=(A=this.schedule.items)==null?void 0:A[D];this.isInterstitial(I)&&this.advanceAssetBuffering(I,t);};m.on(g.BUFFERED_TO_END,T);let S=A=>()=>{if(!this.getAssetPlayer(u)||!this.schedule)return;this.shouldPlay=true;let D=this.schedule.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,D,A);};return m.once(g.MEDIA_ENDED,S(i)),m.once(g.PLAYOUT_LIMIT_REACHED,S(1/0)),m.on(g.ERROR,(A,b)=>{if(!this.schedule)return;let D=this.getAssetPlayer(u);if(b.details===x.BUFFER_STALLED_ERROR){if(D!=null&&D.appendInPlace){this.handleInPlaceStall(e);return}this.onTimeupdate(),this.checkBuffer(true);return}this.handleAssetItemError(b,e,this.schedule.findEventIndex(e.identifier),i,`Asset player error ${b.error} ${e}`);}),m.on(g.DESTROYING,()=>{if(!this.getAssetPlayer(u)||!this.schedule)return;let b=new Error(`Asset player destroyed unexpectedly ${u}`),D={fatal:true,type:z.OTHER_ERROR,details:x.INTERSTITIAL_ASSET_ITEM_ERROR,error:b};this.handleAssetItemError(D,e,this.schedule.findEventIndex(e.identifier),i,b.message);}),this.log(`INTERSTITIAL_ASSET_PLAYER_CREATED ${Js(t)}`),this.hls.trigger(g.INTERSTITIAL_ASSET_PLAYER_CREATED,{asset:t,assetListIndex:i,event:e,player:m}),m}clearInterstitial(e,t){e.assetList.forEach(i=>{this.clearAssetPlayer(i.identifier,t);}),e.reset();}resetAssetPlayer(e){let t=this.getAssetPlayerQueueIndex(e);if(t!==-1){this.log(`reset asset player "${e}" after error`);let i=this.playerQueue[t];this.transferMediaFromPlayer(i,null),i.resetDetails();}}clearAssetPlayer(e,t){let i=this.getAssetPlayerQueueIndex(e);if(i!==-1){let r=this.playerQueue[i];this.log(`clear ${r} toSegment: ${t&&$t(t)}`),this.transferMediaFromPlayer(r,t),this.playerQueue.splice(i,1),r.destroy();}}emptyPlayerQueue(){let e;for(;e=this.playerQueue.pop();)e.destroy();this.playerQueue=[];}startAssetPlayer(e,t,i,r,n){let{interstitial:a,assetItem:o,assetId:l}=e,d=a.assetList.length,c=this.playingAsset;this.endedAsset=null,this.playingAsset=o,(!c||c.identifier!==l)&&(c&&(this.clearAssetPlayer(c.identifier,i[r]),delete c.error),this.log(`INTERSTITIAL_ASSET_STARTED ${t+1}/${d} ${Js(o)}`),this.hls.trigger(g.INTERSTITIAL_ASSET_STARTED,{asset:o,assetListIndex:t,event:a,schedule:i.slice(0),scheduleIndex:r,player:e})),this.bufferAssetPlayer(e,n);}bufferAssetPlayer(e,t){var i,r;if(!this.schedule)return;let{interstitial:n,assetItem:a}=e,o=this.schedule.findEventIndex(n.identifier),l=(i=this.schedule.items)==null?void 0:i[o];if(!l)return;e.loadSource(),this.setBufferingItem(l),this.bufferingAsset=a;let d=this.getBufferingPlayer();if(d===e)return;let c=n.appendInPlace;if(c&&d?.interstitial.appendInPlace===false)return;let u=d?.tracks||((r=this.detachedData)==null?void 0:r.tracks)||this.requiredTracks;if(c&&a!==this.playingAsset){if(!e.tracks){this.log(`Waiting for track info before buffering ${e}`);return}if(u&&!bg(u,e.tracks)){let h=new Error(`Asset ${Js(a)} SourceBuffer tracks ('${Object.keys(e.tracks)}') are not compatible with primary content tracks ('${Object.keys(u)}')`),f={fatal:true,type:z.OTHER_ERROR,details:x.INTERSTITIAL_ASSET_ITEM_ERROR,error:h},m=n.findAssetIndex(a);this.handleAssetItemError(f,n,o,m,h.message);return}}this.transferMediaTo(e,t);}handleInPlaceStall(e){let t=this.schedule,i=this.primaryMedia;if(!t||!i)return;let r=i.currentTime,n=t.findAssetIndex(e,r),a=e.assetList[n];if(a){let o=this.getAssetPlayer(a.identifier);if(o){let l=o.currentTime||r-a.timelineStart,d=o.duration-l;if(this.warn(`Stalled at ${l} of ${l+d} in ${o} ${e} (media.currentTime: ${r})`),l&&(d/i.playbackRate<.5||o.bufferedInPlaceToEnd(i))&&o.hls){let c=t.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,c,n);}}}}advanceInPlace(e){let t=this.primaryMedia;t&&t.currentTime<e&&(t.currentTime=e);}handleAssetItemError(e,t,i,r,n){if(e.details===x.BUFFER_STALLED_ERROR)return;let a=t.assetList[r]||null;if(this.warn(`INTERSTITIAL_ASSET_ERROR ${a&&Js(a)} ${e.error}`),!this.schedule)return;let o=a?.identifier||"",l=this.getAssetPlayerQueueIndex(o),d=this.playerQueue[l]||null,c=this.schedule.items,u=ye({},e,{fatal:false,errorAction:ir(true),asset:a,assetListIndex:r,event:t,schedule:c,scheduleIndex:i,player:d});if(this.hls.trigger(g.INTERSTITIAL_ASSET_ERROR,u),!e.fatal)return;let h=this.playingAsset,f=this.bufferingAsset,m=new Error(n);if(a&&(this.clearAssetPlayer(o,null),a.error=m),!t.assetList.some(p=>!p.error))t.error=m;else for(let p=r;p<t.assetList.length;p++)this.resetAssetPlayer(t.assetList[p].identifier);this.updateSchedule(true),t.error?this.primaryFallback(t):h&&h.identifier===o?this.advanceAfterAssetEnded(t,i,r):f&&f.identifier===o&&this.isInterstitial(this.bufferingItem)&&this.advanceAssetBuffering(this.bufferingItem,f);}primaryFallback(e){let t=e.timelineStart,i=this.effectivePlayingItem;if(i){this.log(`Fallback to primary from event "${e.identifier}" start: ${t} pos: ${this.timelinePos} playing: ${$t(i)} error: ${e.error}`);let r=this.timelinePos;r===-1&&(r=this.hls.startPosition);let n=this.updateItem(i,r);if(this.itemsMatch(i,n)&&this.clearInterstitial(e,null),e.appendInPlace&&(this.attachPrimary(t,null),this.flushFrontBuffer(t)),!this.schedule)return;let a=this.schedule.findItemIndexAtTime(r);this.setSchedulePosition(a);}else this.checkStart();}onAssetListLoaded(e,t){var i,r;let n=t.event,a=n.identifier,o=t.assetListResponse.ASSETS;if(!((i=this.schedule)!=null&&i.hasEvent(a)))return;let l=n.timelineStart,d=n.duration,c=0;o.forEach((p,E)=>{let v=parseFloat(p.DURATION);this.createAsset(n,E,c,l+c,v,p.URI),c+=v;}),n.duration=c,this.log(`Loaded asset-list with duration: ${c} (was: ${d}) ${n}`);let u=this.waitingItem,h=u?.event.identifier===a;this.updateSchedule();let f=(r=this.bufferingItem)==null?void 0:r.event;if(h){var m;let p=this.schedule.findEventIndex(a),E=(m=this.schedule.items)==null?void 0:m[p];if(E){if(!this.playingItem&&this.timelinePos>E.end&&this.schedule.findItemIndexAtTime(this.timelinePos)!==p){n.error=new Error(`Interstitial no longer within playback range ${this.timelinePos} ${n}`),this.updateSchedule(true),this.primaryFallback(n);return}this.setBufferingItem(E);}this.setSchedulePosition(p);}else if(f?.identifier===a){let p=n.assetList[0];if(p){let E=this.getAssetPlayer(p.identifier);if(f.appendInPlace){let v=this.primaryMedia;E&&v&&this.bufferAssetPlayer(E,v);}else E&&E.loadSource();}}}onError(e,t){if(this.schedule)switch(t.details){case x.ASSET_LIST_PARSING_ERROR:case x.ASSET_LIST_LOAD_ERROR:case x.ASSET_LIST_LOAD_TIMEOUT:{let i=t.interstitial;i&&(this.updateSchedule(true),this.primaryFallback(i));break}case x.BUFFER_STALLED_ERROR:{let i=this.endedItem||this.waitingItem||this.playingItem;if(this.isInterstitial(i)&&i.event.appendInPlace){this.handleInPlaceStall(i.event);return}this.log(`Primary player stall @${this.timelinePos} bufferedPos: ${this.bufferedPos}`),this.onTimeupdate(),this.checkBuffer(true);break}}}},fg=500,hu=class extends yn{constructor(e,t,i){super(e,t,i,"subtitle-stream-controller",W.SUBTITLE),this.currentTrackId=-1,this.tracksBuffered=[],this.mainDetails=null,this.registerListeners();}onHandlerDestroying(){this.unregisterListeners(),super.onHandlerDestroying(),this.mainDetails=null;}registerListeners(){super.registerListeners();let{hls:e}=this;e.on(g.LEVEL_LOADED,this.onLevelLoaded,this),e.on(g.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(g.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(g.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(g.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.on(g.BUFFER_FLUSHING,this.onBufferFlushing,this);}unregisterListeners(){super.unregisterListeners();let{hls:e}=this;e.off(g.LEVEL_LOADED,this.onLevelLoaded,this),e.off(g.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(g.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(g.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(g.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.off(g.BUFFER_FLUSHING,this.onBufferFlushing,this);}startLoad(e,t){this.stopLoad(),this.state=C.IDLE,this.setInterval(fg),this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick();}onManifestLoading(){super.onManifestLoading(),this.mainDetails=null;}onMediaDetaching(e,t){this.tracksBuffered=[],super.onMediaDetaching(e,t);}onLevelLoaded(e,t){this.mainDetails=t.details;}onSubtitleFragProcessed(e,t){let{frag:i,success:r}=t;if(this.fragContextChanged(i)||(Ue(i)&&(this.fragPrevious=i),this.state=C.IDLE),!r)return;let n=this.tracksBuffered[this.currentTrackId];if(!n)return;let a,o=i.start;for(let d=0;d<n.length;d++)if(o>=n[d].start&&o<=n[d].end){a=n[d];break}let l=i.start+i.duration;a?a.end=l:(a={start:o,end:l},n.push(a)),this.fragmentTracker.fragBuffered(i),this.fragBufferedComplete(i,null),this.media&&this.tick();}onBufferFlushing(e,t){let{startOffset:i,endOffset:r}=t;if(i===0&&r!==Number.POSITIVE_INFINITY){let n=r-1;if(n<=0)return;t.endOffsetSubtitles=Math.max(0,n),this.tracksBuffered.forEach(a=>{for(let o=0;o<a.length;){if(a[o].end<=n){a.shift();continue}else if(a[o].start<n)a[o].start=n;else break;o++;}}),this.fragmentTracker.removeFragmentsInRange(i,n,W.SUBTITLE);}}onError(e,t){let i=t.frag;i?.type===W.SUBTITLE&&(t.details===x.FRAG_GAP&&this.fragmentTracker.fragBuffered(i,true),this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==C.STOPPED&&(this.state=C.IDLE));}onSubtitleTracksUpdated(e,{subtitleTracks:t}){if(this.levels&&yp(this.levels,t)){this.levels=t.map(i=>new ds(i));return}this.tracksBuffered=[],this.levels=t.map(i=>{let r=new ds(i);return this.tracksBuffered[r.id]=[],r}),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,W.SUBTITLE),this.fragPrevious=null,this.mediaBuffer=null;}onSubtitleTrackSwitch(e,t){var i;if(this.currentTrackId=t.id,!((i=this.levels)!=null&&i.length)||this.currentTrackId===-1){this.clearInterval();return}let r=this.levels[this.currentTrackId];r!=null&&r.details?this.mediaBuffer=this.mediaBufferTimeRanges:this.mediaBuffer=null,r&&this.state!==C.STOPPED&&this.setInterval(fg);}onSubtitleTrackLoaded(e,t){var i;let{currentTrackId:r,levels:n}=this,{details:a,id:o}=t;if(!n){this.warn(`Subtitle tracks were reset while loading level ${o}`);return}let l=n[o];if(o>=n.length||!l)return;this.log(`Subtitle track ${o} loaded [${a.startSN},${a.endSN}]${a.lastPartSn?`[part-${a.lastPartSn}-${a.lastPartIndex}]`:""},duration:${a.totalduration}`),this.mediaBuffer=this.mediaBufferTimeRanges;let d=0;if(a.live||(i=l.details)!=null&&i.live){if(a.deltaUpdateFailed)return;let u=this.mainDetails;if(!u){this.startFragRequested=false;return}let h=u.fragments[0];if(!l.details)a.hasProgramDateTime&&u.hasProgramDateTime?(Zo(a,u),d=a.fragmentStart):h&&(d=h.start,Cc(a,d));else {var c;d=this.alignPlaylists(a,l.details,(c=this.levelLastLoaded)==null?void 0:c.details),d===0&&h&&(d=h.start,Cc(a,d));}u&&!this.startFragRequested&&this.setStartPosition(u,d);}l.details=a,this.levelLastLoaded=l,o===r&&(this.hls.trigger(g.SUBTITLE_TRACK_UPDATED,{details:a,id:o,groupId:t.groupId}),this.tick(),a.live&&!this.fragCurrent&&this.media&&this.state===C.IDLE&&(cs(null,a.fragments,this.media.currentTime,0)||(this.warn("Subtitle playlist not aligned with playback"),l.details=void 0)));}_handleFragmentLoadComplete(e){let{frag:t,payload:i}=e,r=t.decryptdata,n=this.hls;if(!this.fragContextChanged(t)&&i&&i.byteLength>0&&r!=null&&r.key&&r.iv&&sr(r.method)){let a=performance.now();this.decrypter.decrypt(new Uint8Array(i),r.key.buffer,r.iv.buffer,Nu(r.method)).catch(o=>{throw n.trigger(g.ERROR,{type:z.MEDIA_ERROR,details:x.FRAG_DECRYPT_ERROR,fatal:false,error:o,reason:o.message,frag:t}),o}).then(o=>{let l=performance.now();n.trigger(g.FRAG_DECRYPTED,{frag:t,payload:o,stats:{tstart:a,tdecrypt:l}});}).catch(o=>{this.warn(`${o.name}: ${o.message}`),this.state=C.IDLE;});}}doTick(){if(!this.media){this.state=C.IDLE;return}if(this.state===C.IDLE){let{currentTrackId:e,levels:t}=this,i=t?.[e];if(!i||!t.length||!i.details||this.waitForLive(i))return;let{config:r}=this,n=this.getLoadPosition(),a=re.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],n,r.maxBufferHole),{end:o,len:l}=a,d=i.details,c=this.hls.maxBufferLength+d.levelTargetDuration;if(l>c)return;let u=d.fragments,h=u.length,f=d.edge,m=null,p=this.fragPrevious;if(o<f){let T=r.maxFragLookUpTolerance,S=o>f-T?0:T;m=cs(p,u,Math.max(u[0].start,o),S),!m&&p&&p.start<u[0].start&&(m=u[0]);}else m=u[h-1];if(m=this.filterReplacedPrimary(m,i.details),!m)return;let E=m.sn-d.startSN,v=u[E-1];if(v&&v.cc===m.cc&&this.fragmentTracker.getState(v)===Ke.NOT_LOADED&&(m=v),this.fragmentTracker.getState(m)===Ke.NOT_LOADED){let T=this.mapToInitFragWhenRequired(m);T&&this.loadFragment(T,i,o);}}}loadFragment(e,t,i){Ue(e)?super.loadFragment(e,t,i):this._loadInitSegment(e,t);}get mediaBufferTimeRanges(){return new fu(this.tracksBuffered[this.currentTrackId]||[])}},fu=class{constructor(e){this.buffered=void 0;let t=(i,r,n)=>{if(r=r>>>0,r>n-1)throw new DOMException(`Failed to execute '${i}' on 'TimeRanges': The index provided (${r}) is greater than the maximum bound (${n})`);return e[r][i]};this.buffered={get length(){return e.length},end(i){return t("end",i,e.length)},start(i){return t("start",i,e.length)}};}},lA={42:225,92:233,94:237,95:243,96:250,123:231,124:247,125:209,126:241,127:9608,128:174,129:176,130:189,131:191,132:8482,133:162,134:163,135:9834,136:224,137:32,138:232,139:226,140:234,141:238,142:244,143:251,144:193,145:201,146:211,147:218,148:220,149:252,150:8216,151:161,152:42,153:8217,154:9473,155:169,156:8480,157:8226,158:8220,159:8221,160:192,161:194,162:199,163:200,164:202,165:203,166:235,167:206,168:207,169:239,170:212,171:217,172:249,173:219,174:171,175:187,176:195,177:227,178:205,179:204,180:236,181:210,182:242,183:213,184:245,185:123,186:125,187:92,188:94,189:95,190:124,191:8764,192:196,193:228,194:214,195:246,196:223,197:165,198:164,199:9475,200:197,201:229,202:216,203:248,204:9487,205:9491,206:9495,207:9499},Op=s=>String.fromCharCode(lA[s]||s),Gt=15,vi=100,dA={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},cA={17:2,18:4,21:6,22:8,23:10,19:13,20:15},uA={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},hA={25:2,26:4,29:6,30:8,31:10,27:13,28:15},fA=["white","green","blue","cyan","red","yellow","magenta","black","transparent"],mu=class{constructor(){this.time=null,this.verboseLevel=0;}log(e,t){if(this.verboseLevel>=e){let i=typeof t=="function"?t():t;Te.log(`${this.time} [${e}] ${i}`);}}},rs=function(e){let t=[];for(let i=0;i<e.length;i++)t.push(e[i].toString(16));return t},ol=class{constructor(){this.foreground="white",this.underline=false,this.italics=false,this.background="black",this.flash=false;}reset(){this.foreground="white",this.underline=false,this.italics=false,this.background="black",this.flash=false;}setStyles(e){let t=["foreground","underline","italics","background","flash"];for(let i=0;i<t.length;i++){let r=t[i];e.hasOwnProperty(r)&&(this[r]=e[r]);}}isDefault(){return this.foreground==="white"&&!this.underline&&!this.italics&&this.background==="black"&&!this.flash}equals(e){return this.foreground===e.foreground&&this.underline===e.underline&&this.italics===e.italics&&this.background===e.background&&this.flash===e.flash}copy(e){this.foreground=e.foreground,this.underline=e.underline,this.italics=e.italics,this.background=e.background,this.flash=e.flash;}toString(){return "color="+this.foreground+", underline="+this.underline+", italics="+this.italics+", background="+this.background+", flash="+this.flash}},gu=class{constructor(){this.uchar=" ",this.penState=new ol;}reset(){this.uchar=" ",this.penState.reset();}setChar(e,t){this.uchar=e,this.penState.copy(t);}setPenState(e){this.penState.copy(e);}equals(e){return this.uchar===e.uchar&&this.penState.equals(e.penState)}copy(e){this.uchar=e.uchar,this.penState.copy(e.penState);}isEmpty(){return this.uchar===" "&&this.penState.isDefault()}},pu=class{constructor(e){this.chars=[],this.pos=0,this.currPenState=new ol,this.cueStartTime=null,this.logger=void 0;for(let t=0;t<vi;t++)this.chars.push(new gu);this.logger=e;}equals(e){for(let t=0;t<vi;t++)if(!this.chars[t].equals(e.chars[t]))return false;return true}copy(e){for(let t=0;t<vi;t++)this.chars[t].copy(e.chars[t]);}isEmpty(){let e=true;for(let t=0;t<vi;t++)if(!this.chars[t].isEmpty()){e=false;break}return e}setCursor(e){this.pos!==e&&(this.pos=e),this.pos<0?(this.logger.log(3,"Negative cursor position "+this.pos),this.pos=0):this.pos>vi&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=vi);}moveCursor(e){let t=this.pos+e;if(e>1)for(let i=this.pos+1;i<t+1;i++)this.chars[i].setPenState(this.currPenState);this.setCursor(t);}backSpace(){this.moveCursor(-1),this.chars[this.pos].setChar(" ",this.currPenState);}insertChar(e){e>=144&&this.backSpace();let t=Op(e);if(this.pos>=vi){this.logger.log(0,()=>"Cannot insert "+e.toString(16)+" ("+t+") at position "+this.pos+". Skipping it!");return}this.chars[this.pos].setChar(t,this.currPenState),this.moveCursor(1);}clearFromPos(e){let t;for(t=e;t<vi;t++)this.chars[t].reset();}clear(){this.clearFromPos(0),this.pos=0,this.currPenState.reset();}clearToEndOfRow(){this.clearFromPos(this.pos);}getTextString(){let e=[],t=true;for(let i=0;i<vi;i++){let r=this.chars[i].uchar;r!==" "&&(t=false),e.push(r);}return t?"":e.join("")}setPenStyles(e){this.currPenState.setStyles(e),this.chars[this.pos].setPenState(this.currPenState);}},fn=class{constructor(e){this.rows=[],this.currRow=Gt-1,this.nrRollUpRows=null,this.lastOutputScreen=null,this.logger=void 0;for(let t=0;t<Gt;t++)this.rows.push(new pu(e));this.logger=e;}reset(){for(let e=0;e<Gt;e++)this.rows[e].clear();this.currRow=Gt-1;}equals(e){let t=true;for(let i=0;i<Gt;i++)if(!this.rows[i].equals(e.rows[i])){t=false;break}return t}copy(e){for(let t=0;t<Gt;t++)this.rows[t].copy(e.rows[t]);}isEmpty(){let e=true;for(let t=0;t<Gt;t++)if(!this.rows[t].isEmpty()){e=false;break}return e}backSpace(){this.rows[this.currRow].backSpace();}clearToEndOfRow(){this.rows[this.currRow].clearToEndOfRow();}insertChar(e){this.rows[this.currRow].insertChar(e);}setPen(e){this.rows[this.currRow].setPenStyles(e);}moveCursor(e){this.rows[this.currRow].moveCursor(e);}setCursor(e){this.logger.log(2,"setCursor: "+e),this.rows[this.currRow].setCursor(e);}setPAC(e){this.logger.log(2,()=>"pacData = "+Ae(e));let t=e.row-1;if(this.nrRollUpRows&&t<this.nrRollUpRows-1&&(t=this.nrRollUpRows-1),this.nrRollUpRows&&this.currRow!==t){for(let o=0;o<Gt;o++)this.rows[o].clear();let n=this.currRow+1-this.nrRollUpRows,a=this.lastOutputScreen;if(a){let o=a.rows[n].cueStartTime,l=this.logger.time;if(o!==null&&l!==null&&o<l)for(let d=0;d<this.nrRollUpRows;d++)this.rows[t-this.nrRollUpRows+d+1].copy(a.rows[n+d]);}}this.currRow=t;let i=this.rows[this.currRow];if(e.indent!==null){let n=e.indent,a=Math.max(n-1,0);i.setCursor(e.indent),e.color=i.chars[a].penState.foreground;}let r={foreground:e.color,underline:e.underline,italics:e.italics,background:"black",flash:false};this.setPen(r);}setBkgData(e){this.logger.log(2,()=>"bkgData = "+Ae(e)),this.backSpace(),this.setPen(e),this.insertChar(32);}setRollUpRows(e){this.nrRollUpRows=e;}rollUp(){if(this.nrRollUpRows===null){this.logger.log(3,"roll_up but nrRollUpRows not set yet");return}this.logger.log(1,()=>this.getDisplayText());let e=this.currRow+1-this.nrRollUpRows,t=this.rows.splice(e,1)[0];t.clear(),this.rows.splice(this.currRow,0,t),this.logger.log(2,"Rolling up");}getDisplayText(e){e=e||false;let t=[],i="",r=-1;for(let n=0;n<Gt;n++){let a=this.rows[n].getTextString();a&&(r=n+1,e?t.push("Row "+r+": '"+a+"'"):t.push(a.trim()));}return t.length>0&&(e?i="["+t.join(" | ")+"]":i=t.join(`
1378
- `)),i}getTextAndFormat(){return this.rows}},ll=class{constructor(e,t,i){this.chNr=void 0,this.outputFilter=void 0,this.mode=void 0,this.verbose=void 0,this.displayedMemory=void 0,this.nonDisplayedMemory=void 0,this.lastOutputScreen=void 0,this.currRollUpRow=void 0,this.writeScreen=void 0,this.cueStartTime=void 0,this.logger=void 0,this.chNr=e,this.outputFilter=t,this.mode=null,this.verbose=0,this.displayedMemory=new fn(i),this.nonDisplayedMemory=new fn(i),this.lastOutputScreen=new fn(i),this.currRollUpRow=this.displayedMemory.rows[Gt-1],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.logger=i;}reset(){this.mode=null,this.displayedMemory.reset(),this.nonDisplayedMemory.reset(),this.lastOutputScreen.reset(),this.outputFilter.reset(),this.currRollUpRow=this.displayedMemory.rows[Gt-1],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null;}getHandler(){return this.outputFilter}setHandler(e){this.outputFilter=e;}setPAC(e){this.writeScreen.setPAC(e);}setBkgData(e){this.writeScreen.setBkgData(e);}setMode(e){e!==this.mode&&(this.mode=e,this.logger.log(2,()=>"MODE="+e),this.mode==="MODE_POP-ON"?this.writeScreen=this.nonDisplayedMemory:(this.writeScreen=this.displayedMemory,this.writeScreen.reset()),this.mode!=="MODE_ROLL-UP"&&(this.displayedMemory.nrRollUpRows=null,this.nonDisplayedMemory.nrRollUpRows=null),this.mode=e);}insertChars(e){for(let i=0;i<e.length;i++)this.writeScreen.insertChar(e[i]);let t=this.writeScreen===this.displayedMemory?"DISP":"NON_DISP";this.logger.log(2,()=>t+": "+this.writeScreen.getDisplayText(true)),(this.mode==="MODE_PAINT-ON"||this.mode==="MODE_ROLL-UP")&&(this.logger.log(1,()=>"DISPLAYED: "+this.displayedMemory.getDisplayText(true)),this.outputDataUpdate());}ccRCL(){this.logger.log(2,"RCL - Resume Caption Loading"),this.setMode("MODE_POP-ON");}ccBS(){this.logger.log(2,"BS - BackSpace"),this.mode!=="MODE_TEXT"&&(this.writeScreen.backSpace(),this.writeScreen===this.displayedMemory&&this.outputDataUpdate());}ccAOF(){}ccAON(){}ccDER(){this.logger.log(2,"DER- Delete to End of Row"),this.writeScreen.clearToEndOfRow(),this.outputDataUpdate();}ccRU(e){this.logger.log(2,"RU("+e+") - Roll Up"),this.writeScreen=this.displayedMemory,this.setMode("MODE_ROLL-UP"),this.writeScreen.setRollUpRows(e);}ccFON(){this.logger.log(2,"FON - Flash On"),this.writeScreen.setPen({flash:true});}ccRDC(){this.logger.log(2,"RDC - Resume Direct Captioning"),this.setMode("MODE_PAINT-ON");}ccTR(){this.logger.log(2,"TR"),this.setMode("MODE_TEXT");}ccRTD(){this.logger.log(2,"RTD"),this.setMode("MODE_TEXT");}ccEDM(){this.logger.log(2,"EDM - Erase Displayed Memory"),this.displayedMemory.reset(),this.outputDataUpdate(true);}ccCR(){this.logger.log(2,"CR - Carriage Return"),this.writeScreen.rollUp(),this.outputDataUpdate(true);}ccENM(){this.logger.log(2,"ENM - Erase Non-displayed Memory"),this.nonDisplayedMemory.reset();}ccEOC(){if(this.logger.log(2,"EOC - End Of Caption"),this.mode==="MODE_POP-ON"){let e=this.displayedMemory;this.displayedMemory=this.nonDisplayedMemory,this.nonDisplayedMemory=e,this.writeScreen=this.nonDisplayedMemory,this.logger.log(1,()=>"DISP: "+this.displayedMemory.getDisplayText());}this.outputDataUpdate(true);}ccTO(e){this.logger.log(2,"TO("+e+") - Tab Offset"),this.writeScreen.moveCursor(e);}ccMIDROW(e){let t={flash:false};if(t.underline=e%2===1,t.italics=e>=46,t.italics)t.foreground="white";else {let i=Math.floor(e/2)-16,r=["white","green","blue","cyan","red","yellow","magenta"];t.foreground=r[i];}this.logger.log(2,"MIDROW: "+Ae(t)),this.writeScreen.setPen(t);}outputDataUpdate(e=false){let t=this.logger.time;t!==null&&this.outputFilter&&(this.cueStartTime===null&&!this.displayedMemory.isEmpty()?this.cueStartTime=t:this.displayedMemory.equals(this.lastOutputScreen)||(this.outputFilter.newCue(this.cueStartTime,t,this.lastOutputScreen),e&&this.outputFilter.dispatchCue&&this.outputFilter.dispatchCue(),this.cueStartTime=this.displayedMemory.isEmpty()?null:t),this.lastOutputScreen.copy(this.displayedMemory));}cueSplitAtTime(e){this.outputFilter&&(this.displayedMemory.isEmpty()||(this.outputFilter.newCue&&this.outputFilter.newCue(this.cueStartTime,e,this.displayedMemory),this.cueStartTime=e));}},dl=class{constructor(e,t,i){this.channels=void 0,this.currentChannel=0,this.cmdHistory=gA(),this.logger=void 0;let r=this.logger=new mu;this.channels=[null,new ll(e,t,r),new ll(e+1,i,r)];}getHandler(e){return this.channels[e].getHandler()}setHandler(e,t){this.channels[e].setHandler(t);}addData(e,t){this.logger.time=e;for(let i=0;i<t.length;i+=2){let r=t[i]&127,n=t[i+1]&127,a=false,o=null;if(r===0&&n===0)continue;this.logger.log(3,()=>"["+rs([t[i],t[i+1]])+"] -> ("+rs([r,n])+")");let l=this.cmdHistory;if(r>=16&&r<=31){if(mA(r,n,l)){ko(null,null,l),this.logger.log(3,()=>"Repeated command ("+rs([r,n])+") is dropped");continue}ko(r,n,this.cmdHistory),a=this.parseCmd(r,n),a||(a=this.parseMidrow(r,n)),a||(a=this.parsePAC(r,n)),a||(a=this.parseBackgroundAttributes(r,n));}else ko(null,null,l);if(!a&&(o=this.parseChars(r,n),o)){let c=this.currentChannel;c&&c>0?this.channels[c].insertChars(o):this.logger.log(2,"No channel found yet. TEXT-MODE?");}!a&&!o&&this.logger.log(2,()=>"Couldn't parse cleaned data "+rs([r,n])+" orig: "+rs([t[i],t[i+1]]));}}parseCmd(e,t){let i=(e===20||e===28||e===21||e===29)&&t>=32&&t<=47,r=(e===23||e===31)&&t>=33&&t<=35;if(!(i||r))return false;let n=e===20||e===21||e===23?1:2,a=this.channels[n];return e===20||e===21||e===28||e===29?t===32?a.ccRCL():t===33?a.ccBS():t===34?a.ccAOF():t===35?a.ccAON():t===36?a.ccDER():t===37?a.ccRU(2):t===38?a.ccRU(3):t===39?a.ccRU(4):t===40?a.ccFON():t===41?a.ccRDC():t===42?a.ccTR():t===43?a.ccRTD():t===44?a.ccEDM():t===45?a.ccCR():t===46?a.ccENM():t===47&&a.ccEOC():a.ccTO(t-32),this.currentChannel=n,true}parseMidrow(e,t){let i=0;if((e===17||e===25)&&t>=32&&t<=47){if(e===17?i=1:i=2,i!==this.currentChannel)return this.logger.log(0,"Mismatch channel in midrow parsing"),false;let r=this.channels[i];return r?(r.ccMIDROW(t),this.logger.log(3,()=>"MIDROW ("+rs([e,t])+")"),true):false}return false}parsePAC(e,t){let i,r=(e>=17&&e<=23||e>=25&&e<=31)&&t>=64&&t<=127,n=(e===16||e===24)&&t>=64&&t<=95;if(!(r||n))return false;let a=e<=23?1:2;t>=64&&t<=95?i=a===1?dA[e]:uA[e]:i=a===1?cA[e]:hA[e];let o=this.channels[a];return o?(o.setPAC(this.interpretPAC(i,t)),this.currentChannel=a,true):false}interpretPAC(e,t){let i,r={color:null,italics:false,indent:null,underline:false,row:e};return t>95?i=t-96:i=t-64,r.underline=(i&1)===1,i<=13?r.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(i/2)]:i<=15?(r.italics=true,r.color="white"):r.indent=Math.floor((i-16)/2)*4,r}parseChars(e,t){let i,r=null,n=null;if(e>=25?(i=2,n=e-8):(i=1,n=e),n>=17&&n<=19){let a;n===17?a=t+80:n===18?a=t+112:a=t+144,this.logger.log(2,()=>"Special char '"+Op(a)+"' in channel "+i),r=[a];}else e>=32&&e<=127&&(r=t===0?[e]:[e,t]);return r&&this.logger.log(3,()=>"Char codes = "+rs(r).join(",")),r}parseBackgroundAttributes(e,t){let i=(e===16||e===24)&&t>=32&&t<=47,r=(e===23||e===31)&&t>=45&&t<=47;if(!(i||r))return false;let n,a={};e===16||e===24?(n=Math.floor((t-32)/2),a.background=fA[n],t%2===1&&(a.background=a.background+"_semi")):t===45?a.background="transparent":(a.foreground="black",t===47&&(a.underline=true));let o=e<=23?1:2;return this.channels[o].setBkgData(a),true}reset(){for(let e=0;e<Object.keys(this.channels).length;e++){let t=this.channels[e];t&&t.reset();}ko(null,null,this.cmdHistory);}cueSplitAtTime(e){for(let t=0;t<this.channels.length;t++){let i=this.channels[t];i&&i.cueSplitAtTime(e);}}};function ko(s,e,t){t.a=s,t.b=e;}function mA(s,e,t){return t.a===s&&t.b===e}function gA(){return {a:null,b:null}}var qu=function(){if(Xo!=null&&Xo.VTTCue)return self.VTTCue;let s=["","lr","rl"],e=["start","middle","end","left","right"];function t(o,l){if(typeof l!="string"||!Array.isArray(o))return false;let d=l.toLowerCase();return ~o.indexOf(d)?d:false}function i(o){return t(s,o)}function r(o){return t(e,o)}function n(o,...l){let d=1;for(;d<arguments.length;d++){let c=arguments[d];for(let u in c)o[u]=c[u];}return o}function a(o,l,d){let c=this,u={enumerable:true};c.hasBeenReset=false;let h="",f=false,m=o,p=l,E=d,v=null,T="",S=true,A="auto",b="start",D=50,I="middle",k=50,R="middle";Object.defineProperty(c,"id",n({},u,{get:function(){return h},set:function(L){h=""+L;}})),Object.defineProperty(c,"pauseOnExit",n({},u,{get:function(){return f},set:function(L){f=!!L;}})),Object.defineProperty(c,"startTime",n({},u,{get:function(){return m},set:function(L){if(typeof L!="number")throw new TypeError("Start time must be set to a number.");m=L,this.hasBeenReset=true;}})),Object.defineProperty(c,"endTime",n({},u,{get:function(){return p},set:function(L){if(typeof L!="number")throw new TypeError("End time must be set to a number.");p=L,this.hasBeenReset=true;}})),Object.defineProperty(c,"text",n({},u,{get:function(){return E},set:function(L){E=""+L,this.hasBeenReset=true;}})),Object.defineProperty(c,"region",n({},u,{get:function(){return v},set:function(L){v=L,this.hasBeenReset=true;}})),Object.defineProperty(c,"vertical",n({},u,{get:function(){return T},set:function(L){let M=i(L);if(M===false)throw new SyntaxError("An invalid or illegal string was specified.");T=M,this.hasBeenReset=true;}})),Object.defineProperty(c,"snapToLines",n({},u,{get:function(){return S},set:function(L){S=!!L,this.hasBeenReset=true;}})),Object.defineProperty(c,"line",n({},u,{get:function(){return A},set:function(L){if(typeof L!="number"&&L!=="auto")throw new SyntaxError("An invalid number or illegal string was specified.");A=L,this.hasBeenReset=true;}})),Object.defineProperty(c,"lineAlign",n({},u,{get:function(){return b},set:function(L){let M=r(L);if(!M)throw new SyntaxError("An invalid or illegal string was specified.");b=M,this.hasBeenReset=true;}})),Object.defineProperty(c,"position",n({},u,{get:function(){return D},set:function(L){if(L<0||L>100)throw new Error("Position must be between 0 and 100.");D=L,this.hasBeenReset=true;}})),Object.defineProperty(c,"positionAlign",n({},u,{get:function(){return I},set:function(L){let M=r(L);if(!M)throw new SyntaxError("An invalid or illegal string was specified.");I=M,this.hasBeenReset=true;}})),Object.defineProperty(c,"size",n({},u,{get:function(){return k},set:function(L){if(L<0||L>100)throw new Error("Size must be between 0 and 100.");k=L,this.hasBeenReset=true;}})),Object.defineProperty(c,"align",n({},u,{get:function(){return R},set:function(L){let M=r(L);if(!M)throw new SyntaxError("An invalid or illegal string was specified.");R=M,this.hasBeenReset=true;}})),c.displayState=void 0;}return a.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},a}(),Eu=class{decode(e,t){if(!e)return "";if(typeof e!="string")throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(e))}};function Fp(s){function e(i,r,n,a){return (i|0)*3600+(r|0)*60+(n|0)+parseFloat(a||0)}let t=s.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);return t?parseFloat(t[2])>59?e(t[2],t[3],0,t[4]):e(t[1],t[2],t[3],t[4]):null}var vu=class{constructor(){this.values=Object.create(null);}set(e,t){!this.get(e)&&t!==""&&(this.values[e]=t);}get(e,t,i){return i?this.has(e)?this.values[e]:t[i]:this.has(e)?this.values[e]:t}has(e){return e in this.values}alt(e,t,i){for(let r=0;r<i.length;++r)if(t===i[r]){this.set(e,t);break}}integer(e,t){/^-?\d+$/.test(t)&&this.set(e,parseInt(t,10));}percent(e,t){if(/^([\d]{1,3})(\.[\d]*)?%$/.test(t)){let i=parseFloat(t);if(i>=0&&i<=100)return this.set(e,i),true}return false}};function Np(s,e,t,i){let r=i?s.split(i):[s];for(let n in r){if(typeof r[n]!="string")continue;let a=r[n].split(t);if(a.length!==2)continue;let o=a[0],l=a[1];e(o,l);}}var Tu=new qu(0,0,""),Do=Tu.align==="middle"?"middle":"center";function pA(s,e,t){let i=s;function r(){let o=Fp(s);if(o===null)throw new Error("Malformed timestamp: "+i);return s=s.replace(/^[^\sa-zA-Z-]+/,""),o}function n(o,l){let d=new vu;Np(o,function(h,f){let m;switch(h){case "region":for(let p=t.length-1;p>=0;p--)if(t[p].id===f){d.set(h,t[p].region);break}break;case "vertical":d.alt(h,f,["rl","lr"]);break;case "line":m=f.split(","),d.integer(h,m[0]),d.percent(h,m[0])&&d.set("snapToLines",false),d.alt(h,m[0],["auto"]),m.length===2&&d.alt("lineAlign",m[1],["start",Do,"end"]);break;case "position":m=f.split(","),d.percent(h,m[0]),m.length===2&&d.alt("positionAlign",m[1],["start",Do,"end","line-left","line-right","auto"]);break;case "size":d.percent(h,f);break;case "align":d.alt(h,f,["start",Do,"end","left","right"]);break}},/:/,/\s/),l.region=d.get("region",null),l.vertical=d.get("vertical","");let c=d.get("line","auto");c==="auto"&&Tu.line===-1&&(c=-1),l.line=c,l.lineAlign=d.get("lineAlign","start"),l.snapToLines=d.get("snapToLines",true),l.size=d.get("size",100),l.align=d.get("align",Do);let u=d.get("position","auto");u==="auto"&&Tu.position===50&&(u=l.align==="start"||l.align==="left"?0:l.align==="end"||l.align==="right"?100:50),l.position=u;}function a(){s=s.replace(/^\s+/,"");}if(a(),e.startTime=r(),a(),s.slice(0,3)!=="-->")throw new Error("Malformed time stamp (time stamps must be separated by '-->'): "+i);s=s.slice(3),a(),e.endTime=r(),a(),n(s,e);}function Up(s){return s.replace(/<br(?: \/)?>/gi,`
1379
- `)}var yu=class{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new Eu,this.regionList=[],this.cue=null,this.oncue=void 0,this.onparsingerror=void 0,this.onflush=void 0;}parse(e){let t=this;e&&(t.buffer+=t.decoder.decode(e,{stream:true}));function i(){let n=t.buffer,a=0;for(n=Up(n);a<n.length&&n[a]!=="\r"&&n[a]!==`
1375
+ transfer tracks: ${Ae(r,(l,d)=>l==="initSegment"?void 0:d)}}`),!_g(r,i)){t.mediaSource=null,t.tracks=void 0;let l=e.currentTime,d=this.details,c=Math.max(l,d?.fragments[0].start||0);if(c-l>1){this.log(`attachTransferred: waiting for playback to reach new tracks start time ${l} -> ${c}`);return}this.warn(`attachTransferred: resetting MediaSource for incompatible tracks ("${Object.keys(r)}"->"${Object.keys(i)}") start time: ${c} currentTime: ${l}`),this.onMediaDetaching(g.MEDIA_DETACHING,{}),this.onMediaAttaching(g.MEDIA_ATTACHING,t),e.currentTime=c;return}this.transferData=void 0,n.forEach(l=>{let d=l,c=r[d];if(c){let u=c.buffer;if(u){let h=this.fragmentTracker,f=c.id;if(h.hasFragments(f)||h.hasParts(f)){let E=re.getBuffered(u);h.detectEvictedFragments(d,E,f,null,true);}let m=ic(d),p=[d,u];this.sourceBuffers[m]=p,u.updating&&this.operationQueue&&this.operationQueue.prependBlocker(d),this.trackSourceBuffer(d,c);}}}),o(),this.bufferCreated();}else this.log("attachTransferred: MediaSource w/o SourceBuffers"),o();}get mediaSourceOpenOrEnded(){var e;let t=(e=this.mediaSource)==null?void 0:e.readyState;return t==="open"||t==="ended"}onMediaDetaching(e,t){let i=!!t.transferMedia;this.transferData=this.overrides=void 0;let{media:r,mediaSource:n,_objectUrl:a}=this;if(n){if(this.log(`media source ${i?"transferring":"detaching"}`),i)this.sourceBuffers.forEach(([o])=>{o&&this.removeBuffer(o);}),this.resetQueue();else {if(this.mediaSourceOpenOrEnded){let o=n.readyState==="open";try{let l=n.sourceBuffers;for(let d=l.length;d--;)o&&l[d].abort(),n.removeSourceBuffer(l[d]);o&&n.endOfStream();}catch(l){this.warn(`onMediaDetaching: ${l.message} while calling endOfStream`);}}this.sourceBufferCount&&this.onBufferReset();}n.removeEventListener("sourceopen",this._onMediaSourceOpen),n.removeEventListener("sourceended",this._onMediaSourceEnded),n.removeEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(n.removeEventListener("startstreaming",this._onStartStreaming),n.removeEventListener("endstreaming",this._onEndStreaming)),this.mediaSource=null,this._objectUrl=null;}r&&(r.removeEventListener("emptied",this._onMediaEmptied),i||(a&&self.URL.revokeObjectURL(a),this.mediaSrc===a?(r.removeAttribute("src"),this.appendSource&&ag(r),r.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.media=null),this.hls.trigger(g.MEDIA_DETACHED,t);}onBufferReset(){this.sourceBuffers.forEach(([e])=>{e&&this.resetBuffer(e);}),this.initTracks();}resetBuffer(e){var t;let i=(t=this.tracks[e])==null?void 0:t.buffer;if(this.removeBuffer(e),i)try{var r;(r=this.mediaSource)!=null&&r.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(i);}catch(n){this.warn(`onBufferReset ${e}`,n);}delete this.tracks[e];}removeBuffer(e){this.removeBufferListeners(e),this.sourceBuffers[ic(e)]=[null,null];let t=this.tracks[e];t&&(t.buffer=void 0);}resetQueue(){this.operationQueue&&this.operationQueue.destroy(),this.operationQueue=new zc(this.tracks);}onBufferCodecs(e,t){var i;let r=this.tracks,n=Object.keys(t);this.log(`BUFFER_CODECS: "${n}" (current SB count ${this.sourceBufferCount})`);let a="audiovideo"in t&&(r.audio||r.video)||r.audiovideo&&("audio"in t||"video"in t),o=!a&&this.sourceBufferCount&&this.media&&n.some(l=>!r[l]);if(a||o){this.warn(`Unsupported transition between "${Object.keys(r)}" and "${n}" SourceBuffers`);return}n.forEach(l=>{var d,c;let u=t[l],{id:h,codec:f,levelCodec:m,container:p,metadata:E,supplemental:v}=u,T=r[l],S=(d=this.transferData)==null||(d=d.tracks)==null?void 0:d[l],A=S!=null&&S.buffer?S:T,b=A?.pendingCodec||A?.codec,D=A?.levelCodec;T||(T=r[l]={buffer:void 0,listeners:[],codec:f,supplemental:v,container:p,levelCodec:m,metadata:E,id:h});let I=Po(b,D),k=I?.replace(ng,"$1"),R=Po(f,m),L=(c=R)==null?void 0:c.replace(ng,"$1");R&&I&&k!==L&&(l.slice(0,5)==="audio"&&(R=Ho(R,this.appendSource)),this.log(`switching codec ${b} to ${R}`),R!==(T.pendingCodec||T.codec)&&(T.pendingCodec=R),T.container=p,this.appendChangeType(l,p,R));}),(this.tracksReady||this.sourceBufferCount)&&(t.tracks=this.sourceBufferTracks),!this.sourceBufferCount&&(this.bufferCodecEventsTotal>1&&!this.tracks.video&&!t.video&&((i=t.audio)==null?void 0:i.id)==="main"&&(this.log("Main audio-only"),this.bufferCodecEventsTotal=1),this.mediaSourceOpenOrEnded&&this.checkPendingTracks());}get sourceBufferTracks(){return Object.keys(this.tracks).reduce((e,t)=>{let i=this.tracks[t];return e[t]={id:i.id,container:i.container,codec:i.codec,levelCodec:i.levelCodec},e},{})}appendChangeType(e,t,i){let r=`${t};codecs=${i}`,n={label:`change-type=${r}`,execute:()=>{let a=this.tracks[e];if(a){let o=a.buffer;o!=null&&o.changeType&&(this.log(`changing ${e} sourceBuffer type to ${r}`),o.changeType(r),a.codec=i,a.container=t);}this.shiftAndExecuteNext(e);},onStart:()=>{},onComplete:()=>{},onError:a=>{this.warn(`Failed to change ${e} SourceBuffer type`,a);}};this.append(n,e,this.isPending(this.tracks[e]));}blockAudio(e){var t;let i=e.start,r=i+e.duration*.05;if(((t=this.fragmentTracker.getAppendedFrag(i,W.MAIN))==null?void 0:t.gap)===true)return;let a={label:"block-audio",execute:()=>{var o;let l=this.tracks.video;(this.lastVideoAppendEnd>r||l!=null&&l.buffer&&re.isBuffered(l.buffer,r)||((o=this.fragmentTracker.getAppendedFrag(r,W.MAIN))==null?void 0:o.gap)===true)&&(this.blockedAudioAppend=null,this.shiftAndExecuteNext("audio"));},onStart:()=>{},onComplete:()=>{},onError:o=>{this.warn("Error executing block-audio operation",o);}};this.blockedAudioAppend={op:a,frag:e},this.append(a,"audio",true);}unblockAudio(){let{blockedAudioAppend:e,operationQueue:t}=this;e&&t&&(this.blockedAudioAppend=null,t.unblockAudio(e.op));}onBufferAppending(e,t){let{tracks:i}=this,{data:r,type:n,parent:a,frag:o,part:l,chunkMeta:d,offset:c}=t,u=d.buffering[n],{sn:h,cc:f}=o,m=self.performance.now();u.start=m;let p=o.stats.buffering,E=l?l.stats.buffering:null;p.start===0&&(p.start=m),E&&E.start===0&&(E.start=m);let v=i.audio,T=false;n==="audio"&&v?.container==="audio/mpeg"&&(T=!this.lastMpegAudioChunk||d.id===1||this.lastMpegAudioChunk.sn!==d.sn,this.lastMpegAudioChunk=d);let S=i.video,A=S?.buffer;if(A&&h!=="initSegment"){let I=l||o,k=this.blockedAudioAppend;if(n==="audio"&&a!=="main"&&!this.blockedAudioAppend&&!(S.ending||S.ended)){let L=I.start+I.duration*.05,M=A.buffered,B=this.currentOp("video");!M.length&&!B?this.blockAudio(I):!B&&!re.isBuffered(A,L)&&this.lastVideoAppendEnd<L&&this.blockAudio(I);}else if(n==="video"){let R=I.end;if(k){let L=k.frag.start;(R>L||R<this.lastVideoAppendEnd||re.isBuffered(A,L))&&this.unblockAudio();}this.lastVideoAppendEnd=R;}}let b=(l||o).start,D={label:`append-${n}`,execute:()=>{var I;u.executeStart=self.performance.now();let k=(I=this.tracks[n])==null?void 0:I.buffer;k&&(T?this.updateTimestampOffset(k,b,.1,n,h,f):c!==void 0&&G(c)&&this.updateTimestampOffset(k,c,1e-6,n,h,f)),this.appendExecutor(r,n);},onStart:()=>{},onComplete:()=>{let I=self.performance.now();u.executeEnd=u.end=I,p.first===0&&(p.first=I),E&&E.first===0&&(E.first=I);let k={};this.sourceBuffers.forEach(([R,L])=>{R&&(k[R]=re.getBuffered(L));}),this.appendErrors[n]=0,n==="audio"||n==="video"?this.appendErrors.audiovideo=0:(this.appendErrors.audio=0,this.appendErrors.video=0),this.hls.trigger(g.BUFFER_APPENDED,{type:n,frag:o,part:l,chunkMeta:d,parent:o.type,timeRanges:k});},onError:I=>{var k;let R={type:z.MEDIA_ERROR,parent:o.type,details:x.BUFFER_APPEND_ERROR,sourceBufferName:n,frag:o,part:l,chunkMeta:d,error:I,err:I,fatal:false},L=(k=this.media)==null?void 0:k.error;if(I.code===DOMException.QUOTA_EXCEEDED_ERR||I.name=="QuotaExceededError"||"quota"in I)R.details=x.BUFFER_FULL_ERROR;else if(I.code===DOMException.INVALID_STATE_ERR&&this.mediaSourceOpenOrEnded&&!L)R.errorAction=ir(true);else if(I.name===Ap&&this.sourceBufferCount===0)R.errorAction=ir(true);else {let M=++this.appendErrors[n];this.warn(`Failed ${M}/${this.hls.config.appendErrorMaxRetry} times to append segment in "${n}" sourceBuffer (${L||"no media error"})`),(M>=this.hls.config.appendErrorMaxRetry||L)&&(R.fatal=true);}this.hls.trigger(g.ERROR,R);}};this.log(`queuing "${n}" append sn: ${h}${l?" p: "+l.index:""} of ${o.type===W.MAIN?"level":"track"} ${o.level} cc: ${f}`),this.append(D,n,this.isPending(this.tracks[n]));}getFlushOp(e,t,i){return this.log(`queuing "${e}" remove ${t}-${i}`),{label:"remove",execute:()=>{this.removeExecutor(e,t,i);},onStart:()=>{},onComplete:()=>{this.hls.trigger(g.BUFFER_FLUSHED,{type:e});},onError:r=>{this.warn(`Failed to remove ${t}-${i} from "${e}" SourceBuffer`,r);}}}onBufferFlushing(e,t){let{type:i,startOffset:r,endOffset:n}=t;i?this.append(this.getFlushOp(i,r,n),i):this.sourceBuffers.forEach(([a])=>{a&&this.append(this.getFlushOp(a,r,n),a);});}onFragParsed(e,t){let{frag:i,part:r}=t,n=[],a=r?r.elementaryStreams:i.elementaryStreams;a[Se.AUDIOVIDEO]?n.push("audiovideo"):(a[Se.AUDIO]&&n.push("audio"),a[Se.VIDEO]&&n.push("video"));let o=()=>{let l=self.performance.now();i.stats.buffering.end=l,r&&(r.stats.buffering.end=l);let d=r?r.stats:i.stats;this.hls.trigger(g.FRAG_BUFFERED,{frag:i,part:r,stats:d,id:i.type});};n.length===0&&this.warn(`Fragments must have at least one ElementaryStreamType set. type: ${i.type} level: ${i.level} sn: ${i.sn}`),this.blockBuffers(o,n).catch(l=>{this.warn(`Fragment buffered callback ${l}`),this.stepOperationQueue(this.sourceBufferTypes);});}onFragChanged(e,t){this.trimBuffers();}get bufferedToEnd(){return this.sourceBufferCount>0&&!this.sourceBuffers.some(([e])=>{if(e){let t=this.tracks[e];if(t)return !t.ended||t.ending}return false})}onBufferEos(e,t){var i;this.sourceBuffers.forEach(([a])=>{if(a){let o=this.tracks[a];(!t.type||t.type===a)&&(o.ending=true,o.ended||(o.ended=true,this.log(`${a} buffer reached EOS`)));}});let r=((i=this.overrides)==null?void 0:i.endOfStream)!==false;this.sourceBufferCount>0&&!this.sourceBuffers.some(([a])=>{var o;return a&&!((o=this.tracks[a])!=null&&o.ended)})?r?(this.log("Queueing EOS"),this.blockUntilOpen(()=>{this.tracksEnded();let{mediaSource:a}=this;if(!a||a.readyState!=="open"){a&&this.log(`Could not call mediaSource.endOfStream(). mediaSource.readyState: ${a.readyState}`);return}this.log("Calling mediaSource.endOfStream()"),a.endOfStream(),this.hls.trigger(g.BUFFERED_TO_END,void 0);})):(this.tracksEnded(),this.hls.trigger(g.BUFFERED_TO_END,void 0)):t.type==="video"&&this.unblockAudio();}tracksEnded(){this.sourceBuffers.forEach(([e])=>{if(e!==null){let t=this.tracks[e];t&&(t.ending=false);}});}onLevelUpdated(e,{details:t}){t.fragments.length&&(this.details=t,this.updateDuration());}updateDuration(){this.blockUntilOpen(()=>{let e=this.getDurationAndRange();e&&this.updateMediaSource(e);});}onError(e,t){if(t.details===x.BUFFER_APPEND_ERROR&&t.frag){var i;let r=(i=t.errorAction)==null?void 0:i.nextAutoLevel;G(r)&&r!==t.frag.level&&this.resetAppendErrors();}}resetAppendErrors(){this.appendErrors={audio:0,video:0,audiovideo:0};}trimBuffers(){let{hls:e,details:t,media:i}=this;if(!i||t===null||!this.sourceBufferCount)return;let r=e.config,n=i.currentTime,a=t.levelTargetDuration,o=t.live&&r.liveBackBufferLength!==null?r.liveBackBufferLength:r.backBufferLength;if(G(o)&&o>=0){let d=Math.max(o,a),c=Math.floor(n/a)*a-d;this.flushBackBuffer(n,a,c);}let l=r.frontBufferFlushThreshold;if(G(l)&&l>0){let d=Math.max(r.maxBufferLength,l),c=Math.max(d,a),u=Math.floor(n/a)*a+c;this.flushFrontBuffer(n,a,u);}}flushBackBuffer(e,t,i){this.sourceBuffers.forEach(([r,n])=>{if(n){let o=re.getBuffered(n);if(o.length>0&&i>o.start(0)){var a;this.hls.trigger(g.BACK_BUFFER_REACHED,{bufferEnd:i});let l=this.tracks[r];if((a=this.details)!=null&&a.live)this.hls.trigger(g.LIVE_BACK_BUFFER_REACHED,{bufferEnd:i});else if(l!=null&&l.ended){this.log(`Cannot flush ${r} back buffer while SourceBuffer is in ended state`);return}this.hls.trigger(g.BUFFER_FLUSHING,{startOffset:0,endOffset:i,type:r});}}});}flushFrontBuffer(e,t,i){this.sourceBuffers.forEach(([r,n])=>{if(n){let a=re.getBuffered(n),o=a.length;if(o<2)return;let l=a.start(o-1),d=a.end(o-1);if(i>l||e>=l&&e<=d)return;this.hls.trigger(g.BUFFER_FLUSHING,{startOffset:l,endOffset:1/0,type:r});}});}getDurationAndRange(){var e;let{details:t,mediaSource:i}=this;if(!t||!this.media||i?.readyState!=="open")return null;let r=t.edge;if(t.live&&this.hls.config.liveDurationInfinity){if(t.fragments.length&&i.setLiveSeekableRange){let d=Math.max(0,t.fragmentStart),c=Math.max(d,r);return {duration:1/0,start:d,end:c}}return {duration:1/0}}let n=(e=this.overrides)==null?void 0:e.duration;if(n)return G(n)?{duration:n}:null;let a=this.media.duration,o=G(i.duration)?i.duration:0;return r>o&&r>a||!G(a)?{duration:r}:null}updateMediaSource({duration:e,start:t,end:i}){let r=this.mediaSource;!this.media||!r||r.readyState!=="open"||(r.duration!==e&&(G(e)&&this.log(`Updating MediaSource duration to ${e.toFixed(3)}`),r.duration=e),t!==void 0&&i!==void 0&&(this.log(`MediaSource duration is set to ${r.duration}. Setting seekable range to ${t}-${i}.`),r.setLiveSeekableRange(t,i)));}get tracksReady(){let e=this.pendingTrackCount;return e>0&&(e>=this.bufferCodecEventsTotal||this.isPending(this.tracks.audiovideo))}checkPendingTracks(){let{bufferCodecEventsTotal:e,pendingTrackCount:t,tracks:i}=this;if(this.log(`checkPendingTracks (pending: ${t} codec events expected: ${e}) ${Ae(i)}`),this.tracksReady){var r;let n=(r=this.transferData)==null?void 0:r.tracks;n&&Object.keys(n).length?this.attachTransferred():this.createSourceBuffers();}}bufferCreated(){if(this.sourceBufferCount){let e={};this.sourceBuffers.forEach(([t,i])=>{if(t){let r=this.tracks[t];e[t]={buffer:i,container:r.container,codec:r.codec,supplemental:r.supplemental,levelCodec:r.levelCodec,id:r.id,metadata:r.metadata};}}),this.hls.trigger(g.BUFFER_CREATED,{tracks:e}),this.log(`SourceBuffers created. Running queue: ${this.operationQueue}`),this.sourceBuffers.forEach(([t])=>{this.executeNext(t);});}else {let e=new Error("could not create source buffer for media codec(s)");this.hls.trigger(g.ERROR,{type:z.MEDIA_ERROR,details:x.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:true,error:e,reason:e.message});}}createSourceBuffers(){let{tracks:e,sourceBuffers:t,mediaSource:i}=this;if(!i)throw new Error("createSourceBuffers called when mediaSource was null");for(let n in e){let a=n,o=e[a];if(this.isPending(o)){let l=this.getTrackCodec(o,a),d=`${o.container};codecs=${l}`;o.codec=l,this.log(`creating sourceBuffer(${d})${this.currentOp(a)?" Queued":""} ${Ae(o)}`);try{let c=i.addSourceBuffer(d),u=ic(a),h=[a,c];t[u]=h,o.buffer=c;}catch(c){var r;this.error(`error while trying to add sourceBuffer: ${c.message}`),this.shiftAndExecuteNext(a),(r=this.operationQueue)==null||r.removeBlockers(),delete this.tracks[a],this.hls.trigger(g.ERROR,{type:z.MEDIA_ERROR,details:x.BUFFER_ADD_CODEC_ERROR,fatal:false,error:c,sourceBufferName:a,mimeType:d,parent:o.id});return}this.trackSourceBuffer(a,o);}}this.bufferCreated();}getTrackCodec(e,t){let i=e.supplemental,r=e.codec;i&&(t==="video"||t==="audiovideo")&&gn(i,"video")&&(r=TT(r,i));let n=Po(r,e.levelCodec);return n?t.slice(0,5)==="audio"?Ho(n,this.appendSource):n:""}trackSourceBuffer(e,t){let i=t.buffer;if(!i)return;let r=this.getTrackCodec(t,e);this.tracks[e]={buffer:i,codec:r,container:t.container,levelCodec:t.levelCodec,supplemental:t.supplemental,metadata:t.metadata,id:t.id,listeners:[]},this.removeBufferListeners(e),this.addBufferListener(e,"updatestart",this.onSBUpdateStart),this.addBufferListener(e,"updateend",this.onSBUpdateEnd),this.addBufferListener(e,"error",this.onSBUpdateError),this.appendSource&&this.addBufferListener(e,"bufferedchange",(n,a)=>{let o=a.removedRanges;o!=null&&o.length&&this.hls.trigger(g.BUFFER_FLUSHED,{type:n});});}get mediaSrc(){var e,t;let i=((e=this.media)==null||(t=e.querySelector)==null?void 0:t.call(e,"source"))||this.media;return i?.src}onSBUpdateStart(e){let t=this.currentOp(e);t&&t.onStart();}onSBUpdateEnd(e){var t;if(((t=this.mediaSource)==null?void 0:t.readyState)==="closed"){this.resetBuffer(e);return}let i=this.currentOp(e);i&&(i.onComplete(),this.shiftAndExecuteNext(e));}onSBUpdateError(e,t){var i;let r=new Error(`${e} SourceBuffer error. MediaSource readyState: ${(i=this.mediaSource)==null?void 0:i.readyState}`);this.error(`${r}`,t),this.hls.trigger(g.ERROR,{type:z.MEDIA_ERROR,details:x.BUFFER_APPENDING_ERROR,sourceBufferName:e,error:r,fatal:false});let n=this.currentOp(e);n&&n.onError(r);}updateTimestampOffset(e,t,i,r,n,a){let o=t-e.timestampOffset;Math.abs(o)>=i&&(this.log(`Updating ${r} SourceBuffer timestampOffset to ${t} (sn: ${n} cc: ${a})`),e.timestampOffset=t);}removeExecutor(e,t,i){let{media:r,mediaSource:n}=this,a=this.tracks[e],o=a?.buffer;if(!r||!n||!o){this.warn(`Attempting to remove from the ${e} SourceBuffer, but it does not exist`),this.shiftAndExecuteNext(e);return}let l=G(r.duration)?r.duration:1/0,d=G(n.duration)?n.duration:1/0,c=Math.max(0,t),u=Math.min(i,l,d);u>c&&(!a.ending||a.ended)?(a.ended=false,this.log(`Removing [${c},${u}] from the ${e} SourceBuffer`),o.remove(c,u)):this.shiftAndExecuteNext(e);}appendExecutor(e,t){let i=this.tracks[t],r=i?.buffer;if(!r)throw new Qc(`Attempting to append to the ${t} SourceBuffer, but it does not exist`);i.ending=false,i.ended=false,r.appendBuffer(e);}blockUntilOpen(e){if(this.isUpdating()||this.isQueued())this.blockBuffers(e).catch(t=>{this.warn(`SourceBuffer blocked callback ${t}`),this.stepOperationQueue(this.sourceBufferTypes);});else try{e();}catch(t){this.warn(`Callback run without blocking ${this.operationQueue} ${t}`);}}isUpdating(){return this.sourceBuffers.some(([e,t])=>e&&t.updating)}isQueued(){return this.sourceBuffers.some(([e])=>e&&!!this.currentOp(e))}isPending(e){return !!e&&!e.buffer}blockBuffers(e,t=this.sourceBufferTypes){if(!t.length)return this.log("Blocking operation requested, but no SourceBuffers exist"),Promise.resolve().then(e);let{operationQueue:i}=this,r=t.map(a=>this.appendBlocker(a));return t.length>1&&!!this.blockedAudioAppend&&this.unblockAudio(),Promise.all(r).then(a=>{i===this.operationQueue&&(e(),this.stepOperationQueue(this.sourceBufferTypes));})}stepOperationQueue(e){e.forEach(t=>{var i;let r=(i=this.tracks[t])==null?void 0:i.buffer;!r||r.updating||this.shiftAndExecuteNext(t);});}append(e,t,i){this.operationQueue&&this.operationQueue.append(e,t,i);}appendBlocker(e){if(this.operationQueue)return this.operationQueue.appendBlocker(e)}currentOp(e){return this.operationQueue?this.operationQueue.current(e):null}executeNext(e){e&&this.operationQueue&&this.operationQueue.executeNext(e);}shiftAndExecuteNext(e){this.operationQueue&&this.operationQueue.shiftAndExecuteNext(e);}get pendingTrackCount(){return Object.keys(this.tracks).reduce((e,t)=>e+(this.isPending(this.tracks[t])?1:0),0)}get sourceBufferCount(){return this.sourceBuffers.reduce((e,[t])=>e+(t?1:0),0)}get sourceBufferTypes(){return this.sourceBuffers.map(([e])=>e).filter(e=>!!e)}addBufferListener(e,t,i){let r=this.tracks[e];if(!r)return;let n=r.buffer;if(!n)return;let a=i.bind(this,e);r.listeners.push({event:t,listener:a}),n.addEventListener(t,a);}removeBufferListeners(e){let t=this.tracks[e];if(!t)return;let i=t.buffer;i&&(t.listeners.forEach(r=>{i.removeEventListener(r.event,r.listener);}),t.listeners.length=0);}};function ag(s){let e=s.querySelectorAll("source");[].slice.call(e).forEach(t=>{s.removeChild(t);});}function aS(s,e){let t=self.document.createElement("source");t.type="video/mp4",t.src=e,s.appendChild(t);}function ic(s){return s==="audio"?1:0}var Zc=class s{constructor(e){this.hls=void 0,this.autoLevelCapping=void 0,this.firstLevel=void 0,this.media=void 0,this.restrictedLevels=void 0,this.timer=void 0,this.clientRect=void 0,this.streamController=void 0,this.hls=e,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.firstLevel=-1,this.media=null,this.restrictedLevels=[],this.timer=void 0,this.clientRect=null,this.registerListeners();}setStreamController(e){this.streamController=e;}destroy(){this.hls&&this.unregisterListener(),this.timer&&this.stopCapping(),this.media=null,this.clientRect=null,this.hls=this.streamController=null;}registerListeners(){let{hls:e}=this;e.on(g.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.on(g.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(g.MANIFEST_PARSED,this.onManifestParsed,this),e.on(g.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(g.BUFFER_CODECS,this.onBufferCodecs,this),e.on(g.MEDIA_DETACHING,this.onMediaDetaching,this);}unregisterListener(){let{hls:e}=this;e.off(g.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.off(g.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(g.MANIFEST_PARSED,this.onManifestParsed,this),e.off(g.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(g.BUFFER_CODECS,this.onBufferCodecs,this),e.off(g.MEDIA_DETACHING,this.onMediaDetaching,this);}onFpsDropLevelCapping(e,t){let i=this.hls.levels[t.droppedLevel];this.isLevelAllowed(i)&&this.restrictedLevels.push({bitrate:i.bitrate,height:i.height,width:i.width});}onMediaAttaching(e,t){this.media=t.media instanceof HTMLVideoElement?t.media:null,this.clientRect=null,this.timer&&this.hls.levels.length&&this.detectPlayerSize();}onManifestParsed(e,t){let i=this.hls;this.restrictedLevels=[],this.firstLevel=t.firstLevel,i.config.capLevelToPlayerSize&&t.video&&this.startCapping();}onLevelsUpdated(e,t){this.timer&&G(this.autoLevelCapping)&&this.detectPlayerSize();}onBufferCodecs(e,t){this.hls.config.capLevelToPlayerSize&&t.video&&this.startCapping();}onMediaDetaching(){this.stopCapping(),this.media=null;}detectPlayerSize(){if(this.media){if(this.mediaHeight<=0||this.mediaWidth<=0){this.clientRect=null;return}let e=this.hls.levels;if(e.length){let t=this.hls,i=this.getMaxLevel(e.length-1);i!==this.autoLevelCapping&&t.logger.log(`Setting autoLevelCapping to ${i}: ${e[i].height}p@${e[i].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`),t.autoLevelCapping=i,t.autoLevelEnabled&&t.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=t.autoLevelCapping;}}}getMaxLevel(e){let t=this.hls.levels;if(!t.length)return -1;let i=t.filter((r,n)=>this.isLevelAllowed(r)&&n<=e);return this.clientRect=null,s.getMaxLevelByMediaSize(i,this.mediaWidth,this.mediaHeight)}startCapping(){this.timer||(this.autoLevelCapping=Number.POSITIVE_INFINITY,self.clearInterval(this.timer),this.timer=self.setInterval(this.detectPlayerSize.bind(this),1e3),this.detectPlayerSize());}stopCapping(){this.restrictedLevels=[],this.firstLevel=-1,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer&&(self.clearInterval(this.timer),this.timer=void 0);}getDimensions(){if(this.clientRect)return this.clientRect;let e=this.media,t={width:0,height:0};if(e){let i=e.getBoundingClientRect();t.width=i.width,t.height=i.height,!t.width&&!t.height&&(t.width=i.right-i.left||e.width||0,t.height=i.bottom-i.top||e.height||0);}return this.clientRect=t,t}get mediaWidth(){return this.getDimensions().width*this.contentScaleFactor}get mediaHeight(){return this.getDimensions().height*this.contentScaleFactor}get contentScaleFactor(){let e=1;if(!this.hls.config.ignoreDevicePixelRatio)try{e=self.devicePixelRatio;}catch{}return Math.min(e,this.hls.config.maxDevicePixelRatio)}isLevelAllowed(e){return !this.restrictedLevels.some(i=>e.bitrate===i.bitrate&&e.width===i.width&&e.height===i.height)}static getMaxLevelByMediaSize(e,t,i){if(!(e!=null&&e.length))return -1;let r=(o,l)=>l?o.width!==l.width||o.height!==l.height:true,n=e.length-1,a=Math.max(t,i);for(let o=0;o<e.length;o+=1){let l=e[o];if((l.width>=a||l.height>=a)&&r(l,e[o+1])){n=o;break}}return n}},oS={MANIFEST:"m",AUDIO:"a",VIDEO:"v",MUXED:"av",INIT:"i",CAPTION:"c",TIMED_TEXT:"tt",KEY:"k",OTHER:"o"},ct=oS,lS={HLS:"h"},dS=lS,yi=class s{constructor(e,t){Array.isArray(e)&&(e=e.map(i=>i instanceof s?i:new s(i))),this.value=e,this.params=t;}},cS="Dict";function uS(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 hS(s,e,t,i){return new Error(`failed to ${s} "${uS(e)}" as ${t}`,{cause:i})}function ci(s,e,t){return hS("serialize",s,e,t)}var rl=class{constructor(e){this.description=e;}},og="Bare Item",fS="Boolean";function mS(s){if(typeof s!="boolean")throw ci(s,fS);return s?"?1":"?0"}function gS(s){return btoa(String.fromCharCode(...s))}var pS="Byte Sequence";function ES(s){if(ArrayBuffer.isView(s)===false)throw ci(s,pS);return `:${gS(s)}:`}var vS="Integer";function TS(s){return s<-999999999999999||999999999999999<s}function bp(s){if(TS(s))throw ci(s,vS);return s.toString()}function yS(s){return `@${bp(s.getTime()/1e3)}`}function _p(s,e){if(s<0)return -_p(-s,e);let t=Math.pow(10,e);if(Math.abs(s*t%1-.5)<Number.EPSILON){let r=Math.floor(s*t);return (r%2===0?r:r+1)/t}else return Math.round(s*t)/t}var SS="Decimal";function AS(s){let e=_p(s,3);if(Math.floor(Math.abs(e)).toString().length>12)throw ci(s,SS);let t=e.toString();return t.includes(".")?t:`${t}.0`}var bS="String",_S=/[\x00-\x1f\x7f]+/;function IS(s){if(_S.test(s))throw ci(s,bS);return `"${s.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function LS(s){return s.description||s.toString().slice(7,-1)}var xS="Token";function lg(s){let e=LS(s);if(/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(e)===false)throw ci(e,xS);return e}function Jc(s){switch(typeof s){case "number":if(!G(s))throw ci(s,og);return Number.isInteger(s)?bp(s):AS(s);case "string":return IS(s);case "symbol":return lg(s);case "boolean":return mS(s);case "object":if(s instanceof Date)return yS(s);if(s instanceof Uint8Array)return ES(s);if(s instanceof rl)return lg(s);default:throw ci(s,og)}}var RS="Key";function eu(s){if(/^[a-z*][a-z0-9\-_.*]*$/.test(s)===false)throw ci(s,RS);return s}function Wu(s){return s==null?"":Object.entries(s).map(([e,t])=>t===true?`;${eu(e)}`:`;${eu(e)}=${Jc(t)}`).join("")}function Ip(s){return s instanceof yi?`${Jc(s.value)}${Wu(s.params)}`:Jc(s)}function kS(s){return `(${s.value.map(Ip).join(" ")})${Wu(s.params)}`}function DS(s,e={whitespace:true}){if(typeof s!="object"||s==null)throw ci(s,cS);let t=s instanceof Map?s.entries():Object.entries(s),i=e?.whitespace?" ":"";return Array.from(t).map(([r,n])=>{n instanceof yi||(n=new yi(n));let a=eu(r);return n.value===true?a+=Wu(n.params):(a+="=",Array.isArray(n.value)?a+=kS(n):a+=Ip(n)),a}).join(`,${i}`)}function Lp(s,e){return DS(s,e)}var ai="CMCD-Object",Me="CMCD-Request",ss="CMCD-Session",Pi="CMCD-Status",CS={br:ai,ab:ai,d:ai,ot:ai,tb:ai,tpb:ai,lb:ai,tab:ai,lab:ai,url:ai,pb:Me,bl:Me,tbl:Me,dl:Me,ltc:Me,mtp:Me,nor:Me,nrr:Me,rc:Me,sn:Me,sta:Me,su:Me,ttfb:Me,ttfbb:Me,ttlb:Me,cmsdd:Me,cmsds:Me,smrt:Me,df:Me,cs:Me,ts:Me,cid:ss,pr:ss,sf:ss,sid:ss,st:ss,v:ss,msd:ss,bs:Pi,bsd:Pi,cdn:Pi,rtp:Pi,bg:Pi,pt:Pi,ec:Pi,e:Pi},MS={REQUEST:Me};function PS(s){return Object.keys(s).reduce((e,t)=>{var i;return (i=s[t])===null||i===void 0||i.forEach(r=>e[r]=t),e},{})}function wS(s,e){let t={};if(!s)return t;let i=Object.keys(s),r=e?PS(e):{};return i.reduce((n,a)=>{var o;let l=CS[a]||r[a]||MS.REQUEST,d=(o=n[l])!==null&&o!==void 0?o:n[l]={};return d[a]=s[a],n},t)}function OS(s){return ["ot","sf","st","e","sta"].includes(s)}function FS(s){return typeof s=="number"?G(s):s!=null&&s!==""&&s!==false}var xp="event";function NS(s,e){let t=new URL(s),i=new URL(e);if(t.origin!==i.origin)return s;let 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("/")+t.search+t.hash}var No=s=>Math.round(s),tu=(s,e)=>Array.isArray(s)?s.map(t=>tu(t,e)):s instanceof yi&&typeof s.value=="string"?new yi(tu(s.value,e),s.params):(e.baseUrl&&(s=NS(s,e.baseUrl)),e.version===1?encodeURIComponent(s):s),Lo=s=>No(s/100)*100,US=(s,e)=>{let t=s;return e.version>=2&&(s instanceof yi&&typeof s.value=="string"?t=new yi([s]):typeof s=="string"&&(t=[s])),tu(t,e)},BS={br:No,d:No,bl:Lo,dl:Lo,mtp:Lo,nor:US,rtp:Lo,tb:No},Rp="request",kp="response",Yu=["ab","bg","bl","br","bs","bsd","cdn","cid","cs","df","ec","lab","lb","ltc","msd","mtp","pb","pr","pt","sf","sid","sn","st","sta","tab","tb","tbl","tpb","ts","v"],$S=["e"],GS=/^[a-zA-Z0-9-.]+-[a-zA-Z0-9-.]+$/;function ml(s){return GS.test(s)}function HS(s){return Yu.includes(s)||$S.includes(s)||ml(s)}var Dp=["d","dl","nor","ot","rtp","su"];function KS(s){return Yu.includes(s)||Dp.includes(s)||ml(s)}var VS=["cmsdd","cmsds","rc","smrt","ttfb","ttfbb","ttlb","url"];function WS(s){return Yu.includes(s)||Dp.includes(s)||VS.includes(s)||ml(s)}var YS=["bl","br","bs","cid","d","dl","mtp","nor","nrr","ot","pr","rtp","sf","sid","st","su","tb","v"];function qS(s){return YS.includes(s)||ml(s)}var jS={[kp]:WS,[xp]:HS,[Rp]:KS};function Cp(s,e={}){let t={};if(s==null||typeof s!="object")return t;let i=e.version||s.v||1,r=e.reportingMode||Rp,n=i===1?qS:jS[r],a=Object.keys(s).filter(n),o=e.filter;typeof o=="function"&&(a=a.filter(o));let l=r===kp||r===xp;l&&!a.includes("ts")&&a.push("ts"),i>1&&!a.includes("v")&&a.push("v");let d=ye({},BS,e.formatters),c={version:i,reportingMode:r,baseUrl:e.baseUrl};return a.sort().forEach(u=>{let h=s[u],f=d[u];if(typeof f=="function"&&(h=f(h,c)),u==="v"){if(i===1)return;h=i;}u=="pr"&&h===1||(l&&u==="ts"&&!G(h)&&(h=Date.now()),FS(h)&&(OS(u)&&typeof h=="string"&&(h=new rl(h)),t[u]=h));}),t}function zS(s,e={}){let t={};if(!s)return t;let i=Cp(s,e),r=wS(i,e?.customHeaderMap);return Object.entries(r).reduce((n,[a,o])=>{let l=Lp(o,{whitespace:false});return l&&(n[a]=l),n},t)}function QS(s,e,t){return ye(s,zS(e,t))}var XS="CMCD";function ZS(s,e={}){return s?Lp(Cp(s,e),{whitespace:false}):""}function JS(s,e={}){if(!s)return "";let t=ZS(s,e);return encodeURIComponent(t)}function eA(s,e={}){if(!s)return "";let t=JS(s,e);return `${XS}=${t}`}var dg=/CMCD=[^&#]+/;function tA(s,e,t){let i=eA(e,t);if(!i)return s;if(dg.test(s))return s.replace(dg,i);let r=s.includes("?")?"&":"?";return `${s}${r}${i}`}var iu=class{constructor(e){this.hls=void 0,this.config=void 0,this.media=void 0,this.sid=void 0,this.cid=void 0,this.useHeaders=false,this.includeKeys=void 0,this.initialized=false,this.starved=false,this.buffering=true,this.audioBuffer=void 0,this.videoBuffer=void 0,this.onWaiting=()=>{this.initialized&&(this.starved=true),this.buffering=true;},this.onPlaying=()=>{this.initialized||(this.initialized=true),this.buffering=false;},this.applyPlaylistData=r=>{try{this.apply(r,{ot:ct.MANIFEST,su:!this.initialized});}catch(n){this.hls.logger.warn("Could not generate manifest CMCD data.",n);}},this.applyFragmentData=r=>{try{let{frag:n,part:a}=r,o=this.hls.levels[n.level],l=this.getObjectType(n),d={d:(a||n).duration*1e3,ot:l};(l===ct.VIDEO||l===ct.AUDIO||l==ct.MUXED)&&(d.br=o.bitrate/1e3,d.tb=this.getTopBandwidth(l)/1e3,d.bl=this.getBufferLength(l));let c=a?this.getNextPart(a):this.getNextFrag(n);c!=null&&c.url&&c.url!==n.url&&(d.nor=c.url),this.apply(r,d);}catch(n){this.hls.logger.warn("Could not generate segment CMCD data.",n);}},this.hls=e;let t=this.config=e.config,{cmcd:i}=t;i!=null&&(t.pLoader=this.createPlaylistLoader(),t.fLoader=this.createFragmentLoader(),this.sid=i.sessionId||e.sessionId,this.cid=i.contentId,this.useHeaders=i.useHeaders===true,this.includeKeys=i.includeKeys,this.registerListeners());}registerListeners(){let e=this.hls;e.on(g.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(g.MEDIA_DETACHED,this.onMediaDetached,this),e.on(g.BUFFER_CREATED,this.onBufferCreated,this);}unregisterListeners(){let e=this.hls;e.off(g.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(g.MEDIA_DETACHED,this.onMediaDetached,this),e.off(g.BUFFER_CREATED,this.onBufferCreated,this);}destroy(){this.unregisterListeners(),this.onMediaDetached(),this.hls=this.config=this.audioBuffer=this.videoBuffer=null,this.onWaiting=this.onPlaying=this.media=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:dS.HLS,sid:this.sid,cid:this.cid,pr:(e=this.media)==null?void 0:e.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(e,t={}){ye(t,this.createData());let i=t.ot===ct.INIT||t.ot===ct.VIDEO||t.ot===ct.MUXED;this.starved&&i&&(t.bs=true,t.su=true,this.starved=false),t.su==null&&(t.su=this.buffering);let{includeKeys:r}=this;r&&(t=Object.keys(t).reduce((a,o)=>(r.includes(o)&&(a[o]=t[o]),a),{}));let n={baseUrl:e.url};this.useHeaders?(e.headers||(e.headers={}),QS(e.headers,t,n)):e.url=tA(e.url,t,n);}getNextFrag(e){var t;let i=(t=this.hls.levels[e.level])==null?void 0:t.details;if(i){let r=e.sn-i.startSN;return i.fragments[r+1]}}getNextPart(e){var t;let{index:i,fragment:r}=e,n=(t=this.hls.levels[r.level])==null||(t=t.details)==null?void 0:t.partList;if(n){let{sn:a}=r;for(let o=n.length-1;o>=0;o--){let l=n[o];if(l.index===i&&l.fragment.sn===a)return n[o+1]}}}getObjectType(e){let{type:t}=e;if(t==="subtitle")return ct.TIMED_TEXT;if(e.sn==="initSegment")return ct.INIT;if(t==="audio")return ct.AUDIO;if(t==="main")return this.hls.audioTracks.length?ct.VIDEO:ct.MUXED}getTopBandwidth(e){let t=0,i,r=this.hls;if(e===ct.AUDIO)i=r.audioTracks;else {let n=r.maxAutoLevel,a=n>-1?n+1:r.levels.length;i=r.levels.slice(0,a);}return i.forEach(n=>{n.bitrate>t&&(t=n.bitrate);}),t>0?t:NaN}getBufferLength(e){let t=this.media,i=e===ct.AUDIO?this.audioBuffer:this.videoBuffer;return !i||!t?NaN:re.bufferInfo(i,t.currentTime,this.config.maxBufferHole).len*1e3}createPlaylistLoader(){let{pLoader:e}=this.config,t=this.applyPlaylistData,i=e||this.config.loader;return class{constructor(n){this.loader=void 0,this.loader=new i(n);}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy();}abort(){this.loader.abort();}load(n,a,o){t(n),this.loader.load(n,a,o);}}}createFragmentLoader(){let{fLoader:e}=this.config,t=this.applyFragmentData,i=e||this.config.loader;return class{constructor(n){this.loader=void 0,this.loader=new i(n);}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy();}abort(){this.loader.abort();}load(n,a,o){t(n),this.loader.load(n,a,o);}}}},iA=3e5,su=class extends ht{constructor(e){super("content-steering",e.logger),this.hls=void 0,this.loader=null,this.uri=null,this.pathwayId=".",this._pathwayPriority=null,this.timeToLoad=300,this.reloadTimer=-1,this.updated=0,this.started=false,this.enabled=true,this.levels=null,this.audioTracks=null,this.subtitleTracks=null,this.penalizedPathways={},this.hls=e,this.registerListeners();}registerListeners(){let e=this.hls;e.on(g.MANIFEST_LOADING,this.onManifestLoading,this),e.on(g.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(g.MANIFEST_PARSED,this.onManifestParsed,this),e.on(g.ERROR,this.onError,this);}unregisterListeners(){let e=this.hls;e&&(e.off(g.MANIFEST_LOADING,this.onManifestLoading,this),e.off(g.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(g.MANIFEST_PARSED,this.onManifestParsed,this),e.off(g.ERROR,this.onError,this));}pathways(){return (this.levels||[]).reduce((e,t)=>(e.indexOf(t.pathwayId)===-1&&e.push(t.pathwayId),e),[])}get pathwayPriority(){return this._pathwayPriority}set pathwayPriority(e){this.updatePathwayPriority(e);}startLoad(){if(this.started=true,this.clearTimeout(),this.enabled&&this.uri){if(this.updated){let e=this.timeToLoad*1e3-(performance.now()-this.updated);if(e>0){this.scheduleRefresh(this.uri,e);return}}this.loadSteeringManifest(this.uri);}}stopLoad(){this.started=false,this.loader&&(this.loader.destroy(),this.loader=null),this.clearTimeout();}clearTimeout(){this.reloadTimer!==-1&&(self.clearTimeout(this.reloadTimer),this.reloadTimer=-1);}destroy(){this.unregisterListeners(),this.stopLoad(),this.hls=null,this.levels=this.audioTracks=this.subtitleTracks=null;}removeLevel(e){let t=this.levels;t&&(this.levels=t.filter(i=>i!==e));}onManifestLoading(){this.stopLoad(),this.enabled=true,this.timeToLoad=300,this.updated=0,this.uri=null,this.pathwayId=".",this.levels=this.audioTracks=this.subtitleTracks=null;}onManifestLoaded(e,t){let{contentSteering:i}=t;i!==null&&(this.pathwayId=i.pathwayId,this.uri=i.uri,this.started&&this.startLoad());}onManifestParsed(e,t){this.audioTracks=t.audioTracks,this.subtitleTracks=t.subtitleTracks;}onError(e,t){let{errorAction:i}=t;if(i?.action===ze.SendAlternateToPenaltyBox&&i.flags===yt.MoveAllAlternatesMatchingHost){let r=this.levels,n=this._pathwayPriority,a=this.pathwayId;if(t.context){let{groupId:o,pathwayId:l,type:d}=t.context;o&&r?a=this.getPathwayForGroupId(o,d,a):l&&(a=l);}a in this.penalizedPathways||(this.penalizedPathways[a]=performance.now()),!n&&r&&(n=this.pathways()),n&&n.length>1&&(this.updatePathwayPriority(n),i.resolved=this.pathwayId!==a),t.details===x.BUFFER_APPEND_ERROR&&!t.fatal?i.resolved=true:i.resolved||this.warn(`Could not resolve ${t.details} ("${t.error.message}") with content-steering for Pathway: ${a} levels: ${r&&r.length} priorities: ${Ae(n)} penalized: ${Ae(this.penalizedPathways)}`);}}filterParsedLevels(e){this.levels=e;let t=this.getLevelsForPathway(this.pathwayId);if(t.length===0){let i=e[0].pathwayId;this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${i}"`),t=this.getLevelsForPathway(i),this.pathwayId=i;}return t.length!==e.length&&this.log(`Found ${t.length}/${e.length} levels in Pathway "${this.pathwayId}"`),t}getLevelsForPathway(e){return this.levels===null?[]:this.levels.filter(t=>e===t.pathwayId)}updatePathwayPriority(e){this._pathwayPriority=e;let t,i=this.penalizedPathways,r=performance.now();Object.keys(i).forEach(n=>{r-i[n]>iA&&delete i[n];});for(let n=0;n<e.length;n++){let a=e[n];if(a in i)continue;if(a===this.pathwayId)return;let o=this.hls.nextLoadLevel,l=this.hls.levels[o];if(t=this.getLevelsForPathway(a),t.length>0){this.log(`Setting Pathway to "${a}"`),this.pathwayId=a,tp(t),this.hls.trigger(g.LEVELS_UPDATED,{levels:t});let d=this.hls.levels[o];l&&d&&this.levels&&(d.attrs["STABLE-VARIANT-ID"]!==l.attrs["STABLE-VARIANT-ID"]&&d.bitrate!==l.bitrate&&this.log(`Unstable Pathways change from bitrate ${l.bitrate} to ${d.bitrate}`),this.hls.nextLoadLevel=o);break}}}getPathwayForGroupId(e,t,i){let r=this.getLevelsForPathway(i).concat(this.levels||[]);for(let n=0;n<r.length;n++)if(t===ce.AUDIO_TRACK&&r[n].hasAudioGroup(e)||t===ce.SUBTITLE_TRACK&&r[n].hasSubtitleGroup(e))return r[n].pathwayId;return i}clonePathways(e){let t=this.levels;if(!t)return;let i={},r={};e.forEach(n=>{let{ID:a,"BASE-ID":o,"URI-REPLACEMENT":l}=n;if(t.some(c=>c.pathwayId===a))return;let d=this.getLevelsForPathway(o).map(c=>{let u=new Re(c.attrs);u["PATHWAY-ID"]=a;let h=u.AUDIO&&`${u.AUDIO}_clone_${a}`,f=u.SUBTITLES&&`${u.SUBTITLES}_clone_${a}`;h&&(i[u.AUDIO]=h,u.AUDIO=h),f&&(r[u.SUBTITLES]=f,u.SUBTITLES=f);let m=Mp(c.uri,u["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",l),p=new ds({attrs:u,audioCodec:c.audioCodec,bitrate:c.bitrate,height:c.height,name:c.name,url:m,videoCodec:c.videoCodec,width:c.width});if(c.audioGroups)for(let E=1;E<c.audioGroups.length;E++)p.addGroupId("audio",`${c.audioGroups[E]}_clone_${a}`);if(c.subtitleGroups)for(let E=1;E<c.subtitleGroups.length;E++)p.addGroupId("text",`${c.subtitleGroups[E]}_clone_${a}`);return p});t.push(...d),cg(this.audioTracks,i,l,a),cg(this.subtitleTracks,r,l,a);});}loadSteeringManifest(e){let 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=false,this.log(`Failed to parse Steering Manifest URI: ${e}`);return}if(r.protocol!=="data:"){let c=(this.hls.bandwidthEstimate||t.abrEwmaDefaultEstimate)|0;r.searchParams.set("_HLS_pathway",this.pathwayId),r.searchParams.set("_HLS_throughput",""+c);}let 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},d={onSuccess:(c,u,h,f)=>{this.log(`Loaded steering manifest: "${r}"`);let m=c.data;if(m?.VERSION!==1){this.log(`Steering VERSION ${m.VERSION} not supported!`);return}this.updated=performance.now(),this.timeToLoad=m.TTL;let{"RELOAD-URI":p,"PATHWAY-CLONES":E,"PATHWAY-PRIORITY":v}=m;if(p)try{this.uri=new self.URL(p,r).href;}catch{this.enabled=false,this.log(`Failed to parse Steering Manifest RELOAD-URI: ${p}`);return}this.scheduleRefresh(this.uri||h.url),E&&this.clonePathways(E);let T={steeringManifest:m,url:r.toString()};this.hls.trigger(g.STEERING_MANIFEST_LOADED,T),v&&this.updatePathwayPriority(v);},onError:(c,u,h,f)=>{if(this.log(`Error loading steering manifest: ${c.code} ${c.text} (${u.url})`),this.stopLoad(),c.code===410){this.enabled=false,this.log(`Steering manifest ${u.url} no longer available`);return}let m=this.timeToLoad*1e3;if(c.code===429){let p=this.loader;if(typeof p?.getResponseHeader=="function"){let E=p.getResponseHeader("Retry-After");E&&(m=parseFloat(E)*1e3);}this.log(`Steering manifest ${u.url} rate limited`);return}this.scheduleRefresh(this.uri||u.url,m);},onTimeout:(c,u,h)=>{this.log(`Timeout loading steering manifest (${u.url})`),this.scheduleRefresh(this.uri||u.url);}};this.log(`Requesting steering manifest: ${r}`),this.loader.load(n,l,d);}scheduleRefresh(e,t=this.timeToLoad*1e3){this.clearTimeout(),this.reloadTimer=self.setTimeout(()=>{var i;let 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 cg(s,e,t,i){s&&Object.keys(e).forEach(r=>{let n=s.filter(a=>a.groupId===r).map(a=>{let o=ye({},a);return o.details=void 0,o.attrs=new Re(o.attrs),o.url=o.attrs.URI=Mp(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 Mp(s,e,t,i){let{HOST:r,PARAMS:n,[t]:a}=i,o;e&&(o=a?.[e],o&&(s=o));let l=new self.URL(s);return r&&!o&&(l.host=r),n&&Object.keys(n).sort().forEach(d=>{d&&l.searchParams.set(d,n[d]);}),l.href}var nl=class s extends ht{constructor(e){super("eme",e.logger),this.hls=void 0,this.config=void 0,this.media=null,this.keyFormatPromise=null,this.keySystemAccessPromises={},this._requestLicenseFailureCount=0,this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},this.mediaKeys=null,this.setMediaKeysQueue=s.CDMCleanupPromise?[s.CDMCleanupPromise]:[],this.bannedKeyIds={},this.onMediaEncrypted=t=>{let{initDataType:i,initData:r}=t,n=`"${t.type}" event: init data type: "${i}"`;if(this.debug(n),r!==null){if(!this.keyFormatPromise){let a=Object.keys(this.keySystemAccessPromises);a.length||(a=dn(this.config));let o=a.map(jd).filter(l=>!!l);this.keyFormatPromise=this.getKeyFormatPromise(o);}this.keyFormatPromise.then(a=>{let o=Oo(a);if(i!=="sinf"||o!==ke.FAIRPLAY){this.log(`Ignoring "${t.type}" event with init data type: "${i}" for selected key-system ${o}`);return}let l;try{let f=He(new Uint8Array(r)),m=Uu(JSON.parse(f).sinf),p=Mg(m);if(!p)throw new Error("'schm' box missing or not cbcs/cenc with schi > tenc");l=new Uint8Array(p.subarray(8,24));}catch(f){this.warn(`${n} Failed to parse sinf: ${f}`);return}let d=rt(l),{keyIdToKeySessionPromise:c,mediaKeySessions:u}=this,h=c[d];for(let f=0;f<u.length;f++){let m=u[f],p=m.decryptdata;if(!p.keyId)continue;let E=rt(p.keyId);if(Qo(l,p.keyId)||p.uri.replace(/-/g,"").indexOf(d)!==-1){if(h=c[E],!h)continue;if(p.pssh)break;delete c[E],p.pssh=new Uint8Array(r),p.keyId=l,h=c[d]=h.then(()=>this.generateRequestWithPreferredKeySession(m,i,r,"encrypted-event-key-match")),h.catch(v=>this.handleError(v));break}}h||this.handleError(new Error(`Key ID ${d} not encountered in playlist. Key-system sessions ${u.length}.`));}).catch(a=>this.handleError(a));}},this.onWaitingForKey=t=>{this.log(`"${t.type}" event`);},this.hls=e,this.config=e.config,this.registerListeners();}destroy(){this.onDestroying(),this.onMediaDetached();let e=this.config;e.requestMediaKeySystemAccessFunc=null,e.licenseXhrSetup=e.licenseResponseCallback=void 0,e.drmSystems=e.drmSystemOptions={},this.hls=this.config=this.keyIdToKeySessionPromise=null,this.onMediaEncrypted=this.onWaitingForKey=null;}registerListeners(){this.hls.on(g.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(g.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(g.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(g.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.on(g.DESTROYING,this.onDestroying,this);}unregisterListeners(){this.hls.off(g.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(g.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(g.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(g.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.off(g.DESTROYING,this.onDestroying,this);}getLicenseServerUrl(e){let{drmSystems:t,widevineLicenseUrl:i}=this.config,r=t?.[e];if(r)return r.licenseUrl;if(e===ke.WIDEVINE&&i)return i}getLicenseServerUrlOrThrow(e){let t=this.getLicenseServerUrl(e);if(t===void 0)throw new Error(`no license server URL configured for key-system "${e}"`);return t}getServerCertificateUrl(e){let{drmSystems:t}=this.config,i=t?.[e];if(i)return i.serverCertificateUrl;this.log(`No Server Certificate in config.drmSystems["${e}"]`);}attemptKeySystemAccess(e){let t=this.hls.levels,i=(a,o,l)=>!!a&&l.indexOf(a)===o,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)=>{let l=d=>{let c=d.shift();this.getMediaKeysPromise(c,r,n).then(u=>a({keySystem:c,mediaKeys:u})).catch(u=>{d.length?l(d):u instanceof st?o(u):o(new st({type:z.KEY_SYSTEM_ERROR,details:x.KEY_SYSTEM_NO_ACCESS,error:u,fatal:true},u.message));});};l(e);})}requestMediaKeySystemAccess(e,t){let{requestMediaKeySystemAccessFunc:i}=this.config;if(typeof i!="function"){let r=`Configured requestMediaKeySystemAccess is not a function ${i}`;return qg===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){var r;let n=ey(e,t,i,this.config.drmSystemOptions||{}),a=this.keySystemAccessPromises[e],o=(r=a)==null?void 0:r.keySystemAccess;if(!o){this.log(`Requesting encrypted media "${e}" key-system access with config: ${Ae(n)}`),o=this.requestMediaKeySystemAccess(e,n);let l=a=this.keySystemAccessPromises[e]={keySystemAccess:o};return o.catch(d=>{this.log(`Failed to obtain access to key-system "${e}": ${d}`);}),o.then(d=>{this.log(`Access for key-system "${d.keySystem}" obtained`);let c=this.fetchServerCertificate(e);this.log(`Create media-keys for "${e}"`);let u=l.mediaKeys=d.createMediaKeys().then(h=>(this.log(`Media-keys created for "${e}"`),l.hasMediaKeys=true,c.then(f=>f?this.setMediaKeysServerCertificate(h,e,f):h)));return u.catch(h=>{this.error(`Failed to create media-keys for "${e}"}: ${h}`);}),u})}return o.then(()=>a.mediaKeys)}createMediaKeySessionContext({decryptdata:e,keySystem:t,mediaKeys:i}){this.log(`Creating key-system session "${t}" keyId: ${rt(e.keyId||[])} keyUri: ${e.uri}`);let r=i.createSession(),n={decryptdata:e,keySystem:t,mediaKeys:i,mediaKeysSession:r,keyStatus:"status-pending"};return this.mediaKeySessions.push(n),n}renewKeySession(e){let t=e.decryptdata;if(t.pssh){let i=this.createMediaKeySessionContext(e),r=xo(t),n="cenc";this.keyIdToKeySessionPromise[r]=this.generateRequestWithPreferredKeySession(i,n,t.pssh.buffer,"expired");}else this.warn("Could not renew expired session. Missing pssh initData.");this.removeSession(e);}updateKeySession(e,t){let i=e.mediaKeysSession;return this.log(`Updating key-session "${i.sessionId}" for keyId ${rt(e.decryptdata.keyId||[])}
1376
+ } (data length: ${t.byteLength})`),i.update(t)}getSelectedKeySystemFormats(){return Object.keys(this.keySystemAccessPromises).map(e=>({keySystem:e,hasMediaKeys:this.keySystemAccessPromises[e].hasMediaKeys})).filter(({hasMediaKeys:e})=>!!e).map(({keySystem:e})=>jd(e)).filter(e=>!!e)}getKeySystemAccess(e){return this.getKeySystemSelectionPromise(e).then(({keySystem:t,mediaKeys:i})=>this.attemptSetMediaKeys(t,i))}selectKeySystem(e){return new Promise((t,i)=>{this.getKeySystemSelectionPromise(e).then(({keySystem:r})=>{let n=jd(r);n?t(n):i(new Error(`Unable to find format for key-system "${r}"`));}).catch(i);})}selectKeySystemFormat(e){let t=Object.keys(e.levelkeys||{});return this.keyFormatPromise||(this.log(`Selecting key-system from fragment (sn: ${e.sn} ${e.type}: ${e.level}) key formats ${t.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(t)),this.keyFormatPromise}getKeyFormatPromise(e){let t=dn(this.config),i=e.map(Oo).filter(r=>!!r&&t.indexOf(r)!==-1);return this.selectKeySystem(i)}getKeyStatus(e){let{mediaKeySessions:t}=this;for(let i=0;i<t.length;i++){let r=sA(e,t[i]);if(r)return r}}loadKey(e){let t=e.keyInfo.decryptdata,i=xo(t),r=this.bannedKeyIds[i];if(r||this.getKeyStatus(t)==="internal-error"){let o=ug(r||"internal-error",t);return this.handleError(o,e.frag),Promise.reject(o)}let n=`(keyId: ${i} format: "${t.keyFormat}" method: ${t.method} uri: ${t.uri})`;this.log(`Starting session for key ${n}`);let a=this.keyIdToKeySessionPromise[i];if(!a){let o=this.getKeySystemForKeyPromise(t).then(({keySystem:l,mediaKeys:d})=>(this.throwIfDestroyed(),this.log(`Handle encrypted media sn: ${e.frag.sn} ${e.frag.type}: ${e.frag.level} using key ${n}`),this.attemptSetMediaKeys(l,d).then(()=>(this.throwIfDestroyed(),this.createMediaKeySessionContext({keySystem:l,mediaKeys:d,decryptdata:t}))))).then(l=>{let d="cenc",c=t.pssh?t.pssh.buffer:null;return this.generateRequestWithPreferredKeySession(l,d,c,"playlist-key")});return o.catch(l=>this.handleError(l,e.frag)),this.keyIdToKeySessionPromise[i]=o,o}return a.catch(o=>{if(o instanceof st){let l=ve({},o.data);this.getKeyStatus(t)==="internal-error"&&(l.decryptdata=t);let d=new st(l,o.message);this.handleError(d,e.frag);}}),a}throwIfDestroyed(e="Invalid state"){if(!this.hls)throw new Error("invalid state")}handleError(e,t){if(this.hls)if(e instanceof st){t&&(e.data.frag=t);let i=e.data.decryptdata;this.error(`${e.message}${i?` (${rt(i.keyId||[])})`:""}`),this.hls.trigger(g.ERROR,e.data);}else this.error(e.message),this.hls.trigger(g.ERROR,{type:z.KEY_SYSTEM_ERROR,details:x.KEY_SYSTEM_NO_KEYS,error:e,fatal:true});}getKeySystemForKeyPromise(e){let t=xo(e),i=this.keyIdToKeySessionPromise[t];if(!i){let r=Oo(e.keyFormat),n=r?[r]:dn(this.config);return this.attemptKeySystemAccess(n)}return i}getKeySystemSelectionPromise(e){if(e.length||(e=dn(this.config)),e.length===0)throw new st({type:z.KEY_SYSTEM_ERROR,details:x.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:true},`Missing key-system license configuration options ${Ae({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(e)}attemptSetMediaKeys(e,t){if(this.mediaKeys===t)return Promise.resolve();let i=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${e}"`);let r=Promise.all(i).then(()=>{if(!this.media)throw this.mediaKeys=null,new Error("Attempted to set mediaKeys without media element attached");return this.media.setMediaKeys(t)});return this.mediaKeys=t,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;let a=(n=this.config.drmSystems)==null||(n=n[e.keySystem])==null?void 0:n.generateRequest;if(a)try{let m=a.call(this.hls,t,i,e);if(!m)throw new Error("Invalid response from configured generateRequest filter");t=m.initDataType,i=m.initData?m.initData:null,e.decryptdata.pssh=i?new Uint8Array(i):null;}catch(m){if(this.warn(m.message),this.hls&&this.hls.config.debug)throw m}if(i===null)return this.log(`Skipping key-session request for "${r}" (no initData)`),Promise.resolve(e);let o=xo(e.decryptdata),l=e.decryptdata.uri;this.log(`Generating key-session request for "${r}" keyId: ${o} URI: ${l} (init data type: ${t} length: ${i.byteLength})`);let d=new Bu,c=e._onmessage=m=>{let p=e.mediaKeysSession;if(!p){d.emit("error",new Error("invalid state"));return}let{messageType:E,message:v}=m;this.log(`"${E}" message event for session "${p.sessionId}" message size: ${v.byteLength}`),E==="license-request"||E==="license-renewal"?this.renewLicense(e,v).catch(T=>{d.eventNames().length?d.emit("error",T):this.handleError(T);}):E==="license-release"?e.keySystem===ke.FAIRPLAY&&this.updateKeySession(e,kc("acknowledged")).then(()=>this.removeSession(e)).catch(T=>this.handleError(T)):this.warn(`unhandled media key message type "${E}"`);},u=(m,p)=>{p.keyStatus=m;let E;m.startsWith("usable")?d.emit("resolved"):m==="internal-error"||m==="output-restricted"||m==="output-downscaled"?E=ug(m,p.decryptdata):m==="expired"?E=new Error(`key expired (keyId: ${o})`):m==="released"?E=new Error("key released"):m==="status-pending"||this.warn(`unhandled key status change "${m}" (keyId: ${o})`),E&&(d.eventNames().length?d.emit("error",E):this.handleError(E));},h=e._onkeystatuseschange=m=>{if(!e.mediaKeysSession){d.emit("error",new Error("invalid state"));return}let E=this.getKeyStatuses(e);if(!Object.keys(E).some(A=>E[A]!=="status-pending"))return;if(E[o]==="expired"){this.log(`Expired key ${Ae(E)} in key-session "${e.mediaKeysSession.sessionId}"`),this.renewKeySession(e);return}let T=E[o];if(T)u(T,e);else {var S;e.keyStatusTimeouts||(e.keyStatusTimeouts={}),(S=e.keyStatusTimeouts)[o]||(S[o]=self.setTimeout(()=>{if(!e.mediaKeysSession||!this.mediaKeys)return;let b=this.getKeyStatus(e.decryptdata);if(b&&b!=="status-pending")return this.log(`No status for keyId ${o} in key-session "${e.mediaKeysSession.sessionId}". Using session key-status ${b} from other session.`),u(b,e);this.log(`key status for ${o} in key-session "${e.mediaKeysSession.sessionId}" timed out after 1000ms`),T="internal-error",u(T,e);},1e3)),this.log(`No status for keyId ${o} (${Ae(E)}).`);}};nt(e.mediaKeysSession,"message",c),nt(e.mediaKeysSession,"keystatuseschange",h);let f=new Promise((m,p)=>{d.on("error",p),d.on("resolved",m);});return e.mediaKeysSession.generateRequest(t,i).then(()=>{this.log(`Request generated for key-session "${e.mediaKeysSession.sessionId}" keyId: ${o} URI: ${l}`);}).catch(m=>{throw new st({type:z.KEY_SYSTEM_ERROR,details:x.KEY_SYSTEM_NO_SESSION,error:m,decryptdata:e.decryptdata,fatal:false},`Error generating key-session request: ${m}`)}).then(()=>f).catch(m=>(d.removeAllListeners(),this.removeSession(e).then(()=>{throw m}))).then(()=>(d.removeAllListeners(),e))}getKeyStatuses(e){let t={};return e.mediaKeysSession.keyStatuses.forEach((i,r)=>{if(typeof r=="string"&&typeof i=="object"){let o=r;r=i,i=o;}let n="buffer"in r?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):new Uint8Array(r);e.keySystem===ke.PLAYREADY&&n.length===16&&Wg(n);let a=rt(n);i==="internal-error"&&(this.bannedKeyIds[a]=i),this.log(`key status change "${i}" for keyStatuses keyId: ${a} key-session "${e.mediaKeysSession.sessionId}"`),t[a]=i;}),t}fetchServerCertificate(e){let 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)=>{let l={responseType:"arraybuffer",url:n},d=t.certLoadPolicy.default,c={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},u={onSuccess:(h,f,m,p)=>{a(h.data);},onError:(h,f,m,p)=>{o(new st({type:z.KEY_SYSTEM_ERROR,details:x.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:true,networkDetails:m,response:ve({url:l.url,data:void 0},h)},`"${e}" certificate request failed (${n}). Status: ${h.code} (${h.text})`));},onTimeout:(h,f,m)=>{o(new st({type:z.KEY_SYSTEM_ERROR,details:x.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:true,networkDetails:m,response:{url:l.url,data:void 0}},`"${e}" certificate request timed out (${n})`));},onAbort:(h,f,m)=>{o(new Error("aborted"));}};r.load(l,c,u);})):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.byteLength}) on "${t}"`),r(e);}).catch(a=>{n(new st({type:z.KEY_SYSTEM_ERROR,details:x.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:a,fatal:true},a.message));});})}renewLicense(e,t){return this.requestLicense(e,new Uint8Array(t)).then(i=>this.updateKeySession(e,new Uint8Array(i)).catch(r=>{throw new st({type:z.KEY_SYSTEM_ERROR,details:x.KEY_SYSTEM_SESSION_UPDATE_FAILED,decryptdata:e.decryptdata,error:r,fatal:false},r.message)}))}unpackPlayReadyKeyMessage(e,t){let i=String.fromCharCode.apply(null,new Uint16Array(t.buffer));if(!i.includes("PlayReadyKeyMessage"))return e.setRequestHeader("Content-Type","text/xml; charset=utf-8"),t;let r=new DOMParser().parseFromString(i,"application/xml"),n=r.querySelectorAll("HttpHeader");if(n.length>0){let c;for(let u=0,h=n.length;u<h;u++){var a,o;c=n[u];let f=(a=c.querySelector("name"))==null?void 0:a.textContent,m=(o=c.querySelector("value"))==null?void 0:o.textContent;f&&m&&e.setRequestHeader(f,m);}}let l=r.querySelector("Challenge"),d=l?.textContent;if(!d)throw new Error("Cannot find <Challenge> in key message");return kc(atob(d))}setupLicenseXHR(e,t,i,r){let n=this.config.licenseXhrSetup;return n?Promise.resolve().then(()=>{if(!i.decryptdata)throw new Error("Key removed");return n.call(this.hls,e,t,i,r)}).catch(a=>{if(!i.decryptdata)throw a;return e.open("POST",t,true),n.call(this.hls,e,t,i,r)}).then(a=>(e.readyState||e.open("POST",t,true),{xhr:e,licenseChallenge:a||r})):(e.open("POST",t,true),Promise.resolve({xhr:e,licenseChallenge:r}))}requestLicense(e,t){let i=this.config.keyLoadPolicy.default;return new Promise((r,n)=>{let a=this.getLicenseServerUrlOrThrow(e.keySystem);this.log(`Sending license request to URL: ${a}`);let o=new XMLHttpRequest;o.responseType="arraybuffer",o.onreadystatechange=()=>{if(!this.hls||!e.mediaKeysSession)return n(new Error("invalid state"));if(o.readyState===4)if(o.status===200){this._requestLicenseFailureCount=0;let l=o.response;this.log(`License received ${l instanceof ArrayBuffer?l.byteLength:l}`);let d=this.config.licenseResponseCallback;if(d)try{l=d.call(this.hls,o,a,e);}catch(c){this.error(c);}r(l);}else {let l=i.errorRetry,d=l?l.maxNumRetry:0;if(this._requestLicenseFailureCount++,this._requestLicenseFailureCount>d||o.status>=400&&o.status<500)n(new st({type:z.KEY_SYSTEM_ERROR,details:x.KEY_SYSTEM_LICENSE_REQUEST_FAILED,decryptdata:e.decryptdata,fatal:true,networkDetails:o,response:{url:a,data:void 0,code:o.status,text:o.statusText}},`License Request XHR failed (${a}). Status: ${o.status} (${o.statusText})`));else {let c=d-this._requestLicenseFailureCount+1;this.warn(`Retrying license request, ${c} 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:d})=>{e.keySystem==ke.PLAYREADY&&(d=this.unpackPlayReadyKeyMessage(l,d)),l.send(d);}).catch(n);})}onDestroying(){this.unregisterListeners(),this._clear();}onMediaAttached(e,t){if(!this.config.emeEnabled)return;let i=t.media;this.media=i,nt(i,"encrypted",this.onMediaEncrypted),nt(i,"waitingforkey",this.onWaitingForKey);}onMediaDetached(){let e=this.media;e&&(ut(e,"encrypted",this.onMediaEncrypted),ut(e,"waitingforkey",this.onWaitingForKey),this.media=null,this.mediaKeys=null);}_clear(){var e;if(this._requestLicenseFailureCount=0,this.keyIdToKeySessionPromise={},this.bannedKeyIds={},!this.mediaKeys&&!this.mediaKeySessions.length)return;let t=this.media,i=this.mediaKeySessions.slice();this.mediaKeySessions=[],this.mediaKeys=null,Tn.clearKeyUriToKeyIdMap();let r=i.length;s.CDMCleanupPromise=Promise.all(i.map(n=>this.removeSession(n)).concat((t==null||(e=t.setMediaKeys(null))==null?void 0:e.catch(n=>{this.log(`Could not clear media keys: ${n}`),this.hls&&this.hls.trigger(g.ERROR,{type:z.OTHER_ERROR,details:x.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR,fatal:false,error:new Error(`Could not clear media keys: ${n}`)});}))||Promise.resolve())).catch(n=>{this.log(`Could not close sessions and clear media keys: ${n}`),this.hls&&this.hls.trigger(g.ERROR,{type:z.OTHER_ERROR,details:x.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:false,error:new Error(`Could not close sessions and clear media keys: ${n}`)});}).then(()=>{r&&this.log("finished closing key sessions and clearing media keys");});}onManifestLoading(){this.keyFormatPromise=null,this.bannedKeyIds={};}onManifestLoaded(e,{sessionKeys:t}){if(!(!t||!this.config.emeEnabled)&&!this.keyFormatPromise){let 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){let{mediaKeysSession:t,licenseXhr:i,decryptdata:r}=e;if(t){this.log(`Remove licenses and keys and close session "${t.sessionId}" keyId: ${rt(r?.keyId||[])}`),e._onmessage&&(t.removeEventListener("message",e._onmessage),e._onmessage=void 0),e._onkeystatuseschange&&(t.removeEventListener("keystatuseschange",e._onkeystatuseschange),e._onkeystatuseschange=void 0),i&&i.readyState!==XMLHttpRequest.DONE&&i.abort(),e.mediaKeysSession=e.decryptdata=e.licenseXhr=void 0;let n=this.mediaKeySessions.indexOf(e);n>-1&&this.mediaKeySessions.splice(n,1);let{keyStatusTimeouts:a}=e;a&&Object.keys(a).forEach(d=>self.clearTimeout(a[d]));let{drmSystemOptions:o}=this.config;return (iy(o)?new Promise((d,c)=>{self.setTimeout(()=>c(new Error("MediaKeySession.remove() timeout")),8e3),t.remove().then(d).catch(c);}):Promise.resolve()).catch(d=>{this.log(`Could not remove session: ${d}`),this.hls&&this.hls.trigger(g.ERROR,{type:z.OTHER_ERROR,details:x.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR,fatal:false,error:new Error(`Could not remove session: ${d}`)});}).then(()=>t.close()).catch(d=>{this.log(`Could not close session: ${d}`),this.hls&&this.hls.trigger(g.ERROR,{type:z.OTHER_ERROR,details:x.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:false,error:new Error(`Could not close session: ${d}`)});})}return Promise.resolve()}};nl.CDMCleanupPromise=void 0;function xo(s){if(!s)throw new Error("Could not read keyId of undefined decryptdata");if(s.keyId===null)throw new Error("keyId is null");return rt(s.keyId)}function sA(s,e){if(s.keyId&&e.mediaKeysSession.keyStatuses.has(s.keyId))return e.mediaKeysSession.keyStatuses.get(s.keyId);if(s.matches(e.decryptdata))return e.keyStatus}var st=class extends Error{constructor(e,t){super(t),this.data=void 0,e.error||(e.error=new Error(t)),this.data=e,e.err=e.error;}};function ug(s,e){let t=s==="output-restricted",i=t?x.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:x.KEY_SYSTEM_STATUS_INTERNAL_ERROR;return new st({type:z.KEY_SYSTEM_ERROR,details:i,fatal:false,decryptdata:e},t?"HDCP level output restricted":`key status changed to "${s}"`)}var ru=class{constructor(e){this.hls=void 0,this.isVideoPlaybackQualityAvailable=false,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(g.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.on(g.MEDIA_DETACHING,this.onMediaDetaching,this);}unregisterListeners(){this.hls.off(g.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.off(g.MEDIA_DETACHING,this.onMediaDetaching,this);}destroy(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=false,this.media=null;}onMediaAttaching(e,t){let i=this.hls.config;if(i.capLevelOnFPSDrop){let r=t.media instanceof self.HTMLVideoElement?t.media:null;this.media=r,r&&typeof r.getVideoPlaybackQuality=="function"&&(this.isVideoPlaybackQualityAvailable=true),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),i.fpsDroppedMonitoringPeriod);}}onMediaDetaching(){this.media=null;}checkFPS(e,t,i){let r=performance.now();if(t){if(this.lastTime){let n=r-this.lastTime,a=i-this.lastDroppedFrames,o=t-this.lastDecodedFrames,l=1e3*a/n,d=this.hls;if(d.trigger(g.FPS_DROP,{currentDropped:a,currentDecoded:o,totalDroppedFrames:i}),l>0&&a>d.config.fpsDroppedMonitoringThreshold*o){let c=d.currentLevel;d.logger.warn("drop FPS ratio greater than max allowed value for currentLevel: "+c),c>0&&(d.autoLevelCapping===-1||d.autoLevelCapping>=c)&&(c=c-1,d.trigger(g.FPS_DROP_LEVEL_CAPPING,{level:c,droppedLevel:d.currentLevel}),d.autoLevelCapping=c,this.streamController.nextLevelSwitch());}}this.lastTime=r,this.lastDroppedFrames=i,this.lastDecodedFrames=t;}}checkFPSInterval(){let e=this.media;if(e)if(this.isVideoPlaybackQualityAvailable){let t=e.getVideoPlaybackQuality();this.checkFPS(e,t.totalVideoFrames,t.droppedVideoFrames);}else this.checkFPS(e,e.webkitDecodedFrameCount,e.webkitDroppedFrameCount);}};function Pp(s,e){let t;try{t=new Event("addtrack");}catch{t=document.createEvent("Event"),t.initEvent("addtrack",false,false);}t.track=s,e.dispatchEvent(t);}function wp(s,e){let t=s.mode;if(t==="disabled"&&(s.mode="hidden"),s.cues&&!s.cues.getCueById(e.id))try{if(s.addCue(e),!s.cues.getCueById(e.id))throw new Error(`addCue is failed for: ${e}`)}catch(i){Te.debug(`[texttrack-utils]: ${i}`);try{let r=new self.TextTrackCue(e.startTime,e.endTime,e.text);r.id=e.id,s.addCue(r);}catch(r){Te.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${r}`);}}t==="disabled"&&(s.mode=t);}function er(s,e){let t=s.mode;if(t==="disabled"&&(s.mode="hidden"),s.cues)for(let i=s.cues.length;i--;)e&&s.cues[i].removeEventListener("enter",e),s.removeCue(s.cues[i]);t==="disabled"&&(s.mode=t);}function nu(s,e,t,i){let r=s.mode;if(r==="disabled"&&(s.mode="hidden"),s.cues&&s.cues.length>0){let n=nA(s.cues,e,t);for(let a=0;a<n.length;a++)(!i||i(n[a]))&&s.removeCue(n[a]);}r==="disabled"&&(s.mode=r);}function rA(s,e){if(e<=s[0].startTime)return 0;let t=s.length-1;if(e>s[t].endTime)return -1;let i=0,r=t,n;for(;i<=r;)if(n=Math.floor((r+i)/2),e<s[n].startTime)r=n-1;else if(e>s[n].startTime&&i<t)i=n+1;else return n;return s[i].startTime-e<e-s[r].startTime?i:r}function nA(s,e,t){let i=[],r=rA(s,e);if(r>-1)for(let n=r,a=s.length;n<a;n++){let o=s[n];if(o.startTime>=e&&o.endTime<=t)i.push(o);else if(o.startTime>t)return i}return i}function Uo(s){let e=[];for(let t=0;t<s.length;t++){let i=s[t];(i.kind==="subtitles"||i.kind==="captions")&&i.label&&e.push(s[t]);}return e}var au=class extends In{constructor(e){super(e,"subtitle-track-controller"),this.media=null,this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=true,this.queuedDefaultTrack=-1,this.useTextTrackPolling=false,this.subtitlePollingInterval=-1,this._subtitleDisplay=true,this.asyncPollTrackChange=()=>this.pollTrackChange(0),this.onTextTracksChanged=()=>{if(this.useTextTrackPolling||self.clearInterval(this.subtitlePollingInterval),!this.media||!this.hls.config.renderTextTracksNatively)return;let t=null,i=Uo(this.media.textTracks);for(let n=0;n<i.length;n++)if(i[n].mode==="hidden")t=i[n];else if(i[n].mode==="showing"){t=i[n];break}let r=this.findTrackForTextTrack(t);this.subtitleTrack!==r&&this.setSubtitleTrack(r);},this.registerListeners();}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,this.onTextTracksChanged=this.asyncPollTrackChange=null,super.destroy();}get subtitleDisplay(){return this._subtitleDisplay}set subtitleDisplay(e){this._subtitleDisplay=e,this.trackId>-1&&this.toggleTrackModes();}registerListeners(){let{hls:e}=this;e.on(g.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(g.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(g.MANIFEST_LOADING,this.onManifestLoading,this),e.on(g.MANIFEST_PARSED,this.onManifestParsed,this),e.on(g.LEVEL_LOADING,this.onLevelLoading,this),e.on(g.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(g.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(g.ERROR,this.onError,this);}unregisterListeners(){let{hls:e}=this;e.off(g.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(g.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(g.MANIFEST_LOADING,this.onManifestLoading,this),e.off(g.MANIFEST_PARSED,this.onManifestParsed,this),e.off(g.LEVEL_LOADING,this.onLevelLoading,this),e.off(g.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(g.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(g.ERROR,this.onError,this);}onMediaAttached(e,t){this.media=t.media,this.media&&(this.queuedDefaultTrack>-1&&(this.subtitleTrack=this.queuedDefaultTrack,this.queuedDefaultTrack=-1),this.useTextTrackPolling=!(this.media.textTracks&&"onchange"in this.media.textTracks),this.useTextTrackPolling?this.pollTrackChange(500):this.media.textTracks.addEventListener("change",this.asyncPollTrackChange));}pollTrackChange(e){self.clearInterval(this.subtitlePollingInterval),this.subtitlePollingInterval=self.setInterval(this.onTextTracksChanged,e);}onMediaDetaching(e,t){let i=this.media;if(!i)return;let r=!!t.transferMedia;if(self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||i.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId),this.subtitleTrack=-1,this.media=null,r)return;Uo(i.textTracks).forEach(a=>{er(a);});}onManifestLoading(){this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=true;}onManifestParsed(e,t){this.tracks=t.subtitleTracks;}onSubtitleTrackLoaded(e,t){let{id:i,groupId:r,details:n}=t,a=this.tracksInGroup[i];if(!a||a.groupId!==r){this.warn(`Subtitle track with id:${i} and group:${r} not found in active group ${a?.groupId}`);return}let o=a.details;a.details=t.details,this.log(`Subtitle track ${i} "${a.name}" lang:${a.lang} group:${r} loaded [${n.startSN}-${n.endSN}]`),i===this.trackId&&this.playlistLoaded(i,t,o);}onLevelLoading(e,t){this.switchLevel(t.level);}onLevelSwitching(e,t){this.switchLevel(t.level);}switchLevel(e){let t=this.hls.levels[e];if(!t)return;let i=t.subtitleGroups||null,r=this.groupIds,n=this.currentTrack;if(!i||r?.length!==i?.length||i!=null&&i.some(a=>r?.indexOf(a)===-1)){this.groupIds=i,this.trackId=-1,this.currentTrack=null;let a=this.tracks.filter(c=>!i||i.indexOf(c.groupId)!==-1);if(a.length)this.selectDefaultTrack&&!a.some(c=>c.default)&&(this.selectDefaultTrack=false),a.forEach((c,u)=>{c.id=u;});else if(!n&&!this.tracksInGroup.length)return;this.tracksInGroup=a;let o=this.hls.config.subtitlePreference;if(!n&&o){this.selectDefaultTrack=false;let c=di(o,a);if(c>-1)n=a[c];else {let u=di(o,this.tracks);n=this.tracks[u];}}let l=this.findTrackId(n);l===-1&&n&&(l=this.findTrackId(null));let d={subtitleTracks:a};this.log(`Updating subtitle tracks, ${a.length} track(s) found in "${i?.join(",")}" group-id`),this.hls.trigger(g.SUBTITLE_TRACKS_UPDATED,d),l!==-1&&this.trackId===-1&&this.setSubtitleTrack(l);}}findTrackId(e){let t=this.tracksInGroup,i=this.selectDefaultTrack;for(let r=0;r<t.length;r++){let n=t[r];if(!(i&&!n.default||!i&&!e)&&(!e||os(n,e)))return r}if(e){for(let r=0;r<t.length;r++){let n=t[r];if(Ln(e.attrs,n.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return r}for(let r=0;r<t.length;r++){let n=t[r];if(Ln(e.attrs,n.attrs,["LANGUAGE"]))return r}}return -1}findTrackForTextTrack(e){if(e){let t=this.tracksInGroup;for(let i=0;i<t.length;i++){let r=t[i];if(qc(r,e))return i}}return -1}onError(e,t){t.fatal||!t.context||t.context.type===ce.SUBTITLE_TRACK&&t.context.id===this.trackId&&(!this.groupIds||this.groupIds.indexOf(t.context.groupId)!==-1)&&this.checkRetry(t);}get allSubtitleTracks(){return this.tracks}get subtitleTracks(){return this.tracksInGroup}get subtitleTrack(){return this.trackId}set subtitleTrack(e){this.selectDefaultTrack=false,this.setSubtitleTrack(e);}setSubtitleOption(e){if(this.hls.config.subtitlePreference=e,e){if(e.id===-1)return this.setSubtitleTrack(-1),null;let t=this.allSubtitleTracks;if(this.selectDefaultTrack=false,t.length){let i=this.currentTrack;if(i&&os(e,i))return i;let r=di(e,this.tracksInGroup);if(r>-1){let n=this.tracksInGroup[r];return this.setSubtitleTrack(r),n}else {if(i)return null;{let n=di(e,t);if(n>-1)return t[n]}}}}return null}loadPlaylist(e){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentTrack)&&this.scheduleLoading(this.currentTrack,e);}loadingPlaylist(e,t){super.loadingPlaylist(e,t);let i=e.id,r=e.groupId,n=this.getUrlWithDirectives(e.url,t),a=e.details,o=a?.age;this.log(`Loading subtitle ${i} "${e.name}" lang:${e.lang} group:${r}${t?.msn!==void 0?" at sn "+t.msn+" part "+t.part:""}${o&&a.live?" age "+o.toFixed(1)+(a.type&&" "+a.type||""):""} ${n}`),this.hls.trigger(g.SUBTITLE_TRACK_LOADING,{url:n,id:i,groupId:r,deliveryDirectives:t||null,track:e});}toggleTrackModes(){let{media:e}=this;if(!e)return;let t=Uo(e.textTracks),i=this.currentTrack,r;if(i&&(r=t.filter(n=>qc(i,n))[0],r||this.warn(`Unable to find subtitle TextTrack with name "${i.name}" and language "${i.lang}"`)),[].slice.call(t).forEach(n=>{n.mode!=="disabled"&&n!==r&&(n.mode="disabled");}),r){let n=this.subtitleDisplay?"showing":"hidden";r.mode!==n&&(r.mode=n);}}setSubtitleTrack(e){let t=this.tracksInGroup;if(!this.media){this.queuedDefaultTrack=e;return}if(e<-1||e>=t.length||!G(e)){this.warn(`Invalid subtitle track id: ${e}`);return}this.selectDefaultTrack=false;let i=this.currentTrack,r=t[e]||null;if(this.trackId=e,this.currentTrack=r,this.toggleTrackModes(),!r){this.hls.trigger(g.SUBTITLE_TRACK_SWITCH,{id:e});return}let n=!!r.details&&!r.details.live;if(e===this.trackId&&r===i&&n)return;this.log(`Switching to subtitle-track ${e}`+(r?` "${r.name}" lang:${r.lang} group:${r.groupId}`:""));let{id:a,groupId:o="",name:l,type:d,url:c}=r;this.hls.trigger(g.SUBTITLE_TRACK_SWITCH,{id:a,groupId:o,name:l,type:d,url:c});let u=this.switchParams(r.url,i?.details,r.details);this.loadPlaylist(u);}};function aA(){try{return crypto.randomUUID()}catch{try{let e=URL.createObjectURL(new Blob),t=e.toString();return URL.revokeObjectURL(e),t.slice(t.lastIndexOf("/")+1)}catch{let t=new Date().getTime();return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,r=>{let n=(t+Math.random()*16)%16|0;return t=Math.floor(t/16),(r=="x"?n:n&3|8).toString(16)})}}}function hn(s){let e=5381,t=s.length;for(;t;)e=e*33^s.charCodeAt(--t);return (e>>>0).toString()}var nr=.025,al=function(s){return s[s.Point=0]="Point",s[s.Range=1]="Range",s}({});function oA(s,e,t){return `${s.identifier}-${t+1}-${hn(e)}`}var ou=class{constructor(e,t){this.base=void 0,this._duration=null,this._timelineStart=null,this.appendInPlaceDisabled=void 0,this.appendInPlaceStarted=void 0,this.dateRange=void 0,this.hasPlayed=false,this.cumulativeDuration=0,this.resumeOffset=NaN,this.playoutLimit=NaN,this.restrictions={skip:false,jump:false},this.snapOptions={out:false,in:false},this.assetList=[],this.assetListLoader=void 0,this.assetListResponse=null,this.resumeAnchor=void 0,this.error=void 0,this.resetOnResume=void 0,this.base=t,this.dateRange=e,this.setDateRange(e);}setDateRange(e){this.dateRange=e,this.resumeOffset=e.attr.optionalFloat("X-RESUME-OFFSET",this.resumeOffset),this.playoutLimit=e.attr.optionalFloat("X-PLAYOUT-LIMIT",this.playoutLimit),this.restrictions=e.attr.enumeratedStringList("X-RESTRICT",this.restrictions),this.snapOptions=e.attr.enumeratedStringList("X-SNAP",this.snapOptions);}reset(){var e;this.appendInPlaceStarted=false,(e=this.assetListLoader)==null||e.destroy(),this.assetListLoader=void 0,this.supplementsPrimary||(this.assetListResponse=null,this.assetList=[],this._duration=null);}isAssetPastPlayoutLimit(e){var t;if(e>0&&e>=this.assetList.length)return true;let i=this.playoutLimit;return e<=0||isNaN(i)?false:i===0?true:(((t=this.assetList[e])==null?void 0:t.startOffset)||0)>i}findAssetIndex(e){return this.assetList.indexOf(e)}get identifier(){return this.dateRange.id}get startDate(){return this.dateRange.startDate}get startTime(){let e=this.dateRange.startTime;if(this.snapOptions.out){let t=this.dateRange.tagAnchor;if(t)return sc(e,t)}return e}get startOffset(){return this.cue.pre?0:this.startTime}get startIsAligned(){if(this.startTime===0||this.snapOptions.out)return true;let e=this.dateRange.tagAnchor;if(e){let t=this.dateRange.startTime,i=sc(t,e);return t-i<.1}return false}get resumptionOffset(){let e=this.resumeOffset,t=G(e)?e:this.duration;return this.cumulativeDuration+t}get resumeTime(){let e=this.startOffset+this.resumptionOffset;if(this.snapOptions.in){let t=this.resumeAnchor;if(t)return sc(e,t)}return e}get appendInPlace(){return this.appendInPlaceStarted?true:this.appendInPlaceDisabled?false:!!(!this.cue.once&&!this.cue.pre&&this.startIsAligned&&(isNaN(this.playoutLimit)&&isNaN(this.resumeOffset)||this.resumeOffset&&this.duration&&Math.abs(this.resumeOffset-this.duration)<nr))}set appendInPlace(e){if(this.appendInPlaceStarted){this.resetOnResume=!e;return}this.appendInPlaceDisabled=!e;}get timelineStart(){return this._timelineStart!==null?this._timelineStart:this.startTime}set timelineStart(e){this._timelineStart=e;}get duration(){let e=this.playoutLimit,t;return this._duration!==null?t=this._duration:this.dateRange.duration?t=this.dateRange.duration:t=this.dateRange.plannedDuration||0,!isNaN(e)&&e<t&&(t=e),t}set duration(e){this._duration=e;}get cue(){return this.dateRange.cue}get timelineOccupancy(){return this.dateRange.attr["X-TIMELINE-OCCUPIES"]==="RANGE"?al.Range:al.Point}get supplementsPrimary(){return this.dateRange.attr["X-TIMELINE-STYLE"]==="PRIMARY"}get contentMayVary(){return this.dateRange.attr["X-CONTENT-MAY-VARY"]!=="NO"}get assetUrl(){return this.dateRange.attr["X-ASSET-URI"]}get assetListUrl(){return this.dateRange.attr["X-ASSET-LIST"]}get baseUrl(){return this.base.url}get assetListLoaded(){return this.assetList.length>0||this.assetListResponse!==null}toString(){return lA(this)}};function sc(s,e){return s-e.start<e.duration/2&&!(Math.abs(s-(e.start+e.duration))<nr)?e.start:e.start+e.duration}function Op(s,e,t){let i=new self.URL(s,t);return i.protocol!=="data:"&&i.searchParams.set("_HLS_primary_id",e),i}function rc(s,e){for(;(t=s.assetList[++e])!=null&&t.error;)var t;return e}function lA(s){return `["${s.identifier}" ${s.cue.pre?"<pre>":s.cue.post?"<post>":""}${s.timelineStart.toFixed(2)}-${s.resumeTime.toFixed(2)}]`}function Js(s){let e=s.timelineStart,t=s.duration||0;return `["${s.identifier}" ${e.toFixed(2)}-${(e+t).toFixed(2)}]`}var lu=class{constructor(e,t,i,r){this.hls=void 0,this.interstitial=void 0,this.assetItem=void 0,this.tracks=null,this.hasDetails=false,this.mediaAttached=null,this._currentTime=void 0,this._bufferedEosTime=void 0,this.checkPlayout=()=>{this.reachedPlayout(this.currentTime)&&this.hls&&this.hls.trigger(g.PLAYOUT_LIMIT_REACHED,{});};let n=this.hls=new e(t);this.interstitial=i,this.assetItem=r;let a=()=>{this.hasDetails=true;};n.once(g.LEVEL_LOADED,a),n.once(g.AUDIO_TRACK_LOADED,a),n.once(g.SUBTITLE_TRACK_LOADED,a),n.on(g.MEDIA_ATTACHING,(o,{media:l})=>{this.removeMediaListeners(),this.mediaAttached=l,this.interstitial.playoutLimit&&(l.addEventListener("timeupdate",this.checkPlayout),this.appendInPlace&&n.on(g.BUFFER_APPENDED,()=>{let c=this.bufferedEnd;this.reachedPlayout(c)&&(this._bufferedEosTime=c,n.trigger(g.BUFFERED_TO_END,void 0));}));});}get appendInPlace(){return this.interstitial.appendInPlace}loadSource(){let e=this.hls;if(e)if(e.url)e.levels.length&&!e.started&&e.startLoad(-1,true);else {let t=this.assetItem.uri;try{t=Op(t,e.config.primarySessionId||"").href;}catch{}e.loadSource(t);}}bufferedInPlaceToEnd(e){var t;if(!this.appendInPlace)return false;if((t=this.hls)!=null&&t.bufferedToEnd)return true;if(!e)return false;let i=Math.min(this._bufferedEosTime||1/0,this.duration),r=this.timelineOffset,n=re.bufferInfo(e,r,0);return this.getAssetTime(n.end)>=i-.02}reachedPlayout(e){let i=this.interstitial.playoutLimit;return this.startOffset+e>=i}get destroyed(){var e;return !((e=this.hls)!=null&&e.userConfig)}get assetId(){return this.assetItem.identifier}get interstitialId(){return this.assetItem.parentIdentifier}get media(){var e;return ((e=this.hls)==null?void 0:e.media)||null}get bufferedEnd(){let e=this.media||this.mediaAttached;if(!e)return this._bufferedEosTime?this._bufferedEosTime:this.currentTime;let t=re.bufferInfo(e,e.currentTime,.001);return this.getAssetTime(t.end)}get currentTime(){let e=this.media||this.mediaAttached;return e?this.getAssetTime(e.currentTime):this._currentTime||0}get duration(){let e=this.assetItem.duration;if(!e)return 0;let t=this.interstitial.playoutLimit;if(t){let i=t-this.startOffset;if(i>0&&i<e)return i}return e}get remaining(){let e=this.duration;return e?Math.max(0,e-this.currentTime):0}get startOffset(){return this.assetItem.startOffset}get timelineOffset(){var e;return ((e=this.hls)==null?void 0:e.config.timelineOffset)||0}set timelineOffset(e){let t=this.timelineOffset;if(e!==t){let i=e-t;if(Math.abs(i)>1/9e4&&this.hls){if(this.hasDetails)throw new Error("Cannot set timelineOffset after playlists are loaded");this.hls.config.timelineOffset=e;}}}getAssetTime(e){let t=this.timelineOffset,i=this.duration;return Math.min(Math.max(0,e-t),i)}removeMediaListeners(){let e=this.mediaAttached;e&&(this._currentTime=e.currentTime,this.bufferSnapShot(),e.removeEventListener("timeupdate",this.checkPlayout));}bufferSnapShot(){if(this.mediaAttached){var e;(e=this.hls)!=null&&e.bufferedToEnd&&(this._bufferedEosTime=this.bufferedEnd);}}destroy(){this.removeMediaListeners(),this.hls&&this.hls.destroy(),this.hls=null,this.tracks=this.mediaAttached=this.checkPlayout=null;}attachMedia(e){var t;this.loadSource(),(t=this.hls)==null||t.attachMedia(e);}detachMedia(){var e;this.removeMediaListeners(),this.mediaAttached=null,(e=this.hls)==null||e.detachMedia();}resumeBuffering(){var e;(e=this.hls)==null||e.resumeBuffering();}pauseBuffering(){var e;(e=this.hls)==null||e.pauseBuffering();}transferMedia(){var e;return this.bufferSnapShot(),((e=this.hls)==null?void 0:e.transferMedia())||null}resetDetails(){let e=this.hls;if(e&&this.hasDetails){e.stopLoad();let t=i=>delete i.details;e.levels.forEach(t),e.allAudioTracks.forEach(t),e.allSubtitleTracks.forEach(t),this.hasDetails=false;}}on(e,t,i){var r;(r=this.hls)==null||r.on(e,t);}once(e,t,i){var r;(r=this.hls)==null||r.once(e,t);}off(e,t,i){var r;(r=this.hls)==null||r.off(e,t);}toString(){var e;return `HlsAssetPlayer: ${Js(this.assetItem)} ${(e=this.hls)==null?void 0:e.sessionId} ${this.appendInPlace?"append-in-place":""}`}},hg=.033,du=class extends ht{constructor(e,t){super("interstitials-sched",t),this.onScheduleUpdate=void 0,this.eventMap={},this.events=null,this.items=null,this.durations={primary:0,playout:0,integrated:0},this.onScheduleUpdate=e;}destroy(){this.reset(),this.onScheduleUpdate=null;}reset(){this.eventMap={},this.setDurations(0,0,0),this.events&&this.events.forEach(e=>e.reset()),this.events=this.items=null;}resetErrorsInRange(e,t){return this.events?this.events.reduce((i,r)=>e<=r.startOffset&&t>r.startOffset?(delete r.error,i+1):i,0):0}get duration(){let e=this.items;return e?e[e.length-1].end:0}get length(){return this.items?this.items.length:0}getEvent(e){return e&&this.eventMap[e]||null}hasEvent(e){return e in this.eventMap}findItemIndex(e,t){if(e.event)return this.findEventIndex(e.event.identifier);let i=-1;e.nextEvent?i=this.findEventIndex(e.nextEvent.identifier)-1:e.previousEvent&&(i=this.findEventIndex(e.previousEvent.identifier)+1);let r=this.items;if(r)for(r[i]||(t===void 0&&(t=e.start),i=this.findItemIndexAtTime(t));i>=0&&(n=r[i])!=null&&n.event;){var n;i--;}return i}findItemIndexAtTime(e,t){let i=this.items;if(i)for(let r=0;r<i.length;r++){let n=i[r];if(t&&t!=="primary"&&(n=n[t]),e===n.start||e>n.start&&e<n.end)return r}return -1}findJumpRestrictedIndex(e,t){let i=this.items;if(i)for(let r=e;r<=t&&i[r];r++){let n=i[r].event;if(n!=null&&n.restrictions.jump&&!n.appendInPlace)return r}return -1}findEventIndex(e){let t=this.items;if(t)for(let r=t.length;r--;){var i;if(((i=t[r].event)==null?void 0:i.identifier)===e)return r}return -1}findAssetIndex(e,t){let i=e.assetList,r=i.length;if(r>1)for(let n=0;n<r;n++){let a=i[n];if(!a.error){let o=a.timelineStart;if(t===o||t>o&&(t<o+(a.duration||0)||n===r-1))return n}}return 0}get assetIdAtEnd(){var e;let t=(e=this.items)==null||(e=e[this.length-1])==null?void 0:e.event;if(t){let i=t.assetList,r=i[i.length-1];if(r)return r.identifier}return null}parseInterstitialDateRanges(e,t){let i=e.main.details,{dateRanges:r}=i,n=this.events,a=this.parseDateRanges(r,{url:i.url},t),o=Object.keys(r),l=n?n.filter(d=>!o.includes(d.identifier)):[];a.length&&a.sort((d,c)=>{let u=d.cue.pre,h=d.cue.post,f=c.cue.pre,m=c.cue.post;if(u&&!f)return -1;if(f&&!u||h&&!m)return 1;if(m&&!h)return -1;if(!u&&!f&&!h&&!m){let p=d.startTime,E=c.startTime;if(p!==E)return p-E}return d.dateRange.tagOrder-c.dateRange.tagOrder}),this.events=a,l.forEach(d=>{this.removeEvent(d);}),this.updateSchedule(e,l);}updateSchedule(e,t=[],i=false){let r=this.events||[];if(r.length||t.length||this.length<2){let n=this.items,a=this.parseSchedule(r,e);(i||t.length||n?.length!==a.length||a.some((l,d)=>Math.abs(l.playout.start-n[d].playout.start)>.005||Math.abs(l.playout.end-n[d].playout.end)>.005))&&(this.items=a,this.onScheduleUpdate(t,n));}}parseDateRanges(e,t,i){let r=[],n=Object.keys(e);for(let a=0;a<n.length;a++){let o=n[a],l=e[o];if(l.isInterstitial){let d=this.eventMap[o];d?d.setDateRange(l):(d=new ou(l,t),this.eventMap[o]=d,i===false&&(d.appendInPlace=i)),r.push(d);}}return r}parseSchedule(e,t){let i=[],r=t.main.details,n=r.live?1/0:r.edge,a=0;if(e=e.filter(l=>!l.error&&!(l.cue.once&&l.hasPlayed)),e.length){this.resolveOffsets(e,t);let l=0,d=0;if(e.forEach((c,u)=>{let h=c.cue.pre,f=c.cue.post,m=e[u-1]||null,p=c.appendInPlace,E=f?n:c.startOffset,v=c.duration,T=c.timelineOccupancy===al.Range?v:0,S=c.resumptionOffset,A=m?.startTime===E,b=E+c.cumulativeDuration,D=p?b+v:E+S;if(h||!f&&E<=0){let k=d;d+=T,c.timelineStart=b;let R=a;a+=v,i.push({event:c,start:b,end:D,playout:{start:R,end:a},integrated:{start:k,end:d}});}else if(E<=n){if(!A){let L=E-l;if(L>hg){let M=l,B=d;d+=L;let K=a;a+=L;let j={previousEvent:e[u-1]||null,nextEvent:c,start:M,end:M+L,playout:{start:K,end:a},integrated:{start:B,end:d}};i.push(j);}else L>0&&m&&(m.cumulativeDuration+=L,i[i.length-1].end=E);}f&&(D=b),c.timelineStart=b;let k=d;d+=T;let R=a;a+=v,i.push({event:c,start:b,end:D,playout:{start:R,end:a},integrated:{start:k,end:d}});}else return;let I=c.resumeTime;f||I>n?l=n:l=I;}),l<n){var o;let c=l,u=d,h=n-l;d+=h;let f=a;a+=h,i.push({previousEvent:((o=i[i.length-1])==null?void 0:o.event)||null,nextEvent:null,start:l,end:c+h,playout:{start:f,end:a},integrated:{start:u,end:d}});}this.setDurations(n,a,d);}else i.push({previousEvent:null,nextEvent:null,start:0,end:n,playout:{start:0,end:n},integrated:{start:0,end:n}}),this.setDurations(n,n,n);return i}setDurations(e,t,i){this.durations={primary:e,playout:t,integrated:i};}resolveOffsets(e,t){let i=t.main.details,r=i.live?1/0:i.edge,n=0,a=-1;e.forEach((o,l)=>{let d=o.cue.pre,c=o.cue.post,u=d?0:c?r:o.startTime;this.updateAssetDurations(o),a===u?o.cumulativeDuration=n:(n=0,a=u),!c&&o.snapOptions.in&&(o.resumeAnchor=cs(null,i.fragments,o.startOffset+o.resumptionOffset,0,0)||void 0),o.appendInPlace&&!o.appendInPlaceStarted&&(this.primaryCanResumeInPlaceAt(o,t)||(o.appendInPlace=false)),!o.appendInPlace&&l+1<e.length&&e[l+1].startTime-e[l].resumeTime<hg&&(e[l+1].appendInPlace=false,e[l+1].appendInPlace&&this.warn(`Could not change append strategy for abutting event ${o}`));let f=G(o.resumeOffset)?o.resumeOffset:o.duration;n+=f;});}primaryCanResumeInPlaceAt(e,t){let i=e.resumeTime,r=e.startTime+e.resumptionOffset;return Math.abs(i-r)>nr?(this.log(`"${e.identifier}" resumption ${i} not aligned with estimated timeline end ${r}`),false):!Object.keys(t).some(a=>{let o=t[a].details,l=o.edge;if(i>=l)return this.log(`"${e.identifier}" resumption ${i} past ${a} playlist end ${l}`),false;let d=cs(null,o.fragments,i);if(!d)return this.log(`"${e.identifier}" resumption ${i} does not align with any fragments in ${a} playlist (${o.fragStart}-${o.fragmentEnd})`),true;let c=a==="audio"?.175:0;return Math.abs(d.start-i)<nr+c||Math.abs(d.end-i)<nr+c?false:(this.log(`"${e.identifier}" resumption ${i} not aligned with ${a} fragment bounds (${d.start}-${d.end} sn: ${d.sn} cc: ${d.cc})`),true)})}updateAssetDurations(e){if(!e.assetListLoaded)return;let t=e.timelineStart,i=0,r=false,n=false;for(let a=0;a<e.assetList.length;a++){let o=e.assetList[a],l=t+i;o.startOffset=i,o.timelineStart=l,r||(r=o.duration===null),n||(n=!!o.error);let d=o.error?0:o.duration||0;i+=d;}r&&!n?e.duration=Math.max(i,e.duration):e.duration=i;}removeEvent(e){e.reset(),delete this.eventMap[e.identifier];}};function $t(s){return `[${s.event?'"'+s.event.identifier+'"':"primary"}: ${s.start.toFixed(2)}-${s.end.toFixed(2)}]`}var cu=class{constructor(e){this.hls=void 0,this.hls=e;}destroy(){this.hls=null;}loadAssetList(e,t){let i=e.assetListUrl,r;try{r=Op(i,this.hls.sessionId,e.baseUrl);}catch(h){let f=this.assignAssetListError(e,x.ASSET_LIST_LOAD_ERROR,h,i);this.hls.trigger(g.ERROR,f);return}t&&r.protocol!=="data:"&&r.searchParams.set("_HLS_start_offset",""+t);let n=this.hls.config,a=n.loader,o=new a(n),l={responseType:"json",url:r.href},d=n.interstitialAssetListLoadPolicy.default,c={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},u={onSuccess:(h,f,m,p)=>{let E=h.data,v=E?.ASSETS;if(!Array.isArray(v)){let T=this.assignAssetListError(e,x.ASSET_LIST_PARSING_ERROR,new Error("Invalid interstitial asset list"),m.url,f,p);this.hls.trigger(g.ERROR,T);return}e.assetListResponse=E,this.hls.trigger(g.ASSET_LIST_LOADED,{event:e,assetListResponse:E,networkDetails:p});},onError:(h,f,m,p)=>{let E=this.assignAssetListError(e,x.ASSET_LIST_LOAD_ERROR,new Error(`Error loading X-ASSET-LIST: HTTP status ${h.code} ${h.text} (${f.url})`),f.url,p,m);this.hls.trigger(g.ERROR,E);},onTimeout:(h,f,m)=>{let p=this.assignAssetListError(e,x.ASSET_LIST_LOAD_TIMEOUT,new Error(`Timeout loading X-ASSET-LIST (${f.url})`),f.url,h,m);this.hls.trigger(g.ERROR,p);}};return o.load(l,c,u),this.hls.trigger(g.ASSET_LIST_LOADING,{event:e}),o}assignAssetListError(e,t,i,r,n,a){return e.error=i,{type:z.NETWORK_ERROR,details:t,fatal:false,interstitial:e,url:r,error:i,networkDetails:a,stats:n}}};function fg(s){s?.play().catch(()=>{});}function Ro(s,e){return `[${s}] Advancing timeline position to ${e}`}var uu=class extends ht{constructor(e,t){super("interstitials",e.logger),this.HlsPlayerClass=void 0,this.hls=void 0,this.assetListLoader=void 0,this.mediaSelection=null,this.altSelection=null,this.media=null,this.detachedData=null,this.requiredTracks=null,this.manager=null,this.playerQueue=[],this.bufferedPos=-1,this.timelinePos=-1,this.schedule=void 0,this.playingItem=null,this.bufferingItem=null,this.waitingItem=null,this.endedItem=null,this.playingAsset=null,this.endedAsset=null,this.bufferingAsset=null,this.shouldPlay=false,this.onPlay=()=>{this.shouldPlay=true;},this.onPause=()=>{this.shouldPlay=false;},this.onSeeking=()=>{let i=this.currentTime;if(i===void 0||this.playbackDisabled||!this.schedule)return;let r=i-this.timelinePos;if(Math.abs(r)<1/7056e5)return;let a=r<=-0.01;this.timelinePos=i,this.bufferedPos=i;let o=this.playingItem;if(!o){this.checkBuffer();return}if(a&&this.schedule.resetErrorsInRange(i,i-r)&&this.updateSchedule(true),this.checkBuffer(),a&&i<o.start||i>=o.end){var l;let f=this.findItemIndex(o),m=this.schedule.findItemIndexAtTime(i);if(m===-1&&(m=f+(a?-1:1),this.log(`seeked ${a?"back ":""}to position not covered by schedule ${i} (resolving from ${f} to ${m})`)),!this.isInterstitial(o)&&(l=this.media)!=null&&l.paused&&(this.shouldPlay=false),!a&&m>f){let p=this.schedule.findJumpRestrictedIndex(f+1,m);if(p>f){this.setSchedulePosition(p);return}}this.setSchedulePosition(m);return}let d=this.playingAsset;if(!d){if(this.playingLastItem&&this.isInterstitial(o)){let f=o.event.assetList[0];f&&(this.endedItem=this.playingItem,this.playingItem=null,this.setScheduleToAssetAtTime(i,f));}return}let c=d.timelineStart,u=d.duration||0;if(a&&i<c||i>=c+u){var h;(h=o.event)!=null&&h.appendInPlace&&(this.clearInterstitial(o.event,o),this.flushFrontBuffer(i)),this.setScheduleToAssetAtTime(i,d);}},this.onTimeupdate=()=>{let i=this.currentTime;if(i===void 0||this.playbackDisabled)return;if(i>this.timelinePos)this.timelinePos=i,i>this.bufferedPos&&this.checkBuffer();else return;let r=this.playingItem;if(!r||this.playingLastItem)return;if(i>=r.end){this.timelinePos=r.end;let o=this.findItemIndex(r);this.setSchedulePosition(o+1);}let n=this.playingAsset;if(!n)return;let a=n.timelineStart+(n.duration||0);i>=a&&this.setScheduleToAssetAtTime(i,n);},this.onScheduleUpdate=(i,r)=>{let n=this.schedule;if(!n)return;let a=this.playingItem,o=n.events||[],l=n.items||[],d=n.durations,c=i.map(p=>p.identifier),u=!!(o.length||c.length);(u||r)&&this.log(`INTERSTITIALS_UPDATED (${o.length}): ${o}
1377
+ Schedule: ${l.map(p=>$t(p))} pos: ${this.timelinePos}`),c.length&&this.log(`Removed events ${c}`);let h=null,f=null;a&&(h=this.updateItem(a,this.timelinePos),this.itemsMatch(a,h)?this.playingItem=h:this.waitingItem=this.endedItem=null),this.waitingItem=this.updateItem(this.waitingItem),this.endedItem=this.updateItem(this.endedItem);let m=this.bufferingItem;if(m&&(f=this.updateItem(m,this.bufferedPos),this.itemsMatch(m,f)?this.bufferingItem=f:m.event&&(this.bufferingItem=this.playingItem,this.clearInterstitial(m.event,null))),i.forEach(p=>{p.assetList.forEach(E=>{this.clearAssetPlayer(E.identifier,null);});}),this.playerQueue.forEach(p=>{if(p.interstitial.appendInPlace){let E=p.assetItem.timelineStart,v=p.timelineOffset-E;if(v)try{p.timelineOffset=E;}catch(T){Math.abs(v)>nr&&this.warn(`${T} ("${p.assetId}" ${p.timelineOffset}->${E})`);}}}),u||r){if(this.hls.trigger(g.INTERSTITIALS_UPDATED,{events:o.slice(0),schedule:l.slice(0),durations:d,removedIds:c}),this.isInterstitial(a)&&c.includes(a.event.identifier)){this.warn(`Interstitial "${a.event.identifier}" removed while playing`),this.primaryFallback(a.event);return}a&&this.trimInPlace(h,a),m&&f!==h&&this.trimInPlace(f,m),this.checkBuffer();}},this.hls=e,this.HlsPlayerClass=t,this.assetListLoader=new cu(e),this.schedule=new du(this.onScheduleUpdate,e.logger),this.registerListeners();}registerListeners(){let e=this.hls;e&&(e.on(g.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(g.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(g.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(g.MANIFEST_LOADING,this.onManifestLoading,this),e.on(g.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(g.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(g.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.on(g.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(g.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.on(g.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.on(g.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.on(g.BUFFER_APPENDED,this.onBufferAppended,this),e.on(g.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(g.BUFFERED_TO_END,this.onBufferedToEnd,this),e.on(g.MEDIA_ENDED,this.onMediaEnded,this),e.on(g.ERROR,this.onError,this),e.on(g.DESTROYING,this.onDestroying,this));}unregisterListeners(){let e=this.hls;e&&(e.off(g.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(g.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(g.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(g.MANIFEST_LOADING,this.onManifestLoading,this),e.off(g.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(g.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(g.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.off(g.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(g.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.off(g.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.off(g.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.off(g.BUFFER_CODECS,this.onBufferCodecs,this),e.off(g.BUFFER_APPENDED,this.onBufferAppended,this),e.off(g.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(g.BUFFERED_TO_END,this.onBufferedToEnd,this),e.off(g.MEDIA_ENDED,this.onMediaEnded,this),e.off(g.ERROR,this.onError,this),e.off(g.DESTROYING,this.onDestroying,this));}startLoad(){this.resumeBuffering();}stopLoad(){this.pauseBuffering();}resumeBuffering(){var e;(e=this.getBufferingPlayer())==null||e.resumeBuffering();}pauseBuffering(){var e;(e=this.getBufferingPlayer())==null||e.pauseBuffering();}destroy(){this.unregisterListeners(),this.stopLoad(),this.assetListLoader&&this.assetListLoader.destroy(),this.emptyPlayerQueue(),this.clearScheduleState(),this.schedule&&this.schedule.destroy(),this.media=this.detachedData=this.mediaSelection=this.requiredTracks=this.altSelection=this.schedule=this.manager=null,this.hls=this.HlsPlayerClass=this.log=null,this.assetListLoader=null,this.onPlay=this.onPause=this.onSeeking=this.onTimeupdate=null,this.onScheduleUpdate=null;}onDestroying(){let e=this.primaryMedia||this.media;e&&this.removeMediaListeners(e);}removeMediaListeners(e){ut(e,"play",this.onPlay),ut(e,"pause",this.onPause),ut(e,"seeking",this.onSeeking),ut(e,"timeupdate",this.onTimeupdate);}onMediaAttaching(e,t){let i=this.media=t.media;nt(i,"seeking",this.onSeeking),nt(i,"timeupdate",this.onTimeupdate),nt(i,"play",this.onPlay),nt(i,"pause",this.onPause);}onMediaAttached(e,t){let i=this.effectivePlayingItem,r=this.detachedData;if(this.detachedData=null,i===null)this.checkStart();else if(!r){this.clearScheduleState();let n=this.findItemIndex(i);this.setSchedulePosition(n);}}clearScheduleState(){this.log("clear schedule state"),this.playingItem=this.bufferingItem=this.waitingItem=this.endedItem=this.playingAsset=this.endedAsset=this.bufferingAsset=null;}onMediaDetaching(e,t){let i=!!t.transferMedia,r=this.media;if(this.media=null,!i&&(r&&this.removeMediaListeners(r),this.detachedData)){let n=this.getBufferingPlayer();n&&(this.log(`Removing schedule state for detachedData and ${n}`),this.playingAsset=this.endedAsset=this.bufferingAsset=this.bufferingItem=this.waitingItem=this.detachedData=null,n.detachMedia()),this.shouldPlay=false;}}get interstitialsManager(){if(!this.hls)return null;if(this.manager)return this.manager;let e=this,t=()=>e.bufferingItem||e.waitingItem,i=u=>u&&e.getAssetPlayer(u.identifier),r=(u,h,f,m,p)=>{if(u){let E=u[h].start,v=u.event;if(v){if(h==="playout"||v.timelineOccupancy!==al.Point){let T=i(f);T?.interstitial===v&&(E+=T.assetItem.startOffset+T[p]);}}else {let T=m==="bufferedPos"?a():e[m];E+=T-u.start;}return E}return 0},n=(u,h)=>{var f;if(u!==0&&h!=="primary"&&(f=e.schedule)!=null&&f.length){var m;let p=e.schedule.findItemIndexAtTime(u),E=(m=e.schedule.items)==null?void 0:m[p];if(E){let v=E[h].start-E.start;return u+v}}return u},a=()=>{let u=e.bufferedPos;return u===Number.MAX_VALUE?o("primary"):Math.max(u,0)},o=u=>{var h,f;return (h=e.primaryDetails)!=null&&h.live?e.primaryDetails.edge:((f=e.schedule)==null?void 0:f.durations[u])||0},l=(u,h)=>{var f,m;let p=e.effectivePlayingItem;if(p!=null&&(f=p.event)!=null&&f.restrictions.skip||!e.schedule)return;e.log(`seek to ${u} "${h}"`);let E=e.effectivePlayingItem,v=e.schedule.findItemIndexAtTime(u,h),T=(m=e.schedule.items)==null?void 0:m[v],S=e.getBufferingPlayer(),A=S?.interstitial,b=A?.appendInPlace,D=E&&e.itemsMatch(E,T);if(E&&(b||D)){let I=i(e.playingAsset),k=I?.media||e.primaryMedia;if(k){let R=h==="primary"?k.currentTime:r(E,h,e.playingAsset,"timelinePos","currentTime"),L=u-R,M=(b?R:k.currentTime)+L;if(M>=0&&(!I||b||M<=I.duration)){k.currentTime=M;return}}}if(T){let I=u;if(h!=="primary"){let R=T[h].start,L=u-R;I=T.start+L;}let k=!e.isInterstitial(T);if((!e.isInterstitial(E)||E.event.appendInPlace)&&(k||T.event.appendInPlace)){let R=e.media||(b?S?.media:null);R&&(R.currentTime=I);}else if(E){let R=e.findItemIndex(E);if(v>R){let M=e.schedule.findJumpRestrictedIndex(R+1,v);if(M>R){e.setSchedulePosition(M);return}}let L=0;if(k)e.timelinePos=I,e.checkBuffer();else {let M=T.event.assetList,B=u-(T[h]||T).start;for(let K=M.length;K--;){let j=M[K];if(j.duration&&B>=j.startOffset&&B<j.startOffset+j.duration){L=K;break}}}e.setSchedulePosition(v,L);}}},d=()=>{let u=e.effectivePlayingItem;if(e.isInterstitial(u))return u;let h=t();return e.isInterstitial(h)?h:null},c={get bufferedEnd(){let u=t(),h=e.bufferingItem;if(h&&h===u){var f;return r(h,"playout",e.bufferingAsset,"bufferedPos","bufferedEnd")-h.playout.start||((f=e.bufferingAsset)==null?void 0:f.startOffset)||0}return 0},get currentTime(){let u=d(),h=e.effectivePlayingItem;return h&&h===u?r(h,"playout",e.effectivePlayingAsset,"timelinePos","currentTime")-h.playout.start:0},set currentTime(u){let h=d(),f=e.effectivePlayingItem;f&&f===h&&l(u+f.playout.start,"playout");},get duration(){let u=d();return u?u.playout.end-u.playout.start:0},get assetPlayers(){var u;let h=(u=d())==null?void 0:u.event.assetList;return h?h.map(f=>e.getAssetPlayer(f.identifier)):[]},get playingIndex(){var u;let h=(u=d())==null?void 0:u.event;return h&&e.effectivePlayingAsset?h.findAssetIndex(e.effectivePlayingAsset):-1},get scheduleItem(){return d()}};return this.manager={get events(){var u;return ((u=e.schedule)==null||(u=u.events)==null?void 0:u.slice(0))||[]},get schedule(){var u;return ((u=e.schedule)==null||(u=u.items)==null?void 0:u.slice(0))||[]},get interstitialPlayer(){return d()?c:null},get playerQueue(){return e.playerQueue.slice(0)},get bufferingAsset(){return e.bufferingAsset},get bufferingItem(){return t()},get bufferingIndex(){let u=t();return e.findItemIndex(u)},get playingAsset(){return e.effectivePlayingAsset},get playingItem(){return e.effectivePlayingItem},get playingIndex(){let u=e.effectivePlayingItem;return e.findItemIndex(u)},primary:{get bufferedEnd(){return a()},get currentTime(){let u=e.timelinePos;return u>0?u:0},set currentTime(u){l(u,"primary");},get duration(){return o("primary")},get seekableStart(){var u;return ((u=e.primaryDetails)==null?void 0:u.fragmentStart)||0}},integrated:{get bufferedEnd(){return r(t(),"integrated",e.bufferingAsset,"bufferedPos","bufferedEnd")},get currentTime(){return r(e.effectivePlayingItem,"integrated",e.effectivePlayingAsset,"timelinePos","currentTime")},set currentTime(u){l(u,"integrated");},get duration(){return o("integrated")},get seekableStart(){var u;return n(((u=e.primaryDetails)==null?void 0:u.fragmentStart)||0,"integrated")}},skip:()=>{let u=e.effectivePlayingItem,h=u?.event;if(h&&!h.restrictions.skip){let f=e.findItemIndex(u);if(h.appendInPlace){let m=u.playout.start+u.event.duration;l(m+.001,"playout");}else e.advanceAfterAssetEnded(h,f,1/0);}}}}get effectivePlayingItem(){return this.waitingItem||this.playingItem||this.endedItem}get effectivePlayingAsset(){return this.playingAsset||this.endedAsset}get playingLastItem(){var e;let t=this.playingItem,i=(e=this.schedule)==null?void 0:e.items;return !this.playbackStarted||!t||!i?false:this.findItemIndex(t)===i.length-1}get playbackStarted(){return this.effectivePlayingItem!==null}get currentTime(){var e,t;if(this.mediaSelection===null)return;let i=this.waitingItem||this.playingItem;if(this.isInterstitial(i)&&!i.event.appendInPlace)return;let r=this.media;!r&&(e=this.bufferingItem)!=null&&(e=e.event)!=null&&e.appendInPlace&&(r=this.primaryMedia);let n=(t=r)==null?void 0:t.currentTime;if(!(n===void 0||!G(n)))return n}get primaryMedia(){var e;return this.media||((e=this.detachedData)==null?void 0:e.media)||null}isInterstitial(e){return !!(e!=null&&e.event)}retreiveMediaSource(e,t){let i=this.getAssetPlayer(e);i&&this.transferMediaFromPlayer(i,t);}transferMediaFromPlayer(e,t){let i=e.interstitial.appendInPlace,r=e.media;if(i&&r===this.primaryMedia){if(this.bufferingAsset=null,(!t||this.isInterstitial(t)&&!t.event.appendInPlace)&&t&&r){this.detachedData={media:r};return}let n=e.transferMedia();this.log(`transfer MediaSource from ${e} ${Ae(n)}`),this.detachedData=n;}else t&&r&&(this.shouldPlay||(this.shouldPlay=!r.paused));}transferMediaTo(e,t){var i,r;if(e.media===t)return;let n=null,a=this.hls,o=e!==a,l=o&&e.interstitial.appendInPlace,d=(i=this.detachedData)==null?void 0:i.mediaSource,c;if(a.media)l&&(n=a.transferMedia(),this.detachedData=n),c="Primary";else if(d){let m=this.getBufferingPlayer();m?(n=m.transferMedia(),c=`${m}`):c="detached MediaSource";}else c="detached media";if(!n){if(d)n=this.detachedData,this.log(`using detachedData: MediaSource ${Ae(n)}`);else if(!this.detachedData||a.media===t){let m=this.playerQueue;m.length>1&&m.forEach(p=>{if(o&&p.interstitial.appendInPlace!==l){let E=p.interstitial;this.clearInterstitial(p.interstitial,null),E.appendInPlace=false,E.appendInPlace&&this.warn(`Could not change append strategy for queued assets ${E}`);}}),this.hls.detachMedia(),this.detachedData={media:t};}}let u=n&&"mediaSource"in n&&((r=n.mediaSource)==null?void 0:r.readyState)!=="closed",h=u&&n?n:t;this.log(`${u?"transfering MediaSource":"attaching media"} to ${o?e:"Primary"} from ${c} (media.currentTime: ${t.currentTime})`);let f=this.schedule;if(h===n&&f){let m=o&&e.assetId===f.assetIdAtEnd;h.overrides={duration:f.duration,endOfStream:!o||m,cueRemoval:!o};}e.attachMedia(h);}onInterstitialCueEnter(){this.onTimeupdate();}checkStart(){let e=this.schedule,t=e?.events;if(!t||this.playbackDisabled||!this.media)return;this.bufferedPos===-1&&(this.bufferedPos=0);let i=this.timelinePos,r=this.effectivePlayingItem;if(i===-1){let n=this.hls.startPosition;if(this.log(Ro("checkStart",n)),this.timelinePos=n,t.length&&t[0].cue.pre){let a=e.findEventIndex(t[0].identifier);this.setSchedulePosition(a);}else if(n>=0||!this.primaryLive){let a=this.timelinePos=n>0?n:0,o=e.findItemIndexAtTime(a);this.setSchedulePosition(o);}}else if(r&&!this.playingItem){let n=e.findItemIndex(r);this.setSchedulePosition(n);}}advanceAssetBuffering(e,t){let i=e.event,r=i.findAssetIndex(t),n=rc(i,r);if(!i.isAssetPastPlayoutLimit(n))this.bufferedToEvent(e,n);else if(this.schedule){var a;let o=(a=this.schedule.items)==null?void 0:a[this.findItemIndex(e)+1];o&&this.bufferedToItem(o);}}advanceAfterAssetEnded(e,t,i){let r=rc(e,i);if(e.isAssetPastPlayoutLimit(r)){if(this.schedule){let n=this.schedule.items;if(n){let a=t+1,o=n.length;if(a>=o){this.setSchedulePosition(-1);return}let l=e.resumeTime;this.timelinePos<l&&(this.log(Ro("advanceAfterAssetEnded",l)),this.timelinePos=l,e.appendInPlace&&this.advanceInPlace(l),this.checkBuffer(this.bufferedPos<l)),this.setSchedulePosition(a);}}}else {if(e.appendInPlace){let n=e.assetList[r];n&&this.advanceInPlace(n.timelineStart);}this.setSchedulePosition(t,r);}}setScheduleToAssetAtTime(e,t){let i=this.schedule;if(!i)return;let r=t.parentIdentifier,n=i.getEvent(r);if(n){let a=i.findEventIndex(r),o=i.findAssetIndex(n,e);this.advanceAfterAssetEnded(n,a,o-1);}}setSchedulePosition(e,t){var i;let r=(i=this.schedule)==null?void 0:i.items;if(!r||this.playbackDisabled)return;let n=e>=0?r[e]:null;this.log(`setSchedulePosition ${e}, ${t} (${n&&$t(n)}) pos: ${this.timelinePos}`);let a=this.waitingItem||this.playingItem,o=this.playingLastItem;if(this.isInterstitial(a)){let c=a.event,u=this.playingAsset,h=u?.identifier,f=h?this.getAssetPlayer(h):null;if(f&&h&&(!this.eventItemsMatch(a,n)||t!==void 0&&h!==c.assetList[t].identifier)){var l;let m=c.findAssetIndex(u);if(this.log(`INTERSTITIAL_ASSET_ENDED ${m+1}/${c.assetList.length} ${Js(u)}`),this.endedAsset=u,this.playingAsset=null,this.hls.trigger(g.INTERSTITIAL_ASSET_ENDED,{asset:u,assetListIndex:m,event:c,schedule:r.slice(0),scheduleIndex:e,player:f}),a!==this.playingItem){this.itemsMatch(a,this.playingItem)&&!this.playingAsset&&this.advanceAfterAssetEnded(c,this.findItemIndex(this.playingItem),m);return}this.retreiveMediaSource(h,n),f.media&&!((l=this.detachedData)!=null&&l.mediaSource)&&f.detachMedia();}if(!this.eventItemsMatch(a,n)&&(this.endedItem=a,this.playingItem=null,this.log(`INTERSTITIAL_ENDED ${c} ${$t(a)}`),c.hasPlayed=true,this.hls.trigger(g.INTERSTITIAL_ENDED,{event:c,schedule:r.slice(0),scheduleIndex:e}),c.cue.once)){var d;this.updateSchedule();let m=(d=this.schedule)==null?void 0:d.items;if(n&&m){let p=this.findItemIndex(n);this.advanceSchedule(p,m,t,a,o);}return}}this.advanceSchedule(e,r,t,a,o);}advanceSchedule(e,t,i,r,n){let a=this.schedule;if(!a)return;let o=t[e]||null,l=this.primaryMedia,d=this.playerQueue;if(d.length&&d.forEach(c=>{let u=c.interstitial,h=a.findEventIndex(u.identifier);(h<e||h>e+1)&&this.clearInterstitial(u,o);}),this.isInterstitial(o)){this.timelinePos=Math.min(Math.max(this.timelinePos,o.start),o.end);let c=o.event;if(i===void 0){i=a.findAssetIndex(c,this.timelinePos);let m=rc(c,i-1);if(c.isAssetPastPlayoutLimit(m)||c.appendInPlace&&this.timelinePos===o.end){this.advanceAfterAssetEnded(c,e,i);return}i=m;}let u=this.waitingItem;this.assetsBuffered(o,l)||this.setBufferingItem(o);let h=this.preloadAssets(c,i);if(this.eventItemsMatch(o,u||r)||(this.waitingItem=o,this.log(`INTERSTITIAL_STARTED ${$t(o)} ${c.appendInPlace?"append in place":""}`),this.hls.trigger(g.INTERSTITIAL_STARTED,{event:c,schedule:t.slice(0),scheduleIndex:e})),!c.assetListLoaded){this.log(`Waiting for ASSET-LIST to complete loading ${c}`);return}if(c.assetListLoader&&(c.assetListLoader.destroy(),c.assetListLoader=void 0),!l){this.log(`Waiting for attachMedia to start Interstitial ${c}`);return}this.waitingItem=this.endedItem=null,this.playingItem=o;let f=c.assetList[i];if(!f){this.advanceAfterAssetEnded(c,e,i||0);return}if(h||(h=this.getAssetPlayer(f.identifier)),h===null||h.destroyed){let m=c.assetList.length;this.warn(`asset ${i+1}/${m} player destroyed ${c}`),h=this.createAssetPlayer(c,f,i),h.loadSource();}if(!this.eventItemsMatch(o,this.bufferingItem)&&c.appendInPlace&&this.isAssetBuffered(f))return;this.startAssetPlayer(h,i,t,e,l),this.shouldPlay&&fg(h.media);}else o?(this.resumePrimary(o,e,r),this.shouldPlay&&fg(this.hls.media)):n&&this.isInterstitial(r)&&(this.endedItem=null,this.playingItem=r,r.event.appendInPlace||this.attachPrimary(a.durations.primary,null));}get playbackDisabled(){return this.hls.config.enableInterstitialPlayback===false}get primaryDetails(){var e;return (e=this.mediaSelection)==null?void 0:e.main.details}get primaryLive(){var e;return !!((e=this.primaryDetails)!=null&&e.live)}resumePrimary(e,t,i){var r,n;if(this.playingItem=e,this.playingAsset=this.endedAsset=null,this.waitingItem=this.endedItem=null,this.bufferedToItem(e),this.log(`resuming ${$t(e)}`),!((r=this.detachedData)!=null&&r.mediaSource)){let o=this.timelinePos;(o<e.start||o>=e.end)&&(o=this.getPrimaryResumption(e,t),this.log(Ro("resumePrimary",o)),this.timelinePos=o),this.attachPrimary(o,e);}if(!i)return;let a=(n=this.schedule)==null?void 0:n.items;a&&(this.log(`INTERSTITIALS_PRIMARY_RESUMED ${$t(e)}`),this.hls.trigger(g.INTERSTITIALS_PRIMARY_RESUMED,{schedule:a.slice(0),scheduleIndex:t}),this.checkBuffer());}getPrimaryResumption(e,t){let i=e.start;if(this.primaryLive){let r=this.primaryDetails;if(t===0)return this.hls.startPosition;if(r&&(i<r.fragmentStart||i>r.edge))return this.hls.liveSyncPosition||-1}return i}isAssetBuffered(e){let t=this.getAssetPlayer(e.identifier);return t!=null&&t.hls?t.hls.bufferedToEnd:re.bufferInfo(this.primaryMedia,this.timelinePos,0).end+1>=e.timelineStart+(e.duration||0)}attachPrimary(e,t,i){t?this.setBufferingItem(t):this.bufferingItem=this.playingItem,this.bufferingAsset=null;let r=this.primaryMedia;if(!r)return;let n=this.hls;n.media?this.checkBuffer():(this.transferMediaTo(n,r),i&&this.startLoadingPrimaryAt(e,i)),i||(this.log(Ro("attachPrimary",e)),this.timelinePos=e,this.startLoadingPrimaryAt(e,i));}startLoadingPrimaryAt(e,t){var i;let r=this.hls;!r.loadingEnabled||!r.media||Math.abs((((i=r.mainForwardBufferInfo)==null?void 0:i.start)||r.media.currentTime)-e)>.5?r.startLoad(e,t):r.bufferingEnabled||r.resumeBuffering();}onManifestLoading(){var e;this.stopLoad(),(e=this.schedule)==null||e.reset(),this.emptyPlayerQueue(),this.clearScheduleState(),this.shouldPlay=false,this.bufferedPos=this.timelinePos=-1,this.mediaSelection=this.altSelection=this.manager=this.requiredTracks=null,this.hls.off(g.BUFFER_CODECS,this.onBufferCodecs,this),this.hls.on(g.BUFFER_CODECS,this.onBufferCodecs,this);}onLevelUpdated(e,t){if(t.level===-1||!this.schedule)return;let i=this.hls.levels[t.level];if(!i.details)return;let r=ve(ve({},this.mediaSelection||this.altSelection),{},{main:i});this.mediaSelection=r,this.schedule.parseInterstitialDateRanges(r,this.hls.config.interstitialAppendInPlace),!this.effectivePlayingItem&&this.schedule.items&&this.checkStart();}onAudioTrackUpdated(e,t){let i=this.hls.audioTracks[t.id],r=this.mediaSelection;if(!r){this.altSelection=ve(ve({},this.altSelection),{},{audio:i});return}let n=ve(ve({},r),{},{audio:i});this.mediaSelection=n;}onSubtitleTrackUpdated(e,t){let i=this.hls.subtitleTracks[t.id],r=this.mediaSelection;if(!r){this.altSelection=ve(ve({},this.altSelection),{},{subtitles:i});return}let n=ve(ve({},r),{},{subtitles:i});this.mediaSelection=n;}onAudioTrackSwitching(e,t){let i=bm(t);this.playerQueue.forEach(({hls:r})=>r&&(r.setAudioOption(t)||r.setAudioOption(i)));}onSubtitleTrackSwitch(e,t){let i=bm(t);this.playerQueue.forEach(({hls:r})=>r&&(r.setSubtitleOption(t)||t.id!==-1&&r.setSubtitleOption(i)));}onBufferCodecs(e,t){let i=t.tracks;i&&(this.requiredTracks=i);}onBufferAppended(e,t){this.checkBuffer();}onBufferFlushed(e,t){let i=this.playingItem;if(i&&!this.itemsMatch(i,this.bufferingItem)&&!this.isInterstitial(i)){let r=this.timelinePos;this.bufferedPos=r,this.checkBuffer();}}onBufferedToEnd(e){if(!this.schedule)return;let t=this.schedule.events;if(this.bufferedPos<Number.MAX_VALUE&&t){for(let r=0;r<t.length;r++){let n=t[r];if(n.cue.post){var i;let a=this.schedule.findEventIndex(n.identifier),o=(i=this.schedule.items)==null?void 0:i[a];this.isInterstitial(o)&&this.eventItemsMatch(o,this.bufferingItem)&&this.bufferedToItem(o,0);break}}this.bufferedPos=Number.MAX_VALUE;}}onMediaEnded(e){let t=this.playingItem;if(!this.playingLastItem&&t){let i=this.findItemIndex(t);this.setSchedulePosition(i+1);}else this.shouldPlay=false;}updateItem(e,t){var i;let r=(i=this.schedule)==null?void 0:i.items;if(e&&r){let n=this.findItemIndex(e,t);return r[n]||null}return null}trimInPlace(e,t){if(this.isInterstitial(e)&&e.event.appendInPlace&&t.end-e.end>.25){e.event.assetList.forEach((n,a)=>{e.event.isAssetPastPlayoutLimit(a)&&this.clearAssetPlayer(n.identifier,null);});let i=e.end+.25,r=re.bufferInfo(this.primaryMedia,i,0);(r.end>i||(r.nextStart||0)>i)&&(this.log(`trim buffered interstitial ${$t(e)} (was ${$t(t)})`),this.attachPrimary(i,null,true),this.flushFrontBuffer(i));}}itemsMatch(e,t){return !!t&&(e===t||e.event&&t.event&&this.eventItemsMatch(e,t)||!e.event&&!t.event&&this.findItemIndex(e)===this.findItemIndex(t))}eventItemsMatch(e,t){var i;return !!t&&(e===t||e.event.identifier===((i=t.event)==null?void 0:i.identifier))}findItemIndex(e,t){return e&&this.schedule?this.schedule.findItemIndex(e,t):-1}updateSchedule(e=false){var t;let i=this.mediaSelection;i&&((t=this.schedule)==null||t.updateSchedule(i,[],e));}checkBuffer(e){var t;let i=(t=this.schedule)==null?void 0:t.items;if(!i)return;let r=re.bufferInfo(this.primaryMedia,this.timelinePos,0);e&&(this.bufferedPos=this.timelinePos),e||(e=r.len<1),this.updateBufferedPos(r.end,i,e);}updateBufferedPos(e,t,i){let r=this.schedule,n=this.bufferingItem;if(this.bufferedPos>e||!r)return;if(t.length===1&&this.itemsMatch(t[0],n)){this.bufferedPos=e;return}let a=this.playingItem,o=this.findItemIndex(a),l=r.findItemIndexAtTime(e);if(this.bufferedPos<e){var d;let c=this.findItemIndex(n),u=Math.min(c+1,t.length-1),h=t[u];if((l===-1&&n&&e>=n.end||(d=h.event)!=null&&d.appendInPlace&&e+.01>=h.start)&&(l=u),this.isInterstitial(n)){let f=n.event;if(u-o>1&&f.appendInPlace===false||f.assetList.length===0&&f.assetListLoader)return}if(this.bufferedPos=e,l>c&&l>o)this.bufferedToItem(h);else {let f=this.primaryDetails;this.primaryLive&&f&&e>f.edge-f.targetduration&&h.start<f.edge+this.hls.config.interstitialLiveLookAhead&&this.isInterstitial(h)&&this.preloadAssets(h.event,0);}}else i&&a&&!this.itemsMatch(a,n)&&(l===o?this.bufferedToItem(a):l===o+1&&this.bufferedToItem(t[l]));}assetsBuffered(e,t){return e.event.assetList.length===0?false:!e.event.assetList.some(r=>{let n=this.getAssetPlayer(r.identifier);return !(n!=null&&n.bufferedInPlaceToEnd(t))})}setBufferingItem(e){let t=this.bufferingItem,i=this.schedule;if(!this.itemsMatch(e,t)&&i){let{items:r,events:n}=i;if(!r||!n)return t;let a=this.isInterstitial(e),o=this.getBufferingPlayer();this.bufferingItem=e,this.bufferedPos=Math.max(e.start,Math.min(e.end,this.timelinePos));let l=o?o.remaining:t?t.end-this.timelinePos:0;if(this.log(`INTERSTITIALS_BUFFERED_TO_BOUNDARY ${$t(e)}`+(t?` (${l.toFixed(2)} remaining)`:"")),!this.playbackDisabled)if(a){let d=i.findAssetIndex(e.event,this.bufferedPos);e.event.assetList.forEach((c,u)=>{let h=this.getAssetPlayer(c.identifier);h&&(u===d&&h.loadSource(),h.resumeBuffering());});}else this.hls.resumeBuffering(),this.playerQueue.forEach(d=>d.pauseBuffering());this.hls.trigger(g.INTERSTITIALS_BUFFERED_TO_BOUNDARY,{events:n.slice(0),schedule:r.slice(0),bufferingIndex:this.findItemIndex(e),playingIndex:this.findItemIndex(this.playingItem)});}else this.bufferingItem!==e&&(this.bufferingItem=e);return t}bufferedToItem(e,t=0){let i=this.setBufferingItem(e);if(!this.playbackDisabled){if(this.isInterstitial(e))this.bufferedToEvent(e,t);else if(i!==null){this.bufferingAsset=null;let r=this.detachedData;r?r.mediaSource?this.attachPrimary(e.start,e,true):this.preloadPrimary(e):this.preloadPrimary(e);}}}preloadPrimary(e){let t=this.findItemIndex(e),i=this.getPrimaryResumption(e,t);this.startLoadingPrimaryAt(i);}bufferedToEvent(e,t){let i=e.event,r=i.assetList.length===0&&!i.assetListLoader,n=i.cue.once;if(r||!n){let a=this.preloadAssets(i,t);if(a!=null&&a.interstitial.appendInPlace){let o=this.primaryMedia;o&&this.bufferAssetPlayer(a,o);}}}preloadAssets(e,t){let i=e.assetUrl,r=e.assetList.length,n=r===0&&!e.assetListLoader,a=e.cue.once;if(n){let l=e.timelineStart;if(e.appendInPlace){var o;let h=this.playingItem;!this.isInterstitial(h)&&(h==null||(o=h.nextEvent)==null?void 0:o.identifier)===e.identifier&&this.flushFrontBuffer(l+.25);}let d,c=0;if(!this.playingItem&&this.primaryLive&&(c=this.hls.startPosition,c===-1&&(c=this.hls.liveSyncPosition||0)),c&&!(e.cue.pre||e.cue.post)){let h=c-l;h>0&&(d=Math.round(h*1e3)/1e3);}if(this.log(`Load interstitial asset ${t+1}/${i?1:r} ${e}${d?` live-start: ${c} start-offset: ${d}`:""}`),i)return this.createAsset(e,0,0,l,e.duration,i);let u=this.assetListLoader.loadAssetList(e,d);u&&(e.assetListLoader=u);}else if(!a&&r){for(let d=t;d<r;d++){let c=e.assetList[d],u=this.getAssetPlayerQueueIndex(c.identifier);(u===-1||this.playerQueue[u].destroyed)&&!c.error&&this.createAssetPlayer(e,c,d);}let l=e.assetList[t];if(l){let d=this.getAssetPlayer(l.identifier);return d&&d.loadSource(),d}}return null}flushFrontBuffer(e){let t=this.requiredTracks;if(!t)return;this.log(`Removing front buffer starting at ${e}`),Object.keys(t).forEach(r=>{this.hls.trigger(g.BUFFER_FLUSHING,{startOffset:e,endOffset:1/0,type:r});});}getAssetPlayerQueueIndex(e){let t=this.playerQueue;for(let i=0;i<t.length;i++)if(e===t[i].assetId)return i;return -1}getAssetPlayer(e){let t=this.getAssetPlayerQueueIndex(e);return this.playerQueue[t]||null}getBufferingPlayer(){let{playerQueue:e,primaryMedia:t}=this;if(t){for(let i=0;i<e.length;i++)if(e[i].media===t)return e[i]}return null}createAsset(e,t,i,r,n,a){let o={parentIdentifier:e.identifier,identifier:oA(e,a,t),duration:n,startOffset:i,timelineStart:r,uri:a};return this.createAssetPlayer(e,o,t)}createAssetPlayer(e,t,i){let r=this.hls,n=r.userConfig,a=n.videoPreference,o=r.loadLevelObj||r.levels[r.currentLevel];(a||o)&&(a=ye({},a),o.videoCodec&&(a.videoCodec=o.videoCodec),o.videoRange&&(a.allowedVideoRanges=[o.videoRange]));let l=r.audioTracks[r.audioTrack],d=r.subtitleTracks[r.subtitleTrack],c=0;if(this.primaryLive||e.appendInPlace){let A=this.timelinePos-t.timelineStart;if(A>1){let b=t.duration;b&&A<b&&(c=A);}}let u=t.identifier,h=ve(ve({},n),{},{maxMaxBufferLength:Math.min(180,r.config.maxMaxBufferLength),autoStartLoad:true,startFragPrefetch:true,primarySessionId:r.sessionId,assetPlayerId:u,abrEwmaDefaultEstimate:r.bandwidthEstimate,interstitialsController:void 0,startPosition:c,liveDurationInfinity:false,testBandwidth:false,videoPreference:a,audioPreference:l||n.audioPreference,subtitlePreference:d||n.subtitlePreference});e.appendInPlace&&(e.appendInPlaceStarted=true,t.timelineStart&&(h.timelineOffset=t.timelineStart));let f=h.cmcd;f!=null&&f.sessionId&&f.contentId&&(h.cmcd=ye({},f,{contentId:hn(t.uri)})),this.getAssetPlayer(u)&&this.warn(`Duplicate date range identifier ${e} and asset ${u}`);let m=new lu(this.HlsPlayerClass,h,e,t);this.playerQueue.push(m),e.assetList[i]=t;let p=true,E=A=>{if(A.live){var b;let k=new Error(`Interstitials MUST be VOD assets ${e}`),R={fatal:true,type:z.OTHER_ERROR,details:x.INTERSTITIAL_ASSET_ITEM_ERROR,error:k},L=((b=this.schedule)==null?void 0:b.findEventIndex(e.identifier))||-1;this.handleAssetItemError(R,e,L,i,k.message);return}let D=A.edge-A.fragmentStart,I=t.duration;(p||I===null||D>I)&&(p=false,this.log(`Interstitial asset "${u}" duration change ${I} > ${D}`),t.duration=D,this.updateSchedule());};m.on(g.LEVEL_UPDATED,(A,{details:b})=>E(b)),m.on(g.LEVEL_PTS_UPDATED,(A,{details:b})=>E(b)),m.on(g.EVENT_CUE_ENTER,()=>this.onInterstitialCueEnter());let v=(A,b)=>{let D=this.getAssetPlayer(u);if(D&&b.tracks){D.off(g.BUFFER_CODECS,v),D.tracks=b.tracks;let I=this.primaryMedia;this.bufferingAsset===D.assetItem&&I&&!D.media&&this.bufferAssetPlayer(D,I);}};m.on(g.BUFFER_CODECS,v);let T=()=>{var A;let b=this.getAssetPlayer(u);if(this.log(`buffered to end of asset ${b}`),!b||!this.schedule)return;let D=this.schedule.findEventIndex(e.identifier),I=(A=this.schedule.items)==null?void 0:A[D];this.isInterstitial(I)&&this.advanceAssetBuffering(I,t);};m.on(g.BUFFERED_TO_END,T);let S=A=>()=>{if(!this.getAssetPlayer(u)||!this.schedule)return;this.shouldPlay=true;let D=this.schedule.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,D,A);};return m.once(g.MEDIA_ENDED,S(i)),m.once(g.PLAYOUT_LIMIT_REACHED,S(1/0)),m.on(g.ERROR,(A,b)=>{if(!this.schedule)return;let D=this.getAssetPlayer(u);if(b.details===x.BUFFER_STALLED_ERROR){if(D!=null&&D.appendInPlace){this.handleInPlaceStall(e);return}this.onTimeupdate(),this.checkBuffer(true);return}this.handleAssetItemError(b,e,this.schedule.findEventIndex(e.identifier),i,`Asset player error ${b.error} ${e}`);}),m.on(g.DESTROYING,()=>{if(!this.getAssetPlayer(u)||!this.schedule)return;let b=new Error(`Asset player destroyed unexpectedly ${u}`),D={fatal:true,type:z.OTHER_ERROR,details:x.INTERSTITIAL_ASSET_ITEM_ERROR,error:b};this.handleAssetItemError(D,e,this.schedule.findEventIndex(e.identifier),i,b.message);}),this.log(`INTERSTITIAL_ASSET_PLAYER_CREATED ${Js(t)}`),this.hls.trigger(g.INTERSTITIAL_ASSET_PLAYER_CREATED,{asset:t,assetListIndex:i,event:e,player:m}),m}clearInterstitial(e,t){e.assetList.forEach(i=>{this.clearAssetPlayer(i.identifier,t);}),e.reset();}resetAssetPlayer(e){let t=this.getAssetPlayerQueueIndex(e);if(t!==-1){this.log(`reset asset player "${e}" after error`);let i=this.playerQueue[t];this.transferMediaFromPlayer(i,null),i.resetDetails();}}clearAssetPlayer(e,t){let i=this.getAssetPlayerQueueIndex(e);if(i!==-1){let r=this.playerQueue[i];this.log(`clear ${r} toSegment: ${t&&$t(t)}`),this.transferMediaFromPlayer(r,t),this.playerQueue.splice(i,1),r.destroy();}}emptyPlayerQueue(){let e;for(;e=this.playerQueue.pop();)e.destroy();this.playerQueue=[];}startAssetPlayer(e,t,i,r,n){let{interstitial:a,assetItem:o,assetId:l}=e,d=a.assetList.length,c=this.playingAsset;this.endedAsset=null,this.playingAsset=o,(!c||c.identifier!==l)&&(c&&(this.clearAssetPlayer(c.identifier,i[r]),delete c.error),this.log(`INTERSTITIAL_ASSET_STARTED ${t+1}/${d} ${Js(o)}`),this.hls.trigger(g.INTERSTITIAL_ASSET_STARTED,{asset:o,assetListIndex:t,event:a,schedule:i.slice(0),scheduleIndex:r,player:e})),this.bufferAssetPlayer(e,n);}bufferAssetPlayer(e,t){var i,r;if(!this.schedule)return;let{interstitial:n,assetItem:a}=e,o=this.schedule.findEventIndex(n.identifier),l=(i=this.schedule.items)==null?void 0:i[o];if(!l)return;e.loadSource(),this.setBufferingItem(l),this.bufferingAsset=a;let d=this.getBufferingPlayer();if(d===e)return;let c=n.appendInPlace;if(c&&d?.interstitial.appendInPlace===false)return;let u=d?.tracks||((r=this.detachedData)==null?void 0:r.tracks)||this.requiredTracks;if(c&&a!==this.playingAsset){if(!e.tracks){this.log(`Waiting for track info before buffering ${e}`);return}if(u&&!_g(u,e.tracks)){let h=new Error(`Asset ${Js(a)} SourceBuffer tracks ('${Object.keys(e.tracks)}') are not compatible with primary content tracks ('${Object.keys(u)}')`),f={fatal:true,type:z.OTHER_ERROR,details:x.INTERSTITIAL_ASSET_ITEM_ERROR,error:h},m=n.findAssetIndex(a);this.handleAssetItemError(f,n,o,m,h.message);return}}this.transferMediaTo(e,t);}handleInPlaceStall(e){let t=this.schedule,i=this.primaryMedia;if(!t||!i)return;let r=i.currentTime,n=t.findAssetIndex(e,r),a=e.assetList[n];if(a){let o=this.getAssetPlayer(a.identifier);if(o){let l=o.currentTime||r-a.timelineStart,d=o.duration-l;if(this.warn(`Stalled at ${l} of ${l+d} in ${o} ${e} (media.currentTime: ${r})`),l&&(d/i.playbackRate<.5||o.bufferedInPlaceToEnd(i))&&o.hls){let c=t.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,c,n);}}}}advanceInPlace(e){let t=this.primaryMedia;t&&t.currentTime<e&&(t.currentTime=e);}handleAssetItemError(e,t,i,r,n){if(e.details===x.BUFFER_STALLED_ERROR)return;let a=t.assetList[r]||null;if(this.warn(`INTERSTITIAL_ASSET_ERROR ${a&&Js(a)} ${e.error}`),!this.schedule)return;let o=a?.identifier||"",l=this.getAssetPlayerQueueIndex(o),d=this.playerQueue[l]||null,c=this.schedule.items,u=ye({},e,{fatal:false,errorAction:ir(true),asset:a,assetListIndex:r,event:t,schedule:c,scheduleIndex:i,player:d});if(this.hls.trigger(g.INTERSTITIAL_ASSET_ERROR,u),!e.fatal)return;let h=this.playingAsset,f=this.bufferingAsset,m=new Error(n);if(a&&(this.clearAssetPlayer(o,null),a.error=m),!t.assetList.some(p=>!p.error))t.error=m;else for(let p=r;p<t.assetList.length;p++)this.resetAssetPlayer(t.assetList[p].identifier);this.updateSchedule(true),t.error?this.primaryFallback(t):h&&h.identifier===o?this.advanceAfterAssetEnded(t,i,r):f&&f.identifier===o&&this.isInterstitial(this.bufferingItem)&&this.advanceAssetBuffering(this.bufferingItem,f);}primaryFallback(e){let t=e.timelineStart,i=this.effectivePlayingItem;if(i){this.log(`Fallback to primary from event "${e.identifier}" start: ${t} pos: ${this.timelinePos} playing: ${$t(i)} error: ${e.error}`);let r=this.timelinePos;r===-1&&(r=this.hls.startPosition);let n=this.updateItem(i,r);if(this.itemsMatch(i,n)&&this.clearInterstitial(e,null),e.appendInPlace&&(this.attachPrimary(t,null),this.flushFrontBuffer(t)),!this.schedule)return;let a=this.schedule.findItemIndexAtTime(r);this.setSchedulePosition(a);}else this.checkStart();}onAssetListLoaded(e,t){var i,r;let n=t.event,a=n.identifier,o=t.assetListResponse.ASSETS;if(!((i=this.schedule)!=null&&i.hasEvent(a)))return;let l=n.timelineStart,d=n.duration,c=0;o.forEach((p,E)=>{let v=parseFloat(p.DURATION);this.createAsset(n,E,c,l+c,v,p.URI),c+=v;}),n.duration=c,this.log(`Loaded asset-list with duration: ${c} (was: ${d}) ${n}`);let u=this.waitingItem,h=u?.event.identifier===a;this.updateSchedule();let f=(r=this.bufferingItem)==null?void 0:r.event;if(h){var m;let p=this.schedule.findEventIndex(a),E=(m=this.schedule.items)==null?void 0:m[p];if(E){if(!this.playingItem&&this.timelinePos>E.end&&this.schedule.findItemIndexAtTime(this.timelinePos)!==p){n.error=new Error(`Interstitial no longer within playback range ${this.timelinePos} ${n}`),this.updateSchedule(true),this.primaryFallback(n);return}this.setBufferingItem(E);}this.setSchedulePosition(p);}else if(f?.identifier===a){let p=n.assetList[0];if(p){let E=this.getAssetPlayer(p.identifier);if(f.appendInPlace){let v=this.primaryMedia;E&&v&&this.bufferAssetPlayer(E,v);}else E&&E.loadSource();}}}onError(e,t){if(this.schedule)switch(t.details){case x.ASSET_LIST_PARSING_ERROR:case x.ASSET_LIST_LOAD_ERROR:case x.ASSET_LIST_LOAD_TIMEOUT:{let i=t.interstitial;i&&(this.updateSchedule(true),this.primaryFallback(i));break}case x.BUFFER_STALLED_ERROR:{let i=this.endedItem||this.waitingItem||this.playingItem;if(this.isInterstitial(i)&&i.event.appendInPlace){this.handleInPlaceStall(i.event);return}this.log(`Primary player stall @${this.timelinePos} bufferedPos: ${this.bufferedPos}`),this.onTimeupdate(),this.checkBuffer(true);break}}}},mg=500,hu=class extends yn{constructor(e,t,i){super(e,t,i,"subtitle-stream-controller",W.SUBTITLE),this.currentTrackId=-1,this.tracksBuffered=[],this.mainDetails=null,this.registerListeners();}onHandlerDestroying(){this.unregisterListeners(),super.onHandlerDestroying(),this.mainDetails=null;}registerListeners(){super.registerListeners();let{hls:e}=this;e.on(g.LEVEL_LOADED,this.onLevelLoaded,this),e.on(g.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(g.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(g.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(g.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.on(g.BUFFER_FLUSHING,this.onBufferFlushing,this);}unregisterListeners(){super.unregisterListeners();let{hls:e}=this;e.off(g.LEVEL_LOADED,this.onLevelLoaded,this),e.off(g.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(g.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(g.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(g.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.off(g.BUFFER_FLUSHING,this.onBufferFlushing,this);}startLoad(e,t){this.stopLoad(),this.state=C.IDLE,this.setInterval(mg),this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick();}onManifestLoading(){super.onManifestLoading(),this.mainDetails=null;}onMediaDetaching(e,t){this.tracksBuffered=[],super.onMediaDetaching(e,t);}onLevelLoaded(e,t){this.mainDetails=t.details;}onSubtitleFragProcessed(e,t){let{frag:i,success:r}=t;if(this.fragContextChanged(i)||(Ue(i)&&(this.fragPrevious=i),this.state=C.IDLE),!r)return;let n=this.tracksBuffered[this.currentTrackId];if(!n)return;let a,o=i.start;for(let d=0;d<n.length;d++)if(o>=n[d].start&&o<=n[d].end){a=n[d];break}let l=i.start+i.duration;a?a.end=l:(a={start:o,end:l},n.push(a)),this.fragmentTracker.fragBuffered(i),this.fragBufferedComplete(i,null),this.media&&this.tick();}onBufferFlushing(e,t){let{startOffset:i,endOffset:r}=t;if(i===0&&r!==Number.POSITIVE_INFINITY){let n=r-1;if(n<=0)return;t.endOffsetSubtitles=Math.max(0,n),this.tracksBuffered.forEach(a=>{for(let o=0;o<a.length;){if(a[o].end<=n){a.shift();continue}else if(a[o].start<n)a[o].start=n;else break;o++;}}),this.fragmentTracker.removeFragmentsInRange(i,n,W.SUBTITLE);}}onError(e,t){let i=t.frag;i?.type===W.SUBTITLE&&(t.details===x.FRAG_GAP&&this.fragmentTracker.fragBuffered(i,true),this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==C.STOPPED&&(this.state=C.IDLE));}onSubtitleTracksUpdated(e,{subtitleTracks:t}){if(this.levels&&Sp(this.levels,t)){this.levels=t.map(i=>new ds(i));return}this.tracksBuffered=[],this.levels=t.map(i=>{let r=new ds(i);return this.tracksBuffered[r.id]=[],r}),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,W.SUBTITLE),this.fragPrevious=null,this.mediaBuffer=null;}onSubtitleTrackSwitch(e,t){var i;if(this.currentTrackId=t.id,!((i=this.levels)!=null&&i.length)||this.currentTrackId===-1){this.clearInterval();return}let r=this.levels[this.currentTrackId];r!=null&&r.details?this.mediaBuffer=this.mediaBufferTimeRanges:this.mediaBuffer=null,r&&this.state!==C.STOPPED&&this.setInterval(mg);}onSubtitleTrackLoaded(e,t){var i;let{currentTrackId:r,levels:n}=this,{details:a,id:o}=t;if(!n){this.warn(`Subtitle tracks were reset while loading level ${o}`);return}let l=n[o];if(o>=n.length||!l)return;this.log(`Subtitle track ${o} loaded [${a.startSN},${a.endSN}]${a.lastPartSn?`[part-${a.lastPartSn}-${a.lastPartIndex}]`:""},duration:${a.totalduration}`),this.mediaBuffer=this.mediaBufferTimeRanges;let d=0;if(a.live||(i=l.details)!=null&&i.live){if(a.deltaUpdateFailed)return;let u=this.mainDetails;if(!u){this.startFragRequested=false;return}let h=u.fragments[0];if(!l.details)a.hasProgramDateTime&&u.hasProgramDateTime?(Zo(a,u),d=a.fragmentStart):h&&(d=h.start,Cc(a,d));else {var c;d=this.alignPlaylists(a,l.details,(c=this.levelLastLoaded)==null?void 0:c.details),d===0&&h&&(d=h.start,Cc(a,d));}u&&!this.startFragRequested&&this.setStartPosition(u,d);}l.details=a,this.levelLastLoaded=l,o===r&&(this.hls.trigger(g.SUBTITLE_TRACK_UPDATED,{details:a,id:o,groupId:t.groupId}),this.tick(),a.live&&!this.fragCurrent&&this.media&&this.state===C.IDLE&&(cs(null,a.fragments,this.media.currentTime,0)||(this.warn("Subtitle playlist not aligned with playback"),l.details=void 0)));}_handleFragmentLoadComplete(e){let{frag:t,payload:i}=e,r=t.decryptdata,n=this.hls;if(!this.fragContextChanged(t)&&i&&i.byteLength>0&&r!=null&&r.key&&r.iv&&sr(r.method)){let a=performance.now();this.decrypter.decrypt(new Uint8Array(i),r.key.buffer,r.iv.buffer,Nu(r.method)).catch(o=>{throw n.trigger(g.ERROR,{type:z.MEDIA_ERROR,details:x.FRAG_DECRYPT_ERROR,fatal:false,error:o,reason:o.message,frag:t}),o}).then(o=>{let l=performance.now();n.trigger(g.FRAG_DECRYPTED,{frag:t,payload:o,stats:{tstart:a,tdecrypt:l}});}).catch(o=>{this.warn(`${o.name}: ${o.message}`),this.state=C.IDLE;});}}doTick(){if(!this.media){this.state=C.IDLE;return}if(this.state===C.IDLE){let{currentTrackId:e,levels:t}=this,i=t?.[e];if(!i||!t.length||!i.details||this.waitForLive(i))return;let{config:r}=this,n=this.getLoadPosition(),a=re.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],n,r.maxBufferHole),{end:o,len:l}=a,d=i.details,c=this.hls.maxBufferLength+d.levelTargetDuration;if(l>c)return;let u=d.fragments,h=u.length,f=d.edge,m=null,p=this.fragPrevious;if(o<f){let T=r.maxFragLookUpTolerance,S=o>f-T?0:T;m=cs(p,u,Math.max(u[0].start,o),S),!m&&p&&p.start<u[0].start&&(m=u[0]);}else m=u[h-1];if(m=this.filterReplacedPrimary(m,i.details),!m)return;let E=m.sn-d.startSN,v=u[E-1];if(v&&v.cc===m.cc&&this.fragmentTracker.getState(v)===Ke.NOT_LOADED&&(m=v),this.fragmentTracker.getState(m)===Ke.NOT_LOADED){let T=this.mapToInitFragWhenRequired(m);T&&this.loadFragment(T,i,o);}}}loadFragment(e,t,i){Ue(e)?super.loadFragment(e,t,i):this._loadInitSegment(e,t);}get mediaBufferTimeRanges(){return new fu(this.tracksBuffered[this.currentTrackId]||[])}},fu=class{constructor(e){this.buffered=void 0;let t=(i,r,n)=>{if(r=r>>>0,r>n-1)throw new DOMException(`Failed to execute '${i}' on 'TimeRanges': The index provided (${r}) is greater than the maximum bound (${n})`);return e[r][i]};this.buffered={get length(){return e.length},end(i){return t("end",i,e.length)},start(i){return t("start",i,e.length)}};}},dA={42:225,92:233,94:237,95:243,96:250,123:231,124:247,125:209,126:241,127:9608,128:174,129:176,130:189,131:191,132:8482,133:162,134:163,135:9834,136:224,137:32,138:232,139:226,140:234,141:238,142:244,143:251,144:193,145:201,146:211,147:218,148:220,149:252,150:8216,151:161,152:42,153:8217,154:9473,155:169,156:8480,157:8226,158:8220,159:8221,160:192,161:194,162:199,163:200,164:202,165:203,166:235,167:206,168:207,169:239,170:212,171:217,172:249,173:219,174:171,175:187,176:195,177:227,178:205,179:204,180:236,181:210,182:242,183:213,184:245,185:123,186:125,187:92,188:94,189:95,190:124,191:8764,192:196,193:228,194:214,195:246,196:223,197:165,198:164,199:9475,200:197,201:229,202:216,203:248,204:9487,205:9491,206:9495,207:9499},Fp=s=>String.fromCharCode(dA[s]||s),Gt=15,vi=100,cA={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},uA={17:2,18:4,21:6,22:8,23:10,19:13,20:15},hA={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},fA={25:2,26:4,29:6,30:8,31:10,27:13,28:15},mA=["white","green","blue","cyan","red","yellow","magenta","black","transparent"],mu=class{constructor(){this.time=null,this.verboseLevel=0;}log(e,t){if(this.verboseLevel>=e){let i=typeof t=="function"?t():t;Te.log(`${this.time} [${e}] ${i}`);}}},rs=function(e){let t=[];for(let i=0;i<e.length;i++)t.push(e[i].toString(16));return t},ol=class{constructor(){this.foreground="white",this.underline=false,this.italics=false,this.background="black",this.flash=false;}reset(){this.foreground="white",this.underline=false,this.italics=false,this.background="black",this.flash=false;}setStyles(e){let t=["foreground","underline","italics","background","flash"];for(let i=0;i<t.length;i++){let r=t[i];e.hasOwnProperty(r)&&(this[r]=e[r]);}}isDefault(){return this.foreground==="white"&&!this.underline&&!this.italics&&this.background==="black"&&!this.flash}equals(e){return this.foreground===e.foreground&&this.underline===e.underline&&this.italics===e.italics&&this.background===e.background&&this.flash===e.flash}copy(e){this.foreground=e.foreground,this.underline=e.underline,this.italics=e.italics,this.background=e.background,this.flash=e.flash;}toString(){return "color="+this.foreground+", underline="+this.underline+", italics="+this.italics+", background="+this.background+", flash="+this.flash}},gu=class{constructor(){this.uchar=" ",this.penState=new ol;}reset(){this.uchar=" ",this.penState.reset();}setChar(e,t){this.uchar=e,this.penState.copy(t);}setPenState(e){this.penState.copy(e);}equals(e){return this.uchar===e.uchar&&this.penState.equals(e.penState)}copy(e){this.uchar=e.uchar,this.penState.copy(e.penState);}isEmpty(){return this.uchar===" "&&this.penState.isDefault()}},pu=class{constructor(e){this.chars=[],this.pos=0,this.currPenState=new ol,this.cueStartTime=null,this.logger=void 0;for(let t=0;t<vi;t++)this.chars.push(new gu);this.logger=e;}equals(e){for(let t=0;t<vi;t++)if(!this.chars[t].equals(e.chars[t]))return false;return true}copy(e){for(let t=0;t<vi;t++)this.chars[t].copy(e.chars[t]);}isEmpty(){let e=true;for(let t=0;t<vi;t++)if(!this.chars[t].isEmpty()){e=false;break}return e}setCursor(e){this.pos!==e&&(this.pos=e),this.pos<0?(this.logger.log(3,"Negative cursor position "+this.pos),this.pos=0):this.pos>vi&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=vi);}moveCursor(e){let t=this.pos+e;if(e>1)for(let i=this.pos+1;i<t+1;i++)this.chars[i].setPenState(this.currPenState);this.setCursor(t);}backSpace(){this.moveCursor(-1),this.chars[this.pos].setChar(" ",this.currPenState);}insertChar(e){e>=144&&this.backSpace();let t=Fp(e);if(this.pos>=vi){this.logger.log(0,()=>"Cannot insert "+e.toString(16)+" ("+t+") at position "+this.pos+". Skipping it!");return}this.chars[this.pos].setChar(t,this.currPenState),this.moveCursor(1);}clearFromPos(e){let t;for(t=e;t<vi;t++)this.chars[t].reset();}clear(){this.clearFromPos(0),this.pos=0,this.currPenState.reset();}clearToEndOfRow(){this.clearFromPos(this.pos);}getTextString(){let e=[],t=true;for(let i=0;i<vi;i++){let r=this.chars[i].uchar;r!==" "&&(t=false),e.push(r);}return t?"":e.join("")}setPenStyles(e){this.currPenState.setStyles(e),this.chars[this.pos].setPenState(this.currPenState);}},fn=class{constructor(e){this.rows=[],this.currRow=Gt-1,this.nrRollUpRows=null,this.lastOutputScreen=null,this.logger=void 0;for(let t=0;t<Gt;t++)this.rows.push(new pu(e));this.logger=e;}reset(){for(let e=0;e<Gt;e++)this.rows[e].clear();this.currRow=Gt-1;}equals(e){let t=true;for(let i=0;i<Gt;i++)if(!this.rows[i].equals(e.rows[i])){t=false;break}return t}copy(e){for(let t=0;t<Gt;t++)this.rows[t].copy(e.rows[t]);}isEmpty(){let e=true;for(let t=0;t<Gt;t++)if(!this.rows[t].isEmpty()){e=false;break}return e}backSpace(){this.rows[this.currRow].backSpace();}clearToEndOfRow(){this.rows[this.currRow].clearToEndOfRow();}insertChar(e){this.rows[this.currRow].insertChar(e);}setPen(e){this.rows[this.currRow].setPenStyles(e);}moveCursor(e){this.rows[this.currRow].moveCursor(e);}setCursor(e){this.logger.log(2,"setCursor: "+e),this.rows[this.currRow].setCursor(e);}setPAC(e){this.logger.log(2,()=>"pacData = "+Ae(e));let t=e.row-1;if(this.nrRollUpRows&&t<this.nrRollUpRows-1&&(t=this.nrRollUpRows-1),this.nrRollUpRows&&this.currRow!==t){for(let o=0;o<Gt;o++)this.rows[o].clear();let n=this.currRow+1-this.nrRollUpRows,a=this.lastOutputScreen;if(a){let o=a.rows[n].cueStartTime,l=this.logger.time;if(o!==null&&l!==null&&o<l)for(let d=0;d<this.nrRollUpRows;d++)this.rows[t-this.nrRollUpRows+d+1].copy(a.rows[n+d]);}}this.currRow=t;let i=this.rows[this.currRow];if(e.indent!==null){let n=e.indent,a=Math.max(n-1,0);i.setCursor(e.indent),e.color=i.chars[a].penState.foreground;}let r={foreground:e.color,underline:e.underline,italics:e.italics,background:"black",flash:false};this.setPen(r);}setBkgData(e){this.logger.log(2,()=>"bkgData = "+Ae(e)),this.backSpace(),this.setPen(e),this.insertChar(32);}setRollUpRows(e){this.nrRollUpRows=e;}rollUp(){if(this.nrRollUpRows===null){this.logger.log(3,"roll_up but nrRollUpRows not set yet");return}this.logger.log(1,()=>this.getDisplayText());let e=this.currRow+1-this.nrRollUpRows,t=this.rows.splice(e,1)[0];t.clear(),this.rows.splice(this.currRow,0,t),this.logger.log(2,"Rolling up");}getDisplayText(e){e=e||false;let t=[],i="",r=-1;for(let n=0;n<Gt;n++){let a=this.rows[n].getTextString();a&&(r=n+1,e?t.push("Row "+r+": '"+a+"'"):t.push(a.trim()));}return t.length>0&&(e?i="["+t.join(" | ")+"]":i=t.join(`
1378
+ `)),i}getTextAndFormat(){return this.rows}},ll=class{constructor(e,t,i){this.chNr=void 0,this.outputFilter=void 0,this.mode=void 0,this.verbose=void 0,this.displayedMemory=void 0,this.nonDisplayedMemory=void 0,this.lastOutputScreen=void 0,this.currRollUpRow=void 0,this.writeScreen=void 0,this.cueStartTime=void 0,this.logger=void 0,this.chNr=e,this.outputFilter=t,this.mode=null,this.verbose=0,this.displayedMemory=new fn(i),this.nonDisplayedMemory=new fn(i),this.lastOutputScreen=new fn(i),this.currRollUpRow=this.displayedMemory.rows[Gt-1],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.logger=i;}reset(){this.mode=null,this.displayedMemory.reset(),this.nonDisplayedMemory.reset(),this.lastOutputScreen.reset(),this.outputFilter.reset(),this.currRollUpRow=this.displayedMemory.rows[Gt-1],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null;}getHandler(){return this.outputFilter}setHandler(e){this.outputFilter=e;}setPAC(e){this.writeScreen.setPAC(e);}setBkgData(e){this.writeScreen.setBkgData(e);}setMode(e){e!==this.mode&&(this.mode=e,this.logger.log(2,()=>"MODE="+e),this.mode==="MODE_POP-ON"?this.writeScreen=this.nonDisplayedMemory:(this.writeScreen=this.displayedMemory,this.writeScreen.reset()),this.mode!=="MODE_ROLL-UP"&&(this.displayedMemory.nrRollUpRows=null,this.nonDisplayedMemory.nrRollUpRows=null),this.mode=e);}insertChars(e){for(let i=0;i<e.length;i++)this.writeScreen.insertChar(e[i]);let t=this.writeScreen===this.displayedMemory?"DISP":"NON_DISP";this.logger.log(2,()=>t+": "+this.writeScreen.getDisplayText(true)),(this.mode==="MODE_PAINT-ON"||this.mode==="MODE_ROLL-UP")&&(this.logger.log(1,()=>"DISPLAYED: "+this.displayedMemory.getDisplayText(true)),this.outputDataUpdate());}ccRCL(){this.logger.log(2,"RCL - Resume Caption Loading"),this.setMode("MODE_POP-ON");}ccBS(){this.logger.log(2,"BS - BackSpace"),this.mode!=="MODE_TEXT"&&(this.writeScreen.backSpace(),this.writeScreen===this.displayedMemory&&this.outputDataUpdate());}ccAOF(){}ccAON(){}ccDER(){this.logger.log(2,"DER- Delete to End of Row"),this.writeScreen.clearToEndOfRow(),this.outputDataUpdate();}ccRU(e){this.logger.log(2,"RU("+e+") - Roll Up"),this.writeScreen=this.displayedMemory,this.setMode("MODE_ROLL-UP"),this.writeScreen.setRollUpRows(e);}ccFON(){this.logger.log(2,"FON - Flash On"),this.writeScreen.setPen({flash:true});}ccRDC(){this.logger.log(2,"RDC - Resume Direct Captioning"),this.setMode("MODE_PAINT-ON");}ccTR(){this.logger.log(2,"TR"),this.setMode("MODE_TEXT");}ccRTD(){this.logger.log(2,"RTD"),this.setMode("MODE_TEXT");}ccEDM(){this.logger.log(2,"EDM - Erase Displayed Memory"),this.displayedMemory.reset(),this.outputDataUpdate(true);}ccCR(){this.logger.log(2,"CR - Carriage Return"),this.writeScreen.rollUp(),this.outputDataUpdate(true);}ccENM(){this.logger.log(2,"ENM - Erase Non-displayed Memory"),this.nonDisplayedMemory.reset();}ccEOC(){if(this.logger.log(2,"EOC - End Of Caption"),this.mode==="MODE_POP-ON"){let e=this.displayedMemory;this.displayedMemory=this.nonDisplayedMemory,this.nonDisplayedMemory=e,this.writeScreen=this.nonDisplayedMemory,this.logger.log(1,()=>"DISP: "+this.displayedMemory.getDisplayText());}this.outputDataUpdate(true);}ccTO(e){this.logger.log(2,"TO("+e+") - Tab Offset"),this.writeScreen.moveCursor(e);}ccMIDROW(e){let t={flash:false};if(t.underline=e%2===1,t.italics=e>=46,t.italics)t.foreground="white";else {let i=Math.floor(e/2)-16,r=["white","green","blue","cyan","red","yellow","magenta"];t.foreground=r[i];}this.logger.log(2,"MIDROW: "+Ae(t)),this.writeScreen.setPen(t);}outputDataUpdate(e=false){let t=this.logger.time;t!==null&&this.outputFilter&&(this.cueStartTime===null&&!this.displayedMemory.isEmpty()?this.cueStartTime=t:this.displayedMemory.equals(this.lastOutputScreen)||(this.outputFilter.newCue(this.cueStartTime,t,this.lastOutputScreen),e&&this.outputFilter.dispatchCue&&this.outputFilter.dispatchCue(),this.cueStartTime=this.displayedMemory.isEmpty()?null:t),this.lastOutputScreen.copy(this.displayedMemory));}cueSplitAtTime(e){this.outputFilter&&(this.displayedMemory.isEmpty()||(this.outputFilter.newCue&&this.outputFilter.newCue(this.cueStartTime,e,this.displayedMemory),this.cueStartTime=e));}},dl=class{constructor(e,t,i){this.channels=void 0,this.currentChannel=0,this.cmdHistory=pA(),this.logger=void 0;let r=this.logger=new mu;this.channels=[null,new ll(e,t,r),new ll(e+1,i,r)];}getHandler(e){return this.channels[e].getHandler()}setHandler(e,t){this.channels[e].setHandler(t);}addData(e,t){this.logger.time=e;for(let i=0;i<t.length;i+=2){let r=t[i]&127,n=t[i+1]&127,a=false,o=null;if(r===0&&n===0)continue;this.logger.log(3,()=>"["+rs([t[i],t[i+1]])+"] -> ("+rs([r,n])+")");let l=this.cmdHistory;if(r>=16&&r<=31){if(gA(r,n,l)){ko(null,null,l),this.logger.log(3,()=>"Repeated command ("+rs([r,n])+") is dropped");continue}ko(r,n,this.cmdHistory),a=this.parseCmd(r,n),a||(a=this.parseMidrow(r,n)),a||(a=this.parsePAC(r,n)),a||(a=this.parseBackgroundAttributes(r,n));}else ko(null,null,l);if(!a&&(o=this.parseChars(r,n),o)){let c=this.currentChannel;c&&c>0?this.channels[c].insertChars(o):this.logger.log(2,"No channel found yet. TEXT-MODE?");}!a&&!o&&this.logger.log(2,()=>"Couldn't parse cleaned data "+rs([r,n])+" orig: "+rs([t[i],t[i+1]]));}}parseCmd(e,t){let i=(e===20||e===28||e===21||e===29)&&t>=32&&t<=47,r=(e===23||e===31)&&t>=33&&t<=35;if(!(i||r))return false;let n=e===20||e===21||e===23?1:2,a=this.channels[n];return e===20||e===21||e===28||e===29?t===32?a.ccRCL():t===33?a.ccBS():t===34?a.ccAOF():t===35?a.ccAON():t===36?a.ccDER():t===37?a.ccRU(2):t===38?a.ccRU(3):t===39?a.ccRU(4):t===40?a.ccFON():t===41?a.ccRDC():t===42?a.ccTR():t===43?a.ccRTD():t===44?a.ccEDM():t===45?a.ccCR():t===46?a.ccENM():t===47&&a.ccEOC():a.ccTO(t-32),this.currentChannel=n,true}parseMidrow(e,t){let i=0;if((e===17||e===25)&&t>=32&&t<=47){if(e===17?i=1:i=2,i!==this.currentChannel)return this.logger.log(0,"Mismatch channel in midrow parsing"),false;let r=this.channels[i];return r?(r.ccMIDROW(t),this.logger.log(3,()=>"MIDROW ("+rs([e,t])+")"),true):false}return false}parsePAC(e,t){let i,r=(e>=17&&e<=23||e>=25&&e<=31)&&t>=64&&t<=127,n=(e===16||e===24)&&t>=64&&t<=95;if(!(r||n))return false;let a=e<=23?1:2;t>=64&&t<=95?i=a===1?cA[e]:hA[e]:i=a===1?uA[e]:fA[e];let o=this.channels[a];return o?(o.setPAC(this.interpretPAC(i,t)),this.currentChannel=a,true):false}interpretPAC(e,t){let i,r={color:null,italics:false,indent:null,underline:false,row:e};return t>95?i=t-96:i=t-64,r.underline=(i&1)===1,i<=13?r.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(i/2)]:i<=15?(r.italics=true,r.color="white"):r.indent=Math.floor((i-16)/2)*4,r}parseChars(e,t){let i,r=null,n=null;if(e>=25?(i=2,n=e-8):(i=1,n=e),n>=17&&n<=19){let a;n===17?a=t+80:n===18?a=t+112:a=t+144,this.logger.log(2,()=>"Special char '"+Fp(a)+"' in channel "+i),r=[a];}else e>=32&&e<=127&&(r=t===0?[e]:[e,t]);return r&&this.logger.log(3,()=>"Char codes = "+rs(r).join(",")),r}parseBackgroundAttributes(e,t){let i=(e===16||e===24)&&t>=32&&t<=47,r=(e===23||e===31)&&t>=45&&t<=47;if(!(i||r))return false;let n,a={};e===16||e===24?(n=Math.floor((t-32)/2),a.background=mA[n],t%2===1&&(a.background=a.background+"_semi")):t===45?a.background="transparent":(a.foreground="black",t===47&&(a.underline=true));let o=e<=23?1:2;return this.channels[o].setBkgData(a),true}reset(){for(let e=0;e<Object.keys(this.channels).length;e++){let t=this.channels[e];t&&t.reset();}ko(null,null,this.cmdHistory);}cueSplitAtTime(e){for(let t=0;t<this.channels.length;t++){let i=this.channels[t];i&&i.cueSplitAtTime(e);}}};function ko(s,e,t){t.a=s,t.b=e;}function gA(s,e,t){return t.a===s&&t.b===e}function pA(){return {a:null,b:null}}var qu=function(){if(Xo!=null&&Xo.VTTCue)return self.VTTCue;let s=["","lr","rl"],e=["start","middle","end","left","right"];function t(o,l){if(typeof l!="string"||!Array.isArray(o))return false;let d=l.toLowerCase();return ~o.indexOf(d)?d:false}function i(o){return t(s,o)}function r(o){return t(e,o)}function n(o,...l){let d=1;for(;d<arguments.length;d++){let c=arguments[d];for(let u in c)o[u]=c[u];}return o}function a(o,l,d){let c=this,u={enumerable:true};c.hasBeenReset=false;let h="",f=false,m=o,p=l,E=d,v=null,T="",S=true,A="auto",b="start",D=50,I="middle",k=50,R="middle";Object.defineProperty(c,"id",n({},u,{get:function(){return h},set:function(L){h=""+L;}})),Object.defineProperty(c,"pauseOnExit",n({},u,{get:function(){return f},set:function(L){f=!!L;}})),Object.defineProperty(c,"startTime",n({},u,{get:function(){return m},set:function(L){if(typeof L!="number")throw new TypeError("Start time must be set to a number.");m=L,this.hasBeenReset=true;}})),Object.defineProperty(c,"endTime",n({},u,{get:function(){return p},set:function(L){if(typeof L!="number")throw new TypeError("End time must be set to a number.");p=L,this.hasBeenReset=true;}})),Object.defineProperty(c,"text",n({},u,{get:function(){return E},set:function(L){E=""+L,this.hasBeenReset=true;}})),Object.defineProperty(c,"region",n({},u,{get:function(){return v},set:function(L){v=L,this.hasBeenReset=true;}})),Object.defineProperty(c,"vertical",n({},u,{get:function(){return T},set:function(L){let M=i(L);if(M===false)throw new SyntaxError("An invalid or illegal string was specified.");T=M,this.hasBeenReset=true;}})),Object.defineProperty(c,"snapToLines",n({},u,{get:function(){return S},set:function(L){S=!!L,this.hasBeenReset=true;}})),Object.defineProperty(c,"line",n({},u,{get:function(){return A},set:function(L){if(typeof L!="number"&&L!=="auto")throw new SyntaxError("An invalid number or illegal string was specified.");A=L,this.hasBeenReset=true;}})),Object.defineProperty(c,"lineAlign",n({},u,{get:function(){return b},set:function(L){let M=r(L);if(!M)throw new SyntaxError("An invalid or illegal string was specified.");b=M,this.hasBeenReset=true;}})),Object.defineProperty(c,"position",n({},u,{get:function(){return D},set:function(L){if(L<0||L>100)throw new Error("Position must be between 0 and 100.");D=L,this.hasBeenReset=true;}})),Object.defineProperty(c,"positionAlign",n({},u,{get:function(){return I},set:function(L){let M=r(L);if(!M)throw new SyntaxError("An invalid or illegal string was specified.");I=M,this.hasBeenReset=true;}})),Object.defineProperty(c,"size",n({},u,{get:function(){return k},set:function(L){if(L<0||L>100)throw new Error("Size must be between 0 and 100.");k=L,this.hasBeenReset=true;}})),Object.defineProperty(c,"align",n({},u,{get:function(){return R},set:function(L){let M=r(L);if(!M)throw new SyntaxError("An invalid or illegal string was specified.");R=M,this.hasBeenReset=true;}})),c.displayState=void 0;}return a.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},a}(),Eu=class{decode(e,t){if(!e)return "";if(typeof e!="string")throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(e))}};function Np(s){function e(i,r,n,a){return (i|0)*3600+(r|0)*60+(n|0)+parseFloat(a||0)}let t=s.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);return t?parseFloat(t[2])>59?e(t[2],t[3],0,t[4]):e(t[1],t[2],t[3],t[4]):null}var vu=class{constructor(){this.values=Object.create(null);}set(e,t){!this.get(e)&&t!==""&&(this.values[e]=t);}get(e,t,i){return i?this.has(e)?this.values[e]:t[i]:this.has(e)?this.values[e]:t}has(e){return e in this.values}alt(e,t,i){for(let r=0;r<i.length;++r)if(t===i[r]){this.set(e,t);break}}integer(e,t){/^-?\d+$/.test(t)&&this.set(e,parseInt(t,10));}percent(e,t){if(/^([\d]{1,3})(\.[\d]*)?%$/.test(t)){let i=parseFloat(t);if(i>=0&&i<=100)return this.set(e,i),true}return false}};function Up(s,e,t,i){let r=i?s.split(i):[s];for(let n in r){if(typeof r[n]!="string")continue;let a=r[n].split(t);if(a.length!==2)continue;let o=a[0],l=a[1];e(o,l);}}var Tu=new qu(0,0,""),Do=Tu.align==="middle"?"middle":"center";function EA(s,e,t){let i=s;function r(){let o=Np(s);if(o===null)throw new Error("Malformed timestamp: "+i);return s=s.replace(/^[^\sa-zA-Z-]+/,""),o}function n(o,l){let d=new vu;Up(o,function(h,f){let m;switch(h){case "region":for(let p=t.length-1;p>=0;p--)if(t[p].id===f){d.set(h,t[p].region);break}break;case "vertical":d.alt(h,f,["rl","lr"]);break;case "line":m=f.split(","),d.integer(h,m[0]),d.percent(h,m[0])&&d.set("snapToLines",false),d.alt(h,m[0],["auto"]),m.length===2&&d.alt("lineAlign",m[1],["start",Do,"end"]);break;case "position":m=f.split(","),d.percent(h,m[0]),m.length===2&&d.alt("positionAlign",m[1],["start",Do,"end","line-left","line-right","auto"]);break;case "size":d.percent(h,f);break;case "align":d.alt(h,f,["start",Do,"end","left","right"]);break}},/:/,/\s/),l.region=d.get("region",null),l.vertical=d.get("vertical","");let c=d.get("line","auto");c==="auto"&&Tu.line===-1&&(c=-1),l.line=c,l.lineAlign=d.get("lineAlign","start"),l.snapToLines=d.get("snapToLines",true),l.size=d.get("size",100),l.align=d.get("align",Do);let u=d.get("position","auto");u==="auto"&&Tu.position===50&&(u=l.align==="start"||l.align==="left"?0:l.align==="end"||l.align==="right"?100:50),l.position=u;}function a(){s=s.replace(/^\s+/,"");}if(a(),e.startTime=r(),a(),s.slice(0,3)!=="-->")throw new Error("Malformed time stamp (time stamps must be separated by '-->'): "+i);s=s.slice(3),a(),e.endTime=r(),a(),n(s,e);}function Bp(s){return s.replace(/<br(?: \/)?>/gi,`
1379
+ `)}var yu=class{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new Eu,this.regionList=[],this.cue=null,this.oncue=void 0,this.onparsingerror=void 0,this.onflush=void 0;}parse(e){let t=this;e&&(t.buffer+=t.decoder.decode(e,{stream:true}));function i(){let n=t.buffer,a=0;for(n=Bp(n);a<n.length&&n[a]!=="\r"&&n[a]!==`
1380
1380
  `;)++a;let o=n.slice(0,a);return n[a]==="\r"&&++a,n[a]===`
1381
- `&&++a,t.buffer=n.slice(a),o}function r(n){Np(n,function(a,o){},/:/);}try{let n="";if(t.state==="INITIAL"){if(!/\r\n|\n/.test(t.buffer))return this;n=i();let o=n.match(/^()?WEBVTT([ \t].*)?$/);if(!(o!=null&&o[0]))throw new Error("Malformed WebVTT signature.");t.state="HEADER";}let a=!1;for(;t.buffer;){if(!/\r\n|\n/.test(t.buffer))return this;switch(a?a=!1:n=i(),t.state){case "HEADER":/:/.test(n)?r(n):n||(t.state="ID");continue;case "NOTE":n||(t.state="ID");continue;case "ID":if(/^NOTE($|[ \t])/.test(n)){t.state="NOTE";break}if(!n)continue;if(t.cue=new qu(0,0,""),t.state="CUE",n.indexOf("-->")===-1){t.cue.id=n;continue}case "CUE":if(!t.cue){t.state="BADCUE";continue}try{pA(n,t.cue,t.regionList);}catch{t.cue=null,t.state="BADCUE";continue}t.state="CUETEXT";continue;case "CUETEXT":{let o=n.indexOf("-->")!==-1;if(!n||o&&(a=!0)){t.oncue&&t.cue&&t.oncue(t.cue),t.cue=null,t.state="ID";continue}if(t.cue===null)continue;t.cue.text&&(t.cue.text+=`
1381
+ `&&++a,t.buffer=n.slice(a),o}function r(n){Up(n,function(a,o){},/:/);}try{let n="";if(t.state==="INITIAL"){if(!/\r\n|\n/.test(t.buffer))return this;n=i();let o=n.match(/^()?WEBVTT([ \t].*)?$/);if(!(o!=null&&o[0]))throw new Error("Malformed WebVTT signature.");t.state="HEADER";}let a=!1;for(;t.buffer;){if(!/\r\n|\n/.test(t.buffer))return this;switch(a?a=!1:n=i(),t.state){case "HEADER":/:/.test(n)?r(n):n||(t.state="ID");continue;case "NOTE":n||(t.state="ID");continue;case "ID":if(/^NOTE($|[ \t])/.test(n)){t.state="NOTE";break}if(!n)continue;if(t.cue=new qu(0,0,""),t.state="CUE",n.indexOf("-->")===-1){t.cue.id=n;continue}case "CUE":if(!t.cue){t.state="BADCUE";continue}try{EA(n,t.cue,t.regionList);}catch{t.cue=null,t.state="BADCUE";continue}t.state="CUETEXT";continue;case "CUETEXT":{let o=n.indexOf("-->")!==-1;if(!n||o&&(a=!0)){t.oncue&&t.cue&&t.oncue(t.cue),t.cue=null,t.state="ID";continue}if(t.cue===null)continue;t.cue.text&&(t.cue.text+=`
1382
1382
  `),t.cue.text+=n;}continue;case "BADCUE":n||(t.state="ID");}}}catch{t.state==="CUETEXT"&&t.cue&&t.oncue&&t.oncue(t.cue),t.cue=null,t.state=t.state==="INITIAL"?"BADWEBVTT":"BADCUE";}return this}flush(){let e=this;try{if((e.cue||e.state==="HEADER")&&(e.buffer+=`
1383
1383
 
1384
- `,e.parse()),e.state==="INITIAL"||e.state==="BADWEBVTT")throw new Error("Malformed WebVTT signature.")}catch(t){e.onparsingerror&&e.onparsingerror(t);}return e.onflush&&e.onflush(),this}},EA=/\r\n|\n\r|\n|\r/g,nc=function(e,t,i=0){return e.slice(i,i+t.length)===t},vA=function(e){let t=parseInt(e.slice(-3)),i=parseInt(e.slice(-6,-4)),r=parseInt(e.slice(-9,-7)),n=e.length>9?parseInt(e.substring(0,e.indexOf(":"))):0;if(!G(t)||!G(i)||!G(r)||!G(n))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${e}`);return t+=1e3*i,t+=60*1e3*r,t+=60*60*1e3*n,t};function ju(s,e,t){return hn(s.toString())+hn(e.toString())+hn(t)}var TA=function(e,t,i){let r=e[t],n=e[r.prevCC];if(!n||!n.new&&r.new){e.ccOffset=e.presentationOffset=r.start,r.new=false;return}for(;(a=n)!=null&&a.new;){var a;e.ccOffset+=r.start-n.start,r.new=false,r=n,n=e[r.prevCC];}e.presentationOffset=i;};function yA(s,e,t,i,r,n,a){let o=new yu,l=bt(new Uint8Array(s)).trim().replace(EA,`
1384
+ `,e.parse()),e.state==="INITIAL"||e.state==="BADWEBVTT")throw new Error("Malformed WebVTT signature.")}catch(t){e.onparsingerror&&e.onparsingerror(t);}return e.onflush&&e.onflush(),this}},vA=/\r\n|\n\r|\n|\r/g,nc=function(e,t,i=0){return e.slice(i,i+t.length)===t},TA=function(e){let t=parseInt(e.slice(-3)),i=parseInt(e.slice(-6,-4)),r=parseInt(e.slice(-9,-7)),n=e.length>9?parseInt(e.substring(0,e.indexOf(":"))):0;if(!G(t)||!G(i)||!G(r)||!G(n))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${e}`);return t+=1e3*i,t+=60*1e3*r,t+=60*60*1e3*n,t};function ju(s,e,t){return hn(s.toString())+hn(e.toString())+hn(t)}var yA=function(e,t,i){let r=e[t],n=e[r.prevCC];if(!n||!n.new&&r.new){e.ccOffset=e.presentationOffset=r.start,r.new=false;return}for(;(a=n)!=null&&a.new;){var a;e.ccOffset+=r.start-n.start,r.new=false,r=n,n=e[r.prevCC];}e.presentationOffset=i;};function SA(s,e,t,i,r,n,a){let o=new yu,l=bt(new Uint8Array(s)).trim().replace(vA,`
1385
1385
  `).split(`
1386
- `),d=[],c=e?Xy(e.baseTime,e.timescale):0,u="00:00.000",h=0,f=0,m,p=true;o.oncue=function(E){let v=t[i],T=t.ccOffset,S=(h-c)/9e4;if(v!=null&&v.new&&(f!==void 0?T=t.ccOffset=v.start:TA(t,i,S)),S){if(!e){m=new Error("Missing initPTS for VTT MPEGTS");return}T=S-t.presentationOffset;}let A=E.endTime-E.startTime,b=St((E.startTime+T-f)*9e4,r*9e4)/9e4;E.startTime=Math.max(b,0),E.endTime=Math.max(b+A,0);let D=E.text.trim();E.text=decodeURIComponent(encodeURIComponent(D)),E.id||(E.id=ju(E.startTime,E.endTime,D)),E.endTime>0&&d.push(E);},o.onparsingerror=function(E){m=E;},o.onflush=function(){if(m){a(m);return}n(d);},l.forEach(E=>{if(p)if(nc(E,"X-TIMESTAMP-MAP=")){p=false,E.slice(16).split(",").forEach(v=>{nc(v,"LOCAL:")?u=v.slice(6):nc(v,"MPEGTS:")&&(h=parseInt(v.slice(7)));});try{f=vA(u)/1e3;}catch(v){m=v;}return}else E===""&&(p=false);o.parse(E+`
1387
- `);}),o.flush();}var ac="stpp.ttml.im1t",Bp=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,$p=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,SA={left:"start",center:"center",right:"end",start:"start",end:"end"};function mg(s,e,t,i){let r=le(new Uint8Array(s),["mdat"]);if(r.length===0){i(new Error("Could not parse IMSC1 mdat"));return}let n=r.map(o=>bt(o)),a=Qy(e.baseTime,1,e.timescale);try{n.forEach(o=>t(AA(o,a)));}catch(o){i(o);}}function AA(s,e){let r=new DOMParser().parseFromString(s,"text/xml").getElementsByTagName("tt")[0];if(!r)throw new Error("Invalid ttml");let n={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:0},a=Object.keys(n).reduce((u,h)=>(u[h]=r.getAttribute(`ttp:${h}`)||n[h],u),{}),o=r.getAttribute("xml:space")!=="preserve",l=gg(oc(r,"styling","style")),d=gg(oc(r,"layout","region")),c=oc(r,"body","[begin]");return [].map.call(c,u=>{let h=Gp(u,o);if(!h||!u.hasAttribute("begin"))return null;let f=dc(u.getAttribute("begin"),a),m=dc(u.getAttribute("dur"),a),p=dc(u.getAttribute("end"),a);if(f===null)throw pg(u);if(p===null){if(m===null)throw pg(u);p=f+m;}let E=new qu(f-e,p-e,h);E.id=ju(E.startTime,E.endTime,E.text);let v=d[u.getAttribute("region")],T=l[u.getAttribute("style")],S=bA(v,T,l),{textAlign:A}=S;if(A){let b=SA[A];b&&(E.lineAlign=b),E.align=A;}return ye(E,S),E}).filter(u=>u!==null)}function oc(s,e,t){let i=s.getElementsByTagName(e)[0];return i?[].slice.call(i.querySelectorAll(t)):[]}function gg(s){return s.reduce((e,t)=>{let i=t.getAttribute("xml:id");return i&&(e[i]=t),e},{})}function Gp(s,e){return [].slice.call(s.childNodes).reduce((t,i,r)=>{var n;return i.nodeName==="br"&&r?t+`
1388
- `:(n=i.childNodes)!=null&&n.length?Gp(i,e):e?t+i.textContent.trim().replace(/\s+/g," "):t+i.textContent},"")}function bA(s,e,t){let i="http://www.w3.org/ns/ttml#styling",r=null,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)=>{let d=lc(e,i,l)||lc(s,i,l)||lc(r,i,l);return d&&(o[l]=d),o},{})}function lc(s,e,t){return s&&s.hasAttributeNS(e,t)?s.getAttributeNS(e,t):null}function pg(s){return new Error(`Could not parse ttml timestamp ${s}`)}function dc(s,e){if(!s)return null;let t=Fp(s);return t===null&&(Bp.test(s)?t=_A(s,e):$p.test(s)&&(t=IA(s,e))),t}function _A(s,e){let t=Bp.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 IA(s,e){let t=$p.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}var tr=class{constructor(e,t){this.timelineController=void 0,this.cueRanges=[],this.trackName=void 0,this.startTime=null,this.endTime=null,this.screen=null,this.timelineController=e,this.trackName=t;}dispatchCue(){this.startTime!==null&&(this.timelineController.addCues(this.trackName,this.startTime,this.endTime,this.screen,this.cueRanges),this.startTime=null);}newCue(e,t,i){(this.startTime===null||this.startTime>e)&&(this.startTime=e),this.endTime=t,this.screen=i,this.timelineController.createCaptionsTrack(this.trackName);}reset(){this.cueRanges=[],this.startTime=null;}},Su=class{constructor(e){this.hls=void 0,this.media=null,this.config=void 0,this.enabled=true,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=vg(),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(g.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(g.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(g.MANIFEST_LOADING,this.onManifestLoading,this),e.on(g.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(g.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(g.FRAG_LOADING,this.onFragLoading,this),e.on(g.FRAG_LOADED,this.onFragLoaded,this),e.on(g.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.on(g.FRAG_DECRYPTED,this.onFragDecrypted,this),e.on(g.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(g.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.on(g.BUFFER_FLUSHING,this.onBufferFlushing,this);}destroy(){let{hls:e}=this;e.off(g.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(g.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(g.MANIFEST_LOADING,this.onManifestLoading,this),e.off(g.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(g.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(g.FRAG_LOADING,this.onFragLoading,this),e.off(g.FRAG_LOADED,this.onFragLoaded,this),e.off(g.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.off(g.FRAG_DECRYPTED,this.onFragDecrypted,this),e.off(g.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(g.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.off(g.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.media=null,this.cea608Parser1=this.cea608Parser2=void 0;}initCea608Parsers(){let e=new tr(this,"textTrack1"),t=new tr(this,"textTrack2"),i=new tr(this,"textTrack3"),r=new tr(this,"textTrack4");this.cea608Parser1=new dl(1,e,t),this.cea608Parser2=new dl(3,i,r);}addCues(e,t,i,r,n){let a=false;for(let o=n.length;o--;){let l=n[o],d=LA(l[0],l[1],t,i);if(d>=0&&(l[0]=Math.min(l[0],t),l[1]=Math.max(l[1],i),a=true,d/(i-t)>.5))return}if(a||n.push([t,i]),this.config.renderTextTracksNatively){let o=this.captionsTracks[e];this.Cues.newCue(o,t,i,r);}else {let o=this.Cues.newCue(null,t,i,r);this.hls.trigger(g.CUES_PARSED,{type:"captions",cues:o,track:e});}}onInitPtsFound(e,{frag:t,id:i,initPTS:r,timescale:n,trackId:a}){let{unparsedVttFrags:o}=this;i===W.MAIN&&(this.initPTS[t.cc]={baseTime:r,timescale:n,trackId:a}),o.length&&(this.unparsedVttFrags=[],o.forEach(l=>{this.initPTS[l.frag.cc]?this.onFragLoaded(g.FRAG_LOADED,l):this.hls.trigger(g.SUBTITLE_FRAG_PROCESSED,{success:false,frag:l.frag,error:new Error("Subtitle discontinuity domain does not match main")});}));}getExistingTrack(e,t){let{media:i}=this;if(i)for(let r=0;r<i.textTracks.length;r++){let n=i.textTracks[r];if(Eg(n,{name:e,lang:t,characteristics:"transcribes-spoken-dialog,describes-music-and-sound"}))return n}return null}createCaptionsTrack(e){this.config.renderTextTracksNatively?this.createNativeTrack(e):this.createNonNativeTrack(e);}createNativeTrack(e){if(this.captionsTracks[e])return;let{captionsProperties:t,captionsTracks:i,media:r}=this,{label:n,languageCode:a}=t[e],o=this.getExistingTrack(n,a);if(o)i[e]=o,er(i[e]),Mp(i[e],r);else {let l=this.createTextTrack("captions",n,a);l&&(l[e]=true,i[e]=l);}}createNonNativeTrack(e){if(this.nonNativeCaptionsTracks[e])return;let t=this.captionsProperties[e];if(!t)return;let i=t.label,r={_id:e,label:i,kind:"captions",default:t.media?!!t.media.default:false,closedCaptions:t.media};this.nonNativeCaptionsTracks[e]=r,this.hls.trigger(g.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[r]});}createTextTrack(e,t,i){let r=this.media;if(r)return r.addTextTrack(e,t,i)}onMediaAttaching(e,t){this.media=t.media,t.mediaSource||this._cleanTracks();}onMediaDetaching(e,t){let i=!!t.transferMedia;if(this.media=null,i)return;let{captionsTracks:r}=this;Object.keys(r).forEach(n=>{er(r[n]),delete r[n];}),this.nonNativeCaptionsTracks={};}onManifestLoading(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=vg(),this._cleanTracks(),this.tracks=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.textTracks=[],this.unparsedVttFrags=[],this.initPTS=[],this.cea608Parser1&&this.cea608Parser2&&(this.cea608Parser1.reset(),this.cea608Parser2.reset());}_cleanTracks(){let{media:e}=this;if(!e)return;let t=e.textTracks;if(t)for(let i=0;i<t.length;i++)er(t[i]);}onSubtitleTracksUpdated(e,t){let i=t.subtitleTracks||[],r=i.some(n=>n.textCodec===ac);if(this.config.enableWebVTT||r&&this.config.enableIMSC1){if(yp(this.tracks,i)){this.tracks=i;return}if(this.textTracks=[],this.tracks=i,this.config.renderTextTracksNatively){let a=this.media,o=a?Uo(a.textTracks):null;if(this.tracks.forEach((l,d)=>{let c;if(o){let u=null;for(let h=0;h<o.length;h++)if(o[h]&&Eg(o[h],l)){u=o[h],o[h]=null;break}u&&(c=u);}if(c)er(c);else {let u=Hp(l);c=this.createTextTrack(u,l.name,l.lang),c&&(c.mode="disabled");}c&&this.textTracks.push(c);}),o!=null&&o.length){let l=o.filter(d=>d!==null).map(d=>d.label);l.length&&this.hls.logger.warn(`Media element contains unused subtitle tracks: ${l.join(", ")}. Replace media element for each source to clear TextTracks and captions menu.`);}}else if(this.tracks.length){let a=this.tracks.map(o=>({label:o.name,kind:o.type.toLowerCase(),default:o.default,subtitleTrack:o}));this.hls.trigger(g.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:a});}}}onManifestLoaded(e,t){this.config.enableCEA708Captions&&t.captions&&t.captions.forEach(i=>{let r=/(?:CC|SERVICE)([1-4])/.exec(i.instreamId);if(!r)return;let n=`textTrack${r[1]}`,a=this.captionsProperties[n];a&&(a.label=i.name,i.lang&&(a.languageCode=i.lang),a.media=i);});}closedCaptionsForLevel(e){let t=this.hls.levels[e.level];return t?.attrs["CLOSED-CAPTIONS"]}onFragLoading(e,t){if(this.enabled&&t.frag.type===W.MAIN){var i,r;let{cea608Parser1:n,cea608Parser2:a,lastSn:o}=this,{cc:l,sn:d}=t.frag,c=(i=(r=t.part)==null?void 0:r.index)!=null?i:-1;n&&a&&(d!==o+1||d===o&&c!==this.lastPartIndex+1||l!==this.lastCc)&&(n.reset(),a.reset()),this.lastCc=l,this.lastSn=d,this.lastPartIndex=c;}}onFragLoaded(e,t){let{frag:i,payload:r}=t;if(i.type===W.SUBTITLE)if(r.byteLength){let n=i.decryptdata,a="stats"in t;if(n==null||!n.encrypted||a){let o=this.tracks[i.level],l=this.vttCCs;l[i.cc]||(l[i.cc]={start:i.start,prevCC:this.prevCC,new:true},this.prevCC=i.cc),o&&o.textCodec===ac?this._parseIMSC1(i,r):this._parseVTTs(t);}}else this.hls.trigger(g.SUBTITLE_FRAG_PROCESSED,{success:false,frag:i,error:new Error("Empty subtitle payload")});}_parseIMSC1(e,t){let i=this.hls;mg(t,this.initPTS[e.cc],r=>{this._appendCues(r,e.level),i.trigger(g.SUBTITLE_FRAG_PROCESSED,{success:true,frag:e});},r=>{i.logger.log(`Failed to parse IMSC1: ${r}`),i.trigger(g.SUBTITLE_FRAG_PROCESSED,{success:false,frag:e,error:r});});}_parseVTTs(e){var t;let{frag:i,payload:r}=e,{initPTS:n,unparsedVttFrags:a}=this,o=n.length-1;if(!n[i.cc]&&o===-1){a.push(e);return}let l=this.hls,d=(t=i.initSegment)!=null&&t.data?Dt(i.initSegment.data,new Uint8Array(r)).buffer:r;yA(d,this.initPTS[i.cc],this.vttCCs,i.cc,i.start,c=>{this._appendCues(c,i.level),l.trigger(g.SUBTITLE_FRAG_PROCESSED,{success:true,frag:i});},c=>{let u=c.message==="Missing initPTS for VTT MPEGTS";u?a.push(e):this._fallbackToIMSC1(i,r),l.logger.log(`Failed to parse VTT cue: ${c}`),!(u&&o>i.cc)&&l.trigger(g.SUBTITLE_FRAG_PROCESSED,{success:false,frag:i,error:c});});}_fallbackToIMSC1(e,t){let i=this.tracks[e.level];i.textCodec||mg(t,this.initPTS[e.cc],()=>{i.textCodec=ac,this._parseIMSC1(e,t);},()=>{i.textCodec="wvtt";});}_appendCues(e,t){let i=this.hls;if(this.config.renderTextTracksNatively){let r=this.textTracks[t];if(!r||r.mode==="disabled")return;e.forEach(n=>Pp(r,n));}else {let r=this.tracks[t];if(!r)return;let n=r.default?"default":"subtitles"+t;i.trigger(g.CUES_PARSED,{type:"subtitles",cues:e,track:n});}}onFragDecrypted(e,t){let{frag:i}=t;i.type===W.SUBTITLE&&this.onFragLoaded(g.FRAG_LOADED,t);}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={};}onFragParsingUserdata(e,t){if(!this.enabled||!this.config.enableCEA708Captions)return;let{frag:i,samples:r}=t;if(!(i.type===W.MAIN&&this.closedCaptionsForLevel(i)==="NONE"))for(let n=0;n<r.length;n++){let a=r[n].bytes;if(a){this.cea608Parser1||this.initCea608Parsers();let o=this.extractCea608Data(a);this.cea608Parser1.addData(r[n].pts,o[0]),this.cea608Parser2.addData(r[n].pts,o[1]);}}}onBufferFlushing(e,{startOffset:t,endOffset:i,endOffsetSubtitles:r,type:n}){let{media:a}=this;if(!(!a||a.currentTime<i)){if(!n||n==="video"){let{captionsTracks:o}=this;Object.keys(o).forEach(l=>nu(o[l],t,i));}if(this.config.renderTextTracksNatively&&t===0&&r!==void 0){let{textTracks:o}=this;Object.keys(o).forEach(l=>nu(o[l],t,r));}}}extractCea608Data(e){let t=[[],[]],i=e[0]&31,r=2;for(let n=0;n<i;n++){let a=e[r++],o=127&e[r++],l=127&e[r++];if(o===0&&l===0)continue;if((4&a)!==0){let c=3&a;(c===0||c===1)&&(t[c].push(o),t[c].push(l));}}return t}};function Hp(s){return s.characteristics&&/transcribes-spoken-dialog/gi.test(s.characteristics)&&/describes-music-and-sound/gi.test(s.characteristics)?"captions":"subtitles"}function Eg(s,e){return !!s&&s.kind===Hp(e)&&qc(e,s)}function LA(s,e,t,i){return Math.min(e,i)-Math.max(s,t)}function vg(){return {ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:true}}}var xA=/\s/,RA={newCue(s,e,t,i){let r=[],n,a,o,l,d,c=self.VTTCue||self.TextTrackCue;for(let h=0;h<i.rows.length;h++)if(n=i.rows[h],o=true,l=0,d="",!n.isEmpty()){var u;for(let p=0;p<n.chars.length;p++)xA.test(n.chars[p].uchar)&&o?l++:(d+=n.chars[p].uchar,o=false);n.cueStartTime=e,e===t&&(t+=1e-4),l>=16?l--:l++;let f=Up(d.trim()),m=ju(e,t,f);s!=null&&(u=s.cues)!=null&&u.getCueById(m)||(a=new c(e,t,f),a.id=m,a.line=h+1,a.align="left",a.position=10+Math.min(80,Math.floor(l*8/32)*10),r.push(a));}return s&&r.length&&(r.sort((h,f)=>h.line==="auto"||f.line==="auto"?0:h.line>8&&f.line>8?f.line-h.line:h.line-f.line),r.forEach(h=>Pp(s,h))),r}};function kA(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch{}return false}var DA=/(\d+)-(\d+)\/(\d+)/,cl=class{constructor(e){this.fetchSetup=void 0,this.requestTimeout=void 0,this.request=null,this.response=null,this.controller=void 0,this.context=null,this.config=null,this.callbacks=null,this.stats=void 0,this.loader=null,this.fetchSetup=e.fetchSetup||wA,this.controller=new self.AbortController,this.stats=new mn;}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=true,this.controller.abort());}abort(){var e;this.abortInternal(),(e=this.callbacks)!=null&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.response);}load(e,t,i){let r=this.stats;if(r.loading.start)throw new Error("Loader can only be used once.");r.loading.start=self.performance.now();let n=CA(e,this.controller.signal),a=e.responseType==="arraybuffer",o=a?"byteLength":"length",{maxTimeToFirstByteMs:l,maxLoadTimeMs:d}=t.loadPolicy;this.context=e,this.config=t,this.callbacks=i,this.request=this.fetchSetup(e,n),self.clearTimeout(this.requestTimeout),t.timeout=l&&G(l)?l:d,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(r,e,this.response));},t.timeout),(_n(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then(u=>{var h;this.response=this.loader=u;let f=Math.max(self.performance.now(),r.loading.start);if(self.clearTimeout(this.requestTimeout),t.timeout=d,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(r,e,this.response));},d-(f-r.loading.start)),!u.ok){let{status:p,statusText:E}=u;throw new Au(E||"fetch, bad network response",p,u)}r.loading.first=f,r.total=PA(u.headers)||r.total;let m=(h=this.callbacks)==null?void 0:h.onProgress;return m&&G(t.highWaterMark)?this.loadProgressively(u,r,e,t.highWaterMark,m):a?u.arrayBuffer():e.responseType==="json"?u.json():u.text()}).then(u=>{var h,f;let m=this.response;if(!m)throw new Error("loader destroyed");self.clearTimeout(this.requestTimeout),r.loading.end=Math.max(self.performance.now(),r.loading.first);let p=u[o];p&&(r.loaded=r.total=p);let E={url:m.url,data:u,code:m.status},v=(h=this.callbacks)==null?void 0:h.onProgress;v&&!G(t.highWaterMark)&&v(r,e,u,m),(f=this.callbacks)==null||f.onSuccess(E,r,e,m);}).catch(u=>{var h;if(self.clearTimeout(this.requestTimeout),r.aborted)return;let f=u&&u.code||0,m=u?u.message:null;(h=this.callbacks)==null||h.onError({code:f,text:m},e,u?u.details:null,r);});}getCacheAge(){let e=null;if(this.response){let t=this.response.headers.get("age");e=t?parseFloat(t):null;}return e}getResponseHeader(e){return this.response?this.response.headers.get(e):null}loadProgressively(e,t,i,r=0,n){let a=new Jo,o=e.body.getReader(),l=()=>o.read().then(d=>{if(d.done)return a.dataLength&&n(t,i,a.flush().buffer,e),Promise.resolve(new ArrayBuffer(0));let c=d.value,u=c.length;return t.loaded+=u,u<r||a.dataLength?(a.push(c),a.dataLength>=r&&n(t,i,a.flush().buffer,e)):n(t,i,c.buffer,e),l()}).catch(()=>Promise.reject());return l()}};function CA(s,e){let t={method:"GET",mode:"cors",credentials:"same-origin",signal:e,headers:new self.Headers(ye({},s.headers))};return s.rangeEnd&&t.headers.set("Range","bytes="+s.rangeStart+"-"+String(s.rangeEnd-1)),t}function MA(s){let e=DA.exec(s);if(e)return parseInt(e[2])-parseInt(e[1])+1}function PA(s){let e=s.get("Content-Range");if(e){let i=MA(e);if(G(i))return i}let t=s.get("Content-Length");if(t)return parseInt(t)}function wA(s,e){return new self.Request(s.url,e)}var Au=class extends Error{constructor(e,t,i){super(e),this.code=void 0,this.details=void 0,this.code=t,this.details=i;}},OA=/^age:\s*[\d.]+\s*$/im,ul=class{constructor(e){this.xhrSetup=void 0,this.requestTimeout=void 0,this.retryTimeout=void 0,this.retryDelay=void 0,this.config=null,this.callbacks=null,this.context=null,this.loader=null,this.stats=void 0,this.xhrSetup=e&&e.xhrSetup||null,this.stats=new mn,this.retryDelay=0;}destroy(){this.callbacks=null,this.abortInternal(),this.loader=null,this.config=null,this.context=null,this.xhrSetup=null;}abortInternal(){let e=this.loader;self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),e&&(e.onreadystatechange=null,e.onprogress=null,e.readyState!==4&&(this.stats.aborted=true,e.abort()));}abort(){var e;this.abortInternal(),(e=this.callbacks)!=null&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.loader);}load(e,t,i){if(this.stats.loading.start)throw new Error("Loader can only be used once.");this.stats.loading.start=self.performance.now(),this.context=e,this.config=t,this.callbacks=i,this.loadInternal();}loadInternal(){let{config:e,context:t}=this;if(!e||!t)return;let i=this.loader=new self.XMLHttpRequest,r=this.stats;r.loading.first=0,r.loaded=0,r.aborted=false;let n=this.xhrSetup;n?Promise.resolve().then(()=>{if(!(this.loader!==i||this.stats.aborted))return n(i,t.url)}).catch(a=>{if(!(this.loader!==i||this.stats.aborted))return i.open("GET",t.url,true),n(i,t.url)}).then(()=>{this.loader!==i||this.stats.aborted||this.openAndSendXhr(i,t,e);}).catch(a=>{var o;(o=this.callbacks)==null||o.onError({code:i.status,text:a.message},t,i,r);}):this.openAndSendXhr(i,t,e);}openAndSendXhr(e,t,i){e.readyState||e.open("GET",t.url,true);let r=t.headers,{maxTimeToFirstByteMs:n,maxLoadTimeMs:a}=i.loadPolicy;if(r)for(let o in r)e.setRequestHeader(o,r[o]);t.rangeEnd&&e.setRequestHeader("Range","bytes="+t.rangeStart+"-"+(t.rangeEnd-1)),e.onreadystatechange=this.readystatechange.bind(this),e.onprogress=this.loadprogress.bind(this),e.responseType=t.responseType,self.clearTimeout(this.requestTimeout),i.timeout=n&&G(n)?n:a,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),i.timeout),e.send();}readystatechange(){let{context:e,loader:t,stats:i}=this;if(!e||!t)return;let 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;let d=t.status,c=t.responseType==="text"?t.responseText:null;if(d>=200&&d<300){let m=c??t.response;if(m!=null){var a,o;i.loading.end=Math.max(self.performance.now(),i.loading.first);let p=t.responseType==="arraybuffer"?m.byteLength:m.length;i.loaded=i.total=p,i.bwEstimate=i.total*8e3/(i.loading.end-i.loading.first);let E=(a=this.callbacks)==null?void 0:a.onProgress;E&&E(i,e,m,t);let v={url:t.responseURL,data:m,code:d};(o=this.callbacks)==null||o.onSuccess(v,i,e,t);return}}let u=n.loadPolicy.errorRetry,h=i.retry,f={url:e.url,data:void 0,code:d};if(qo(u,h,false,f))this.retry(u);else {var l;Te.error(`${d} while loading ${e.url}`),(l=this.callbacks)==null||l.onError({code:d,text:t.statusText},e,t,i);}}}loadtimeout(){if(!this.config)return;let e=this.config.loadPolicy.timeoutRetry,t=this.stats.retry;if(qo(e,t,true))this.retry(e);else {var i;Te.warn(`timeout while loading ${(i=this.context)==null?void 0:i.url}`);let r=this.callbacks;r&&(this.abortInternal(),r.onTimeout(this.stats,this.context,this.loader));}}retry(e){let{context:t,stats:i}=this;this.retryDelay=Fu(e,i.retry),i.retry++,Te.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${t?.url}, retrying ${i.retry}/${e.maxNumRetry} in ${this.retryDelay}ms`),this.abortInternal(),this.loader=null,self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(this.loadInternal.bind(this),this.retryDelay);}loadprogress(e){let t=this.stats;t.loaded=e.loaded,e.lengthComputable&&(t.total=e.total);}getCacheAge(){let e=null;if(this.loader&&OA.test(this.loader.getAllResponseHeaders())){let t=this.loader.getResponseHeader("age");e=t?parseFloat(t):null;}return e}getResponseHeader(e){return this.loader&&new RegExp(`^${e}:\\s*[\\d.]+\\s*$`,"im").test(this.loader.getAllResponseHeaders())?this.loader.getResponseHeader(e):null}},FA={maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null},NA=ve(ve({autoStartLoad:true,startPosition:-1,defaultAudioCodec:void 0,debug:false,capLevelOnFPSDrop:false,capLevelToPlayerSize:false,ignoreDevicePixelRatio:false,maxDevicePixelRatio:Number.POSITIVE_INFINITY,preferManagedMediaSource:true,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,frontBufferFlushThreshold:1/0,startOnSegmentBoundary:false,maxBufferSize:60*1e3*1e3,maxFragLookUpTolerance:.25,maxBufferHole:.1,detectStallWithCurrentTimeMs:1250,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,nudgeOnVideoHole:true,liveSyncMode:"edge",liveSyncDurationCount:3,liveSyncOnStallIncrease:1,liveMaxLatencyDurationCount:1/0,liveSyncDuration:void 0,liveMaxLatencyDuration:void 0,maxLiveSyncPlaybackRate:1,liveDurationInfinity:false,liveBackBufferLength:null,maxMaxBufferLength:600,enableWorker:true,workerPath:null,enableSoftwareAES:true,startLevel:void 0,startFragPrefetch:false,fpsDroppedMonitoringPeriod:5e3,fpsDroppedMonitoringThreshold:.2,appendErrorMaxRetry:3,ignorePlaylistParsingErrors:false,loader:ul,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:Tc,bufferController:Xc,capLevelController:Zc,errorController:Sc,fpsController:ru,stretchShortVideoTrack:false,maxAudioFramesDrift:1,forceKeyFrameOnDiscontinuity:true,abrEwmaFastLive:3,abrEwmaSlowLive:9,abrEwmaFastVoD:3,abrEwmaSlowVoD:9,abrEwmaDefaultEstimate:5e5,abrEwmaDefaultEstimateMax:5e6,abrBandWidthFactor:.95,abrBandWidthUpFactor:.7,abrMaxWithRealBitrate:false,maxStarvationDelay:4,maxLoadingDelay:4,minAutoBitrate:0,emeEnabled:false,widevineLicenseUrl:void 0,drmSystems:{},drmSystemOptions:{},requestMediaKeySystemAccessFunc:Yg,requireKeySystemAccessOnStart:false,testBandwidth:true,progressive:false,lowLatencyMode:true,cmcd:void 0,enableDateRangeMetadataCues:true,enableEmsgMetadataCues:true,enableEmsgKLVMetadata:false,enableID3MetadataCues:true,enableInterstitialPlayback:true,interstitialAppendInPlace:true,interstitialLiveLookAhead:10,useMediaCapabilities:true,preserveManualLevelOnError:false,certLoadPolicy:{default:FA},keyLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"},errorRetry:{maxNumRetry:8,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"}}},manifestLoadPolicy:{default:{maxTimeToFirstByteMs:1/0,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},playlistLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:2,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},fragLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:12e4,timeoutRetry:{maxNumRetry:4,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:6,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},steeringManifestLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},interstitialAssetListLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:3e4,timeoutRetry:{maxNumRetry:0,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:0,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},manifestLoadingTimeOut:1e4,manifestLoadingMaxRetry:1,manifestLoadingRetryDelay:1e3,manifestLoadingMaxRetryTimeout:64e3,levelLoadingTimeOut:1e4,levelLoadingMaxRetry:4,levelLoadingRetryDelay:1e3,levelLoadingMaxRetryTimeout:64e3,fragLoadingTimeOut:2e4,fragLoadingMaxRetry:6,fragLoadingRetryDelay:1e3,fragLoadingMaxRetryTimeout:64e3},UA()),{},{subtitleStreamController:hu,subtitleTrackController:au,timelineController:Su,audioStreamController:Yc,audioTrackController:jc,emeController:nl,cmcdController:iu,contentSteeringController:su,interstitialsController:uu});function UA(){return {cueHandler:RA,enableWebVTT:true,enableIMSC1:true,enableCEA708Captions:true,captionsTextTrack1Label:"English",captionsTextTrack1LanguageCode:"en",captionsTextTrack2Label:"Spanish",captionsTextTrack2LanguageCode:"es",captionsTextTrack3Label:"Unknown CC",captionsTextTrack3LanguageCode:"",captionsTextTrack4Label:"Unknown CC",captionsTextTrack4LanguageCode:"",renderTextTracksNatively:true}}function BA(s,e,t){if((e.liveSyncDurationCount||e.liveMaxLatencyDurationCount)&&(e.liveSyncDuration||e.liveMaxLatencyDuration))throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");if(e.liveMaxLatencyDurationCount!==void 0&&(e.liveSyncDurationCount===void 0||e.liveMaxLatencyDurationCount<=e.liveSyncDurationCount))throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(e.liveMaxLatencyDuration!==void 0&&(e.liveSyncDuration===void 0||e.liveMaxLatencyDuration<=e.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');let i=bu(s),r=["manifest","level","frag"],n=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return r.forEach(a=>{let o=`${a==="level"?"playlist":a}LoadPolicy`,l=e[o]===void 0,d=[];n.forEach(c=>{let u=`${a}Loading${c}`,h=e[u];if(h!==void 0&&l){d.push(u);let f=i[o].default;switch(e[o]={default:f},c){case "TimeOut":f.maxLoadTimeMs=h,f.maxTimeToFirstByteMs=h;break;case "MaxRetry":f.errorRetry.maxNumRetry=h,f.timeoutRetry.maxNumRetry=h;break;case "RetryDelay":f.errorRetry.retryDelayMs=h,f.timeoutRetry.retryDelayMs=h;break;case "MaxRetryTimeout":f.errorRetry.maxRetryDelayMs=h,f.timeoutRetry.maxRetryDelayMs=h;break}}}),d.length&&t.warn(`hls.js config: "${d.join('", "')}" setting(s) are deprecated, use "${o}": ${Ae(e[o])}`);}),ve(ve({},i),e)}function bu(s){return s&&typeof s=="object"?Array.isArray(s)?s.map(bu):Object.keys(s).reduce((e,t)=>(e[t]=bu(s[t]),e),{}):s}function $A(s,e){let t=s.loader;t!==cl&&t!==ul?(e.log("[config]: Custom loader detected, cannot enable progressive streaming"),s.progressive=false):kA()&&(s.loader=cl,s.progressive=true,s.enableSoftwareAES=true,e.log("[config]: Progressive streaming enabled, using FetchLoader"));}var Bo=2,GA=.1,HA=.05,KA=100,_u=class extends jo{constructor(e,t){super("gap-controller",e.logger),this.hls=void 0,this.fragmentTracker=void 0,this.media=null,this.mediaSource=void 0,this.nudgeRetry=0,this.stallReported=false,this.stalled=null,this.moved=false,this.seeking=false,this.buffered={},this.lastCurrentTime=0,this.ended=0,this.waiting=0,this.onMediaPlaying=()=>{this.ended=0,this.waiting=0;},this.onMediaWaiting=()=>{var i;(i=this.media)!=null&&i.seeking||(this.waiting=self.performance.now(),this.tick());},this.onMediaEnded=()=>{if(this.hls){var i;this.ended=((i=this.media)==null?void 0:i.currentTime)||1,this.hls.trigger(g.MEDIA_ENDED,{stalled:false});}},this.hls=e,this.fragmentTracker=t,this.registerListeners();}registerListeners(){let{hls:e}=this;e&&(e.on(g.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(g.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(g.BUFFER_APPENDED,this.onBufferAppended,this));}unregisterListeners(){let{hls:e}=this;e&&(e.off(g.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(g.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(g.BUFFER_APPENDED,this.onBufferAppended,this));}destroy(){super.destroy(),this.unregisterListeners(),this.media=this.hls=this.fragmentTracker=null,this.mediaSource=void 0;}onMediaAttached(e,t){this.setInterval(KA),this.mediaSource=t.mediaSource;let i=this.media=t.media;nt(i,"playing",this.onMediaPlaying),nt(i,"waiting",this.onMediaWaiting),nt(i,"ended",this.onMediaEnded);}onMediaDetaching(e,t){this.clearInterval();let{media:i}=this;i&&(ut(i,"playing",this.onMediaPlaying),ut(i,"waiting",this.onMediaWaiting),ut(i,"ended",this.onMediaEnded),this.media=null),this.mediaSource=void 0;}onBufferAppended(e,t){this.buffered=t.timeRanges;}get hasBuffered(){return Object.keys(this.buffered).length>0}tick(){var e;if(!((e=this.media)!=null&&e.readyState)||!this.hasBuffered)return;let t=this.media.currentTime;this.poll(t,this.lastCurrentTime),this.lastCurrentTime=t;}poll(e,t){var i,r;let n=(i=this.hls)==null?void 0:i.config;if(!n)return;let a=this.media;if(!a)return;let{seeking:o}=a,l=this.seeking&&!o,d=!this.seeking&&o,c=a.paused&&!o||a.ended||a.playbackRate===0;if(this.seeking=o,e!==t){t&&(this.ended=0),this.moved=true,o||(this.nudgeRetry=0,n.nudgeOnVideoHole&&!c&&e>t&&this.nudgeOnVideoHole(e,t)),this.waiting===0&&this.stallResolved(e);return}if(d||l){l&&this.stallResolved(e);return}if(c){this.nudgeRetry=0,this.stallResolved(e),!this.ended&&a.ended&&this.hls&&(this.ended=e||1,this.hls.trigger(g.MEDIA_ENDED,{stalled:false}));return}if(!re.getBuffered(a).length){this.nudgeRetry=0;return}let u=re.bufferInfo(a,e,0),h=u.nextStart||0,f=this.fragmentTracker;if(o&&f&&this.hls){let D=Tg(this.hls.inFlightFragments,e),I=u.len>Bo,k=!h||D||h-e>Bo&&!f.getPartialFragment(e);if(I||k)return;this.moved=false;}let m=(r=this.hls)==null?void 0:r.latestLevelDetails;if(!this.moved&&this.stalled!==null&&f){if(!(u.len>0)&&!h)return;let I=Math.max(h,u.start||0)-e,R=!!(m!=null&&m.live)?m.targetduration*2:Bo,L=Co(e,f);if(I>0&&(I<=R||L)){a.paused||this._trySkipBufferHole(L);return}}let p=n.detectStallWithCurrentTimeMs,E=self.performance.now(),v=this.waiting,T=this.stalled;if(T===null)if(v>0&&E-v<p)T=this.stalled=v;else {this.stalled=E;return}let S=E-T;if(!o&&(S>=p||v)&&this.hls){var A;if(((A=this.mediaSource)==null?void 0:A.readyState)==="ended"&&!(m!=null&&m.live)&&Math.abs(e-(m?.edge||0))<1){if(this.ended)return;this.ended=e||1,this.hls.trigger(g.MEDIA_ENDED,{stalled:true});return}if(this._reportStall(u),!this.media||!this.hls)return}let b=re.bufferInfo(a,e,n.maxBufferHole);this._tryFixBufferStall(b,S,e);}stallResolved(e){let t=this.stalled;if(t&&this.hls&&(this.stalled=null,this.stallReported)){let i=self.performance.now()-t;this.log(`playback not stuck anymore @${e}, after ${Math.round(i)}ms`),this.stallReported=false,this.waiting=0,this.hls.trigger(g.STALL_RESOLVED,{});}}nudgeOnVideoHole(e,t){var i;let r=this.buffered.video;if(this.hls&&this.media&&this.fragmentTracker&&(i=this.buffered.audio)!=null&&i.length&&r&&r.length>1&&e>r.end(0)){let n=re.bufferedInfo(re.timeRangesToArray(this.buffered.audio),e,0);if(n.len>1&&t>=n.start){let a=re.timeRangesToArray(r),o=re.bufferedInfo(a,t,0).bufferedIndex;if(o>-1&&o<a.length-1){let l=re.bufferedInfo(a,e,0).bufferedIndex,d=a[o].end,c=a[o+1].start;if((l===-1||l>o)&&c-d<1&&e-d<2){let u=new Error(`nudging playhead to flush pipeline after video hole. currentTime: ${e} hole: ${d} -> ${c} buffered index: ${l}`);this.warn(u.message),this.media.currentTime+=1e-6;let h=Co(e,this.fragmentTracker);h&&"fragment"in h?h=h.fragment:h||(h=void 0);let f=re.bufferInfo(this.media,e,0);this.hls.trigger(g.ERROR,{type:z.MEDIA_ERROR,details:x.BUFFER_SEEK_OVER_HOLE,fatal:false,error:u,reason:u.message,frag:h,buffer:f.len,bufferInfo:f});}}}}}_tryFixBufferStall(e,t,i){var r,n;let{fragmentTracker:a,media:o}=this,l=(r=this.hls)==null?void 0:r.config;if(!o||!a||!l)return;let d=(n=this.hls)==null?void 0:n.latestLevelDetails,c=Co(i,a);if((c||d!=null&&d.live&&i<d.fragmentStart)&&(this._trySkipBufferHole(c)||!this.media))return;let u=e.buffered,h=this.adjacentTraversal(e,i);(u&&u.length>1&&e.len>l.maxBufferHole||e.nextStart&&(e.nextStart-i<l.maxBufferHole||h))&&(t>l.highBufferWatchdogPeriod*1e3||this.waiting)&&(this.warn("Trying to nudge playhead over buffer-hole"),this._tryNudgeBuffer(e));}adjacentTraversal(e,t){let i=this.fragmentTracker,r=e.nextStart;if(i&&r){let n=i.getFragAtPos(t,W.MAIN),a=i.getFragAtPos(r,W.MAIN);if(n&&a)return a.sn-n.sn<2}return false}_reportStall(e){let{hls:t,media:i,stallReported:r,stalled:n}=this;if(!r&&n!==null&&i&&t){this.stallReported=true;let a=new Error(`Playback stalling at @${i.currentTime} due to low buffer (${Ae(e)})`);this.warn(a.message),t.trigger(g.ERROR,{type:z.MEDIA_ERROR,details:x.BUFFER_STALLED_ERROR,fatal:false,error:a,buffer:e.len,bufferInfo:e,stalled:{start:n}});}}_trySkipBufferHole(e){var t;let{fragmentTracker:i,media:r}=this,n=(t=this.hls)==null?void 0:t.config;if(!r||!i||!n)return 0;let a=r.currentTime,o=re.bufferInfo(r,a,0),l=a<o.start?o.start:o.nextStart;if(l&&this.hls){let c=o.len<=n.maxBufferHole,u=o.len>0&&o.len<1&&r.readyState<3,h=l-a;if(h>0&&(c||u)){if(h>n.maxBufferHole){let m=false;if(a===0){let p=i.getAppendedFrag(0,W.MAIN);p&&l<p.end&&(m=true);}if(!m&&e){var d;if(!((d=this.hls.loadLevelObj)!=null&&d.details)||Tg(this.hls.inFlightFragments,l))return 0;let E=false,v=e.end;for(;v<l;){let T=Co(v,i);if(T)v+=T.duration;else {E=true;break}}if(E)return 0}}let f=Math.max(l+HA,a+GA);if(this.warn(`skipping hole, adjusting currentTime from ${a} to ${f}`),this.moved=true,r.currentTime=f,!(e!=null&&e.gap)){let m=new Error(`fragment loaded with buffer holes, seeking from ${a} to ${f}`),p={type:z.MEDIA_ERROR,details:x.BUFFER_SEEK_OVER_HOLE,fatal:false,error:m,reason:m.message,buffer:o.len,bufferInfo:o};e&&("fragment"in e?p.part=e:p.frag=e),this.hls.trigger(g.ERROR,p);}return f}}return 0}_tryNudgeBuffer(e){let{hls:t,media:i,nudgeRetry:r}=this,n=t?.config;if(!i||!n)return 0;let a=i.currentTime;if(this.nudgeRetry++,r<n.nudgeMaxRetry){let o=a+(r+1)*n.nudgeOffset,l=new Error(`Nudging 'currentTime' from ${a} to ${o}`);this.warn(l.message),i.currentTime=o,t.trigger(g.ERROR,{type:z.MEDIA_ERROR,details:x.BUFFER_NUDGE_ON_STALL,error:l,fatal:false,buffer:e.len,bufferInfo:e});}else {let o=new Error(`Playhead still not moving while enough data buffered @${a} after ${n.nudgeMaxRetry} nudges`);this.error(o.message),t.trigger(g.ERROR,{type:z.MEDIA_ERROR,details:x.BUFFER_STALLED_ERROR,error:o,fatal:true,buffer:e.len,bufferInfo:e});}}};function Tg(s,e){let t=yg(s.main);if(t&&t.start<=e)return t;let i=yg(s.audio);return i&&i.start<=e?i:null}function yg(s){if(!s)return null;switch(s.state){case C.IDLE:case C.STOPPED:case C.ENDED:case C.ERROR:return null}return s.frag}function Co(s,e){return e.getAppendedFrag(s,W.MAIN)||e.getPartialFragment(s)}var VA=.25;function Iu(){if(!(typeof self>"u"))return self.VTTCue||self.TextTrackCue}function cc(s,e,t,i,r){let n=new s(e,t,"");try{n.value=i,r&&(n.type=r);}catch{n=new s(e,t,Ae(r?ve({type:r},i):i));}return n}var Mo=(()=>{let s=Iu();try{s&&new s(0,Number.POSITIVE_INFINITY,"");}catch{return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})(),Lu=class{constructor(e){this.hls=void 0,this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.removeCues=true,this.assetCue=void 0,this.onEventCueEnter=()=>{this.hls&&this.hls.trigger(g.EVENT_CUE_ENTER,{});},this.hls=e,this._registerListeners();}destroy(){this._unregisterListeners(),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=this.onEventCueEnter=null;}_registerListeners(){let{hls:e}=this;e&&(e.on(g.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(g.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(g.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(g.MANIFEST_LOADING,this.onManifestLoading,this),e.on(g.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.on(g.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(g.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(g.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this));}_unregisterListeners(){let{hls:e}=this;e&&(e.off(g.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(g.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(g.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(g.MANIFEST_LOADING,this.onManifestLoading,this),e.off(g.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.off(g.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(g.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(g.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this));}onMediaAttaching(e,t){var i;this.media=t.media,((i=t.overrides)==null?void 0:i.cueRemoval)===false&&(this.removeCues=false);}onMediaAttached(){var e;let t=(e=this.hls)==null?void 0:e.latestLevelDetails;t&&this.updateDateRangeCues(t);}onMediaDetaching(e,t){this.media=null,!t.transferMedia&&(this.id3Track&&(this.removeCues&&er(this.id3Track,this.onEventCueEnter),this.id3Track=null),this.dateRangeCuesAppended={});}onManifestLoading(){this.dateRangeCuesAppended={};}createTrack(e){let t=this.getID3Track(e.textTracks);return t.mode="hidden",t}getID3Track(e){if(this.media){for(let t=0;t<e.length;t++){let i=e[t];if(i.kind==="metadata"&&i.label==="id3")return Mp(i,this.media),i}return this.media.addTextTrack("metadata","id3")}}onFragParsingMetadata(e,t){if(!this.media||!this.hls)return;let{enableEmsgMetadataCues:i,enableID3MetadataCues:r}=this.hls.config;if(!i&&!r)return;let{samples:n}=t;this.id3Track||(this.id3Track=this.createTrack(this.media));let a=Iu();if(a)for(let o=0;o<n.length;o++){let l=n[o].type;if(l===At.emsg&&!i||!r)continue;let d=dp(n[o].data),c=n[o].pts,u=c+n[o].duration;u>Mo&&(u=Mo),u-c<=0&&(u=c+VA);for(let f=0;f<d.length;f++){let m=d[f];if(!cp(m)){this.updateId3CueEnds(c,l);let p=cc(a,c,u,m,l);p&&this.id3Track.addCue(p);}}}}updateId3CueEnds(e,t){var i;let r=(i=this.id3Track)==null?void 0:i.cues;if(r)for(let n=r.length;n--;){let a=r[n];a.type===t&&a.startTime<e&&a.endTime===Mo&&(a.endTime=e);}}onBufferFlushing(e,{startOffset:t,endOffset:i,type:r}){let{id3Track:n,hls:a}=this;if(!a)return;let{config:{enableEmsgMetadataCues:o,enableID3MetadataCues:l}}=a;if(n&&(o||l)){let d;r==="audio"?d=c=>c.type===At.audioId3&&l:r==="video"?d=c=>c.type===At.emsg&&o:d=c=>c.type===At.audioId3&&l||c.type===At.emsg&&o,nu(n,t,i,d);}}onLevelUpdated(e,{details:t}){this.updateDateRangeCues(t,true);}onLevelPtsUpdated(e,t){Math.abs(t.drift)>.01&&this.updateDateRangeCues(t.details);}updateDateRangeCues(e,t){if(!this.hls||!this.media)return;let{assetPlayerId:i,timelineOffset:r,enableDateRangeMetadataCues:n,interstitialsController:a}=this.hls.config;if(!n)return;let o=Iu();if(i&&r&&!a){let{fragmentStart:p,fragmentEnd:E}=e,v=this.assetCue;v?(v.startTime=p,v.endTime=E):o&&(v=this.assetCue=cc(o,p,E,{assetPlayerId:this.hls.config.assetPlayerId},"hlsjs.interstitial.asset"),v&&(v.id=i,this.id3Track||(this.id3Track=this.createTrack(this.media)),this.id3Track.addCue(v),v.addEventListener("enter",this.onEventCueEnter)));}if(!e.hasProgramDateTime)return;let{id3Track:l}=this,{dateRanges:d}=e,c=Object.keys(d),u=this.dateRangeCuesAppended;if(l&&t){var h;if((h=l.cues)!=null&&h.length){let p=Object.keys(u).filter(E=>!c.includes(E));for(let E=p.length;E--;){var f;let v=p[E],T=(f=u[v])==null?void 0:f.cues;delete u[v],T&&Object.keys(T).forEach(S=>{let A=T[S];if(A){A.removeEventListener("enter",this.onEventCueEnter);try{l.removeCue(A);}catch{}}});}}else u=this.dateRangeCuesAppended={};}let m=e.fragments[e.fragments.length-1];if(!(c.length===0||!G(m?.programDateTime))){this.id3Track||(this.id3Track=this.createTrack(this.media));for(let p=0;p<c.length;p++){let E=c[p],v=d[E],T=v.startTime,S=u[E],A=S?.cues||{},b=S?.durationKnown||false,D=Mo,{duration:I,endDate:k}=v;if(k&&I!==null)D=T+I,b=true;else if(v.endOnNext&&!b){let L=c.reduce((M,B)=>{if(B!==v.id){let H=d[B];if(H.class===v.class&&H.startDate>v.startDate&&(!M||v.startDate<M.startDate))return H}return M},null);L&&(D=L.startTime,b=true);}let R=Object.keys(v.attr);for(let L=0;L<R.length;L++){let M=R[L];if(!zT(M))continue;let B=A[M];if(B)b&&!(S!=null&&S.durationKnown)?B.endTime=D:Math.abs(B.startTime-T)>.01&&(B.startTime=T,B.endTime=D);else if(o){let H=v.attr[M];QT(M)&&(H=_g(H));let K=cc(o,T,D,{key:M,data:H},At.dateRange);K&&(K.id=E,this.id3Track.addCue(K),A[M]=K,a&&(M==="X-ASSET-LIST"||M==="X-ASSET-URL")&&K.addEventListener("enter",this.onEventCueEnter));}}u[E]={cues:A,dateRange:v,durationKnown:b};}}}},xu=class{constructor(e){this.hls=void 0,this.config=void 0,this.media=null,this.currentTime=0,this.stallCount=0,this._latency=null,this._targetLatencyUpdated=false,this.onTimeupdate=()=>{let{media:t}=this,i=this.levelDetails;if(!t||!i)return;this.currentTime=t.currentTime;let r=this.computeLatency();if(r===null)return;this._latency=r;let{lowLatencyMode:n,maxLiveSyncPlaybackRate:a}=this.config;if(!n||a===1||!i.live)return;let o=this.targetLatency;if(o===null)return;let l=r-o,d=Math.min(this.maxLatency,o+i.targetduration);if(l<d&&l>.05&&this.forwardBufferLength>1){let u=Math.min(2,Math.max(1,a)),h=Math.round(2/(1+Math.exp(-0.75*l-this.edgeStalled))*20)/20,f=Math.min(u,Math.max(1,h));this.changeMediaPlaybackRate(t,f);}else t.playbackRate!==1&&t.playbackRate!==0&&this.changeMediaPlaybackRate(t,1);},this.hls=e,this.config=e.config,this.registerListeners();}get levelDetails(){var e;return ((e=this.hls)==null?void 0:e.latestLevelDetails)||null}get latency(){return this._latency||0}get maxLatency(){let{config:e}=this;if(e.liveMaxLatencyDuration!==void 0)return e.liveMaxLatencyDuration;let t=this.levelDetails;return t?e.liveMaxLatencyDurationCount*t.targetduration:0}get targetLatency(){let e=this.levelDetails;if(e===null||this.hls===null)return null;let{holdBack:t,partHoldBack:i,targetduration:r}=e,{liveSyncDuration:n,liveSyncDurationCount:a,lowLatencyMode:o}=this.config,l=this.hls.userConfig,d=o&&i||t;(this._targetLatencyUpdated||l.liveSyncDuration||l.liveSyncDurationCount||d===0)&&(d=n!==void 0?n:a*r);let c=r;return d+Math.min(this.stallCount*this.config.liveSyncOnStallIncrease,c)}set targetLatency(e){this.stallCount=0,this.config.liveSyncDuration=e,this._targetLatencyUpdated=true;}get liveSyncPosition(){let e=this.estimateLiveEdge(),t=this.targetLatency;if(e===null||t===null)return null;let i=this.levelDetails;if(i===null)return null;let r=i.edge,n=e-t-this.edgeStalled,a=r-i.totalduration,o=r-(this.config.lowLatencyMode&&i.partTarget||i.targetduration);return Math.min(Math.max(a,n),o)}get drift(){let e=this.levelDetails;return e===null?1:e.drift}get edgeStalled(){let e=this.levelDetails;if(e===null)return 0;let t=(this.config.lowLatencyMode&&e.partTarget||e.targetduration)*3;return Math.max(e.age-t,0)}get forwardBufferLength(){let{media:e}=this,t=this.levelDetails;if(!e||!t)return 0;let i=e.buffered.length;return (i?e.buffered.end(i-1):t.edge)-this.currentTime}destroy(){this.unregisterListeners(),this.onMediaDetaching(),this.hls=null;}registerListeners(){let{hls:e}=this;e&&(e.on(g.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(g.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(g.MANIFEST_LOADING,this.onManifestLoading,this),e.on(g.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(g.ERROR,this.onError,this));}unregisterListeners(){let{hls:e}=this;e&&(e.off(g.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(g.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(g.MANIFEST_LOADING,this.onManifestLoading,this),e.off(g.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(g.ERROR,this.onError,this));}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener("timeupdate",this.onTimeupdate);}onMediaDetaching(){this.media&&(this.media.removeEventListener("timeupdate",this.onTimeupdate),this.media=null);}onManifestLoading(){this._latency=null,this.stallCount=0;}onLevelUpdated(e,{details:t}){t.advanced&&this.onTimeupdate(),!t.live&&this.media&&this.media.removeEventListener("timeupdate",this.onTimeupdate);}onError(e,t){var i;t.details===x.BUFFER_STALLED_ERROR&&(this.stallCount++,this.hls&&(i=this.levelDetails)!=null&&i.live&&this.hls.logger.warn("[latency-controller]: Stall detected, adjusting target latency"));}changeMediaPlaybackRate(e,t){var i,r;e.playbackRate!==t&&((i=this.hls)==null||i.logger.debug(`[latency-controller]: latency=${this.latency.toFixed(3)}, targetLatency=${(r=this.targetLatency)==null?void 0:r.toFixed(3)}, forwardBufferLength=${this.forwardBufferLength.toFixed(3)}: adjusting playback rate from ${e.playbackRate} to ${t}`),e.playbackRate=t);}estimateLiveEdge(){let e=this.levelDetails;return e===null?null:e.edge+e.age}computeLatency(){let e=this.estimateLiveEdge();return e===null?null:e-this.currentTime}},Ru=class extends In{constructor(e,t){super(e,"level-controller"),this._levels=[],this._firstLevel=-1,this._maxAutoLevel=-1,this._startLevel=void 0,this.currentLevel=null,this.currentLevelIndex=-1,this.manualLevelIndex=-1,this.steering=void 0,this.onParsedComplete=void 0,this.steering=t,this._registerListeners();}_registerListeners(){let{hls:e}=this;e.on(g.MANIFEST_LOADING,this.onManifestLoading,this),e.on(g.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(g.LEVEL_LOADED,this.onLevelLoaded,this),e.on(g.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(g.FRAG_BUFFERED,this.onFragBuffered,this),e.on(g.ERROR,this.onError,this);}_unregisterListeners(){let{hls:e}=this;e.off(g.MANIFEST_LOADING,this.onManifestLoading,this),e.off(g.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(g.LEVEL_LOADED,this.onLevelLoaded,this),e.off(g.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(g.FRAG_BUFFERED,this.onFragBuffered,this),e.off(g.ERROR,this.onError,this);}destroy(){this._unregisterListeners(),this.steering=null,this.resetLevels(),super.destroy();}stopLoad(){this._levels.forEach(t=>{t.loadError=0,t.fragmentError=0;}),super.stopLoad();}resetLevels(){this._startLevel=void 0,this.manualLevelIndex=-1,this.currentLevelIndex=-1,this.currentLevel=null,this._levels=[],this._maxAutoLevel=-1;}onManifestLoading(e,t){this.resetLevels();}onManifestLoaded(e,t){let i=this.hls.config.preferManagedMediaSource,r=[],n={},a={},o=false,l=false,d=false;t.levels.forEach(c=>{let u=c.attrs,{audioCodec:h,videoCodec:f}=c;h&&(c.audioCodec=h=Ho(h,i)||void 0),f&&(f=c.videoCodec=TT(f));let{width:m,height:p,unknownCodecs:E}=c,v=E?.length||0;if(o||(o=!!(m&&p)),l||(l=!!f),d||(d=!!h),v||h&&!this.isAudioSupported(h)||f&&!this.isVideoSupported(f)){this.log(`Some or all CODECS not supported "${u.CODECS}"`);return}let{CODECS:T,"FRAME-RATE":S,"HDCP-LEVEL":A,"PATHWAY-ID":b,RESOLUTION:D,"VIDEO-RANGE":I}=u,R=`${`${b||"."}-`}${c.bitrate}-${D}-${S}-${T}-${I}-${A}`;if(n[R])if(n[R].uri!==c.url&&!c.attrs["PATHWAY-ID"]){let L=a[R]+=1;c.attrs["PATHWAY-ID"]=new Array(L+1).join(".");let M=this.createLevel(c);n[R]=M,r.push(M);}else n[R].addGroupId("audio",u.AUDIO),n[R].addGroupId("text",u.SUBTITLES);else {let L=this.createLevel(c);n[R]=L,a[R]=1,r.push(L);}}),this.filterAndSortMediaOptions(r,t,o,l,d);}createLevel(e){let t=new ds(e),i=e.supplemental;if(i!=null&&i.videoCodec&&!this.isVideoSupported(i.videoCodec)){let r=new Error(`SUPPLEMENTAL-CODECS not supported "${i.videoCodec}"`);this.log(r.message),t.supportedResult=Og(r,[]);}return t}isAudioSupported(e){return gn(e,"audio",this.hls.config.preferManagedMediaSource)}isVideoSupported(e){return gn(e,"video",this.hls.config.preferManagedMediaSource)}filterAndSortMediaOptions(e,t,i,r,n){var a;let o=[],l=[],d=e,c=((a=t.stats)==null?void 0:a.parsing)||{};if((i||r)&&n&&(d=d.filter(({videoCodec:T,videoRange:S,width:A,height:b})=>(!!T||!!(A&&b))&&kT(S))),d.length===0){Promise.resolve().then(()=>{if(this.hls){let T="no level with compatible codecs found in manifest",S=T;t.levels.length&&(S=`one or more CODECS in variant not supported: ${Ae(t.levels.map(b=>b.attrs.CODECS).filter((b,D,I)=>I.indexOf(b)===D))}`,this.warn(S),T+=` (${S})`);let A=new Error(T);this.hls.trigger(g.ERROR,{type:z.MEDIA_ERROR,details:x.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:true,url:t.url,error:A,reason:S});}}),c.end=performance.now();return}t.audioTracks&&(o=t.audioTracks.filter(T=>!T.audioCodec||this.isAudioSupported(T.audioCodec)),Sg(o)),t.subtitles&&(l=t.subtitles,Sg(l));let u=d.slice(0);d.sort((T,S)=>{if(T.attrs["HDCP-LEVEL"]!==S.attrs["HDCP-LEVEL"])return (T.attrs["HDCP-LEVEL"]||"")>(S.attrs["HDCP-LEVEL"]||"")?1:-1;if(i&&T.height!==S.height)return T.height-S.height;if(T.frameRate!==S.frameRate)return T.frameRate-S.frameRate;if(T.videoRange!==S.videoRange)return Ko.indexOf(T.videoRange)-Ko.indexOf(S.videoRange);if(T.videoCodec!==S.videoCodec){let A=Em(T.videoCodec),b=Em(S.videoCodec);if(A!==b)return b-A}if(T.uri===S.uri&&T.codecSet!==S.codecSet){let A=Go(T.codecSet),b=Go(S.codecSet);if(A!==b)return b-A}return T.averageBitrate!==S.averageBitrate?T.averageBitrate-S.averageBitrate:0});let h=u[0];if(this.steering&&(d=this.steering.filterParsedLevels(d),d.length!==u.length)){for(let T=0;T<u.length;T++)if(u[T].pathwayId===d[0].pathwayId){h=u[T];break}}this._levels=d;for(let T=0;T<d.length;T++)if(d[T]===h){var f;this._firstLevel=T;let S=h.bitrate,A=this.hls.bandwidthEstimate;if(this.log(`manifest loaded, ${d.length} level(s) found, first bitrate: ${S}`),((f=this.hls.userConfig)==null?void 0:f.abrEwmaDefaultEstimate)===void 0){let b=Math.min(S,this.hls.config.abrEwmaDefaultEstimateMax);b>A&&A===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=b);}break}let m=n&&!r,p=this.hls.config,E=!!(p.audioStreamController&&p.audioTrackController),v={levels:d,audioTracks:o,subtitleTracks:l,sessionData:t.sessionData,sessionKeys:t.sessionKeys,firstLevel:this._firstLevel,stats:t.stats,audio:n,video:r,altAudio:E&&!m&&o.some(T=>!!T.url)};c.end=performance.now(),this.hls.trigger(g.MANIFEST_PARSED,v);}get levels(){return this._levels.length===0?null:this._levels}get loadLevelObj(){return this.currentLevel}get level(){return this.currentLevelIndex}set level(e){let t=this._levels;if(t.length===0)return;if(e<0||e>=t.length){let c=new Error("invalid level idx"),u=e<0;if(this.hls.trigger(g.ERROR,{type:z.OTHER_ERROR,details:x.LEVEL_SWITCH_ERROR,level:e,fatal:u,error:c,reason:c.message}),u)return;e=Math.min(e,t.length-1);}let 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&&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:""}`);let l={level:e,attrs:a.attrs,details:a.details,bitrate:a.bitrate,averageBitrate:a.averageBitrate,maxBitrate:a.maxBitrate,realBitrate:a.realBitrate,width:a.width,height:a.height,codecSet:a.codecSet,audioCodec:a.audioCodec,videoCodec:a.videoCodec,audioGroups:a.audioGroups,subtitleGroups:a.subtitleGroups,loaded:a.loaded,loadError:a.loadError,fragmentError:a.fragmentError,name:a.name,id:a.id,uri:a.uri,url:a.url,urlId:0,audioGroupIds:a.audioGroupIds,textGroupIds:a.textGroupIds};this.hls.trigger(g.LEVEL_SWITCHING,l);let d=a.details;if(!d||d.live){let c=this.switchParams(a.uri,r?.details,d);this.loadPlaylist(c);}}get manualLevel(){return this.manualLevelIndex}set manualLevel(e){this.manualLevelIndex=e,this._startLevel===void 0&&(this._startLevel=e),e!==-1&&(this.level=e);}get firstLevel(){return this._firstLevel}set firstLevel(e){this._firstLevel=e;}get startLevel(){if(this._startLevel===void 0){let e=this.hls.config.startLevel;return e!==void 0?e:this.hls.firstAutoLevel}return this._startLevel}set startLevel(e){this._startLevel=e;}get pathways(){return this.steering?this.steering.pathways():[]}get pathwayPriority(){return this.steering?this.steering.pathwayPriority:null}set pathwayPriority(e){if(this.steering){let t=this.steering.pathways(),i=e.filter(r=>t.indexOf(r)!==-1);if(e.length<1){this.warn(`pathwayPriority ${e} should contain at least one pathway from list: ${t}`);return}this.steering.pathwayPriority=i;}}onError(e,t){t.fatal||!t.context||t.context.type===ce.LEVEL&&t.context.level===this.level&&this.checkRetry(t);}onFragBuffered(e,{frag:t}){if(t!==void 0&&t.type===W.MAIN){let i=t.elementaryStreams;if(!Object.keys(i).some(n=>!!i[n]))return;let r=this._levels[t.level];r!=null&&r.loadError&&(this.log(`Resetting level error count of ${r.loadError} on frag buffered`),r.loadError=0);}}onLevelLoaded(e,t){var i;let{level:r,details:n}=t,a=t.levelInfo;if(!a){var o;this.warn(`Invalid level index ${r}`),(o=t.deliveryDirectives)!=null&&o.skip&&(n.deltaUpdateFailed=true);return}if(a===this.currentLevel||t.withoutMultiVariant){a.fragmentError===0&&(a.loadError=0);let l=a.details;l===t.details&&l.advanced&&(l=void 0),this.playlistLoaded(r,t,l);}else (i=t.deliveryDirectives)!=null&&i.skip&&(n.deltaUpdateFailed=true);}loadPlaylist(e){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentLevel)&&this.scheduleLoading(this.currentLevel,e);}loadingPlaylist(e,t){super.loadingPlaylist(e,t);let i=this.getUrlWithDirectives(e.uri,t),r=this.currentLevelIndex,n=e.attrs["PATHWAY-ID"],a=e.details,o=a?.age;this.log(`Loading level index ${r}${t?.msn!==void 0?" at sn "+t.msn+" part "+t.part:""}${n?" Pathway "+n:""}${o&&a.live?" age "+o.toFixed(1)+(a.type&&" "+a.type||""):""} ${i}`),this.hls.trigger(g.LEVEL_LOADING,{url:i,level:r,levelInfo:e,pathwayId:e.attrs["PATHWAY-ID"],id:0,deliveryDirectives:t||null});}get nextLoadLevel(){return this.manualLevelIndex!==-1?this.manualLevelIndex:this.hls.nextAutoLevel}set nextLoadLevel(e){this.level=e,this.manualLevelIndex===-1&&(this.hls.nextAutoLevel=e);}removeLevel(e){var t;if(this._levels.length===1)return;let i=this._levels.filter((n,a)=>a!==e?true:(this.steering&&this.steering.removeLevel(n),n===this.currentLevel&&(this.currentLevel=null,this.currentLevelIndex=-1,n.details&&n.details.fragments.forEach(o=>o.level=-1)),false));ep(i),this._levels=i,this.currentLevelIndex>-1&&(t=this.currentLevel)!=null&&t.details&&(this.currentLevelIndex=this.currentLevel.details.fragments[0].level),this.manualLevelIndex>-1&&(this.manualLevelIndex=this.currentLevelIndex);let r=i.length-1;this._firstLevel=Math.min(this._firstLevel,r),this._startLevel&&(this._startLevel=Math.min(this._startLevel,r)),this.hls.trigger(g.LEVELS_UPDATED,{levels:i});}onLevelsUpdated(e,{levels:t}){this._levels=t;}checkMaxAutoUpdated(){let{autoLevelCapping:e,maxAutoLevel:t,maxHdcpLevel:i}=this.hls;this._maxAutoLevel!==t&&(this._maxAutoLevel=t,this.hls.trigger(g.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:e,levels:this.levels,maxAutoLevel:t,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:i}));}};function Sg(s){let e={};s.forEach(t=>{let i=t.groupId||"";t.id=e[i]=e[i]||0,e[i]++;});}function Kp(){return self.SourceBuffer||self.WebKitSourceBuffer}function Vp(){if(!Fi())return false;let e=Kp();return !e||e.prototype&&typeof e.prototype.appendBuffer=="function"&&typeof e.prototype.remove=="function"}function WA(){if(!Vp())return false;let s=Fi();return typeof s?.isTypeSupported=="function"&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some(e=>s.isTypeSupported(pn(e,"video")))||["mp4a.40.2","fLaC"].some(e=>s.isTypeSupported(pn(e,"audio"))))}function YA(){var s;let e=Kp();return typeof(e==null||(s=e.prototype)==null?void 0:s.changeType)=="function"}var qA=100,ku=class extends yn{constructor(e,t,i){super(e,t,i,"stream-controller",W.MAIN),this.audioCodecSwap=false,this.level=-1,this._forceStartLoad=false,this._hasEnoughToStart=false,this.altAudio=0,this.audioOnly=false,this.fragPlaying=null,this.fragLastKbps=0,this.couldBacktrack=false,this.backtrackFragment=null,this.audioCodecSwitch=false,this.videoBuffer=null,this.onMediaPlaying=()=>{this.tick();},this.onMediaSeeked=()=>{let r=this.media,n=r?r.currentTime:null;if(n===null||!G(n)||(this.log(`Media seeked to ${n.toFixed(3)}`),!this.getBufferedFrag(n)))return;let a=this.getFwdBufferInfoAtPos(r,n,W.MAIN,0);if(a===null||a.len===0){this.warn(`Main forward buffer length at ${n} on "seeked" event ${a?a.len:"empty"})`);return}this.tick();},this.registerListeners();}registerListeners(){super.registerListeners();let{hls:e}=this;e.on(g.MANIFEST_PARSED,this.onManifestParsed,this),e.on(g.LEVEL_LOADING,this.onLevelLoading,this),e.on(g.LEVEL_LOADED,this.onLevelLoaded,this),e.on(g.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.on(g.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(g.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.on(g.BUFFER_CREATED,this.onBufferCreated,this),e.on(g.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(g.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(g.FRAG_BUFFERED,this.onFragBuffered,this);}unregisterListeners(){super.unregisterListeners();let{hls:e}=this;e.off(g.MANIFEST_PARSED,this.onManifestParsed,this),e.off(g.LEVEL_LOADED,this.onLevelLoaded,this),e.off(g.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.off(g.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(g.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.off(g.BUFFER_CREATED,this.onBufferCreated,this),e.off(g.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(g.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(g.FRAG_BUFFERED,this.onFragBuffered,this);}onHandlerDestroying(){this.onMediaPlaying=this.onMediaSeeked=null,this.unregisterListeners(),super.onHandlerDestroying();}startLoad(e,t){if(this.levels){let{lastCurrentTime:i,hls:r}=this;if(this.stopLoad(),this.setInterval(qA),this.level=-1,!this.startFragRequested){let n=r.startLevel;n===-1&&(r.config.testBandwidth&&this.levels.length>1?(n=0,this.bitrateTest=true):n=r.firstAutoLevel),r.nextLoadLevel=n,this.level=r.loadLevel,this._hasEnoughToStart=!!t;}i>0&&e===-1&&!t&&(this.log(`Override startPosition with lastCurrentTime @${i.toFixed(3)}`),e=i),this.state=C.IDLE,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick();}else this._forceStartLoad=true,this.state=C.STOPPED;}stopLoad(){this._forceStartLoad=false,super.stopLoad();}doTick(){switch(this.state){case C.WAITING_LEVEL:{let{levels:e,level:t}=this,i=e?.[t],r=i?.details;if(r&&(!r.live||this.levelLastLoaded===i&&!this.waitForLive(i))){if(this.waitForCdnTuneIn(r))break;this.state=C.IDLE;break}else if(this.hls.nextLoadLevel!==this.level){this.state=C.IDLE;break}break}case C.FRAG_LOADING_WAITING_RETRY:this.checkRetryDate();break}this.state===C.IDLE&&this.doTickIdle(),this.onTickEnd();}onTickEnd(){var e;super.onTickEnd(),(e=this.media)!=null&&e.readyState&&this.media.seeking===false&&(this.lastCurrentTime=this.media.currentTime),this.checkFragmentChanged();}doTickIdle(){let{hls:e,levelLastLoaded:t,levels:i,media:r}=this;if(t===null||!r&&!this.primaryPrefetch&&(this.startFragRequested||!e.config.startFragPrefetch)||this.altAudio&&this.audioOnly)return;let n=this.buffering?e.nextLoadLevel:e.loadLevel;if(!(i!=null&&i[n]))return;let a=i[n],o=this.getMainFwdBufferInfo();if(o===null)return;let l=this.getLevelDetails();if(l&&this._streamEnded(o,l)){let p={};this.altAudio===2&&(p.type="video"),this.hls.trigger(g.BUFFER_EOS,p),this.state=C.ENDED;return}if(!this.buffering)return;e.loadLevel!==n&&e.manualLevel===-1&&this.log(`Adapting to level ${n} from level ${this.level}`),this.level=e.nextLoadLevel=n;let d=a.details;if(!d||this.state===C.WAITING_LEVEL||this.waitForLive(a)){this.level=n,this.state=C.WAITING_LEVEL,this.startFragRequested=false;return}let c=o.len,u=this.getMaxBufferLength(a.maxBitrate);if(c>=u)return;this.backtrackFragment&&this.backtrackFragment.start>o.end&&(this.backtrackFragment=null);let h=this.backtrackFragment?this.backtrackFragment.start:o.end,f=this.getNextFragment(h,d);if(this.couldBacktrack&&!this.fragPrevious&&f&&Ue(f)&&this.fragmentTracker.getState(f)!==Ke.OK){var m;let E=((m=this.backtrackFragment)!=null?m:f).sn-d.startSN,v=d.fragments[E-1];v&&f.cc===v.cc&&(f=v,this.fragmentTracker.removeFragment(v));}else this.backtrackFragment&&o.len&&(this.backtrackFragment=null);if(f&&this.isLoopLoading(f,h)){if(!f.gap){let E=this.audioOnly&&!this.altAudio?Se.AUDIO:Se.VIDEO,v=(E===Se.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;v&&this.afterBufferFlushed(v,E,W.MAIN);}f=this.getNextFragmentLoopLoading(f,d,o,W.MAIN,u);}f&&(f.initSegment&&!f.initSegment.data&&!this.bitrateTest&&(f=f.initSegment),this.loadFragment(f,a,h));}loadFragment(e,t,i){let r=this.fragmentTracker.getState(e);r===Ke.NOT_LOADED||r===Ke.PARTIAL?Ue(e)?this.bitrateTest?(this.log(`Fragment ${e.sn} of level ${e.level} is being downloaded to test bitrate and will not be buffered`),this._loadBitrateTestFrag(e,t)):super.loadFragment(e,t,i):this._loadInitSegment(e,t):this.clearTrackerIfNeeded(e);}getBufferedFrag(e){return this.fragmentTracker.getBufferedFrag(e,W.MAIN)}followingBufferedFrag(e){return e?this.getBufferedFrag(e.end+.5):null}immediateLevelSwitch(){this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY);}nextLevelSwitch(){let{levels:e,media:t}=this;if(t!=null&&t.readyState){let i,r=this.getAppendedFrag(t.currentTime);r&&r.start>1&&this.flushMainBuffer(0,r.start-1);let n=this.getLevelDetails();if(n!=null&&n.live){let o=this.getMainFwdBufferInfo();if(!o||o.len<n.targetduration*2)return}if(!t.paused&&e){let o=this.hls.nextLoadLevel,l=e[o],d=this.fragLastKbps;d&&this.fragCurrent?i=this.fragCurrent.duration*l.maxBitrate/(1e3*d)+1:i=0;}else i=0;let a=this.getBufferedFrag(t.currentTime+i);if(a){let o=this.followingBufferedFrag(a);if(o){this.abortCurrentFrag();let l=o.maxStartPTS?o.maxStartPTS:o.start,d=o.duration,c=Math.max(a.end,l+Math.min(Math.max(d-this.config.maxFragLookUpTolerance,d*(this.couldBacktrack?.5:.125)),d*(this.couldBacktrack?.75:.25)));this.flushMainBuffer(c,Number.POSITIVE_INFINITY);}}}}abortCurrentFrag(){let e=this.fragCurrent;switch(this.fragCurrent=null,this.backtrackFragment=null,e&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.state){case C.KEY_LOADING:case C.FRAG_LOADING:case C.FRAG_LOADING_WAITING_RETRY:case C.PARSING:case C.PARSED:this.state=C.IDLE;break}this.nextLoadPosition=this.getLoadPosition();}flushMainBuffer(e,t){super.flushMainBuffer(e,t,this.altAudio===2?"video":null);}onMediaAttached(e,t){super.onMediaAttached(e,t);let i=t.media;nt(i,"playing",this.onMediaPlaying),nt(i,"seeked",this.onMediaSeeked);}onMediaDetaching(e,t){let{media:i}=this;i&&(ut(i,"playing",this.onMediaPlaying),ut(i,"seeked",this.onMediaSeeked)),this.videoBuffer=null,this.fragPlaying=null,super.onMediaDetaching(e,t),!t.transferMedia&&(this._hasEnoughToStart=false);}onManifestLoading(){super.onManifestLoading(),this.log("Trigger BUFFER_RESET"),this.hls.trigger(g.BUFFER_RESET,void 0),this.couldBacktrack=false,this.fragLastKbps=0,this.fragPlaying=this.backtrackFragment=null,this.altAudio=0,this.audioOnly=false;}onManifestParsed(e,t){let i=false,r=false;for(let n=0;n<t.levels.length;n++){let a=t.levels[n].audioCodec;a&&(i=i||a.indexOf("mp4a.40.2")!==-1,r=r||a.indexOf("mp4a.40.5")!==-1);}this.audioCodecSwitch=i&&r&&!YA(),this.audioCodecSwitch&&this.log("Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC"),this.levels=t.levels,this.startFragRequested=false;}onLevelLoading(e,t){let{levels:i}=this;if(!i||this.state!==C.IDLE)return;let r=t.levelInfo;(!r.details||r.details.live&&(this.levelLastLoaded!==r||r.details.expired)||this.waitForCdnTuneIn(r.details))&&(this.state=C.WAITING_LEVEL);}onLevelLoaded(e,t){var i;let{levels:r,startFragRequested:n}=this,a=t.level,o=t.details,l=o.totalduration;if(!r){this.warn(`Levels were reset while loading level ${a}`);return}this.log(`Level ${a} loaded [${o.startSN},${o.endSN}]${o.lastPartSn?`[part-${o.lastPartSn}-${o.lastPartIndex}]`:""}, cc [${o.startCC}, ${o.endCC}] duration:${l}`);let d=t.levelInfo,c=this.fragCurrent;c&&(this.state===C.FRAG_LOADING||this.state===C.FRAG_LOADING_WAITING_RETRY)&&c.level!==t.level&&c.loader&&this.abortCurrentFrag();let u=0;if(o.live||(i=d.details)!=null&&i.live){var h;if(this.checkLiveUpdate(o),o.deltaUpdateFailed)return;u=this.alignPlaylists(o,d.details,(h=this.levelLastLoaded)==null?void 0:h.details);}if(d.details=o,this.levelLastLoaded=d,n||this.setStartPosition(o,u),this.hls.trigger(g.LEVEL_UPDATED,{details:o,level:a}),this.state===C.WAITING_LEVEL){if(this.waitForCdnTuneIn(o))return;this.state=C.IDLE;}n&&o.live&&this.synchronizeToLiveEdge(o),this.tick();}synchronizeToLiveEdge(e){let{config:t,media:i}=this;if(!i)return;let r=this.hls.liveSyncPosition,n=this.getLoadPosition(),a=e.fragmentStart,o=e.edge,l=n>=a-t.maxFragLookUpTolerance&&n<=o;if(r!==null&&i.duration>r&&(n<r||!l)){let c=t.liveMaxLatencyDuration!==void 0?t.liveMaxLatencyDuration:t.liveMaxLatencyDurationCount*e.targetduration;if((!l&&i.readyState<4||n<o-c)&&(this._hasEnoughToStart||(this.nextLoadPosition=r),i.readyState))if(this.warn(`Playback: ${n.toFixed(3)} is located too far from the end of live sliding playlist: ${o}, reset currentTime to : ${r.toFixed(3)}`),this.config.liveSyncMode==="buffered"){var d;let u=re.bufferInfo(i,r,0);if(!((d=u.buffered)!=null&&d.length)){i.currentTime=r;return}if(u.start<=n){i.currentTime=r;return}let{nextStart:f}=re.bufferedInfo(u.buffered,n,0);f&&(i.currentTime=f);}else i.currentTime=r;}}_handleFragmentLoadProgress(e){var t;let i=e.frag,{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}let o=a[i.level];if(!o){this.warn(`Level ${i.level} not found on progress`);return}let l=o.details;if(!l){this.warn(`Dropping fragment ${i.sn} of level ${i.level} after level details were reset`),this.fragmentTracker.removeFragment(i);return}let d=o.videoCodec,c=l.PTSKnown||!l.live,u=(t=i.initSegment)==null?void 0:t.data,h=this._getAudioCodec(o),f=this.transmuxer=this.transmuxer||new sl(this.hls,W.MAIN,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),m=r?r.index:-1,p=m!==-1,E=new vn(i.level,i.sn,i.stats.chunkCount,n.byteLength,m,p),v=this.initPTS[i.cc];f.push(n,u,h,d,i,r,l.totalduration,c,E,v);}onAudioTrackSwitching(e,t){let i=this.hls,r=this.altAudio===2;if(Wo(t.url,i))this.altAudio=1;else {if(this.mediaBuffer!==this.media){this.log("Switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;let a=this.fragCurrent;a&&(this.log("Switching to main audio track, cancel main fragment load"),a.abortRequests(),this.fragmentTracker.removeFragment(a)),this.resetTransmuxer(),this.resetLoadingState();}else this.audioOnly&&this.resetTransmuxer();if(r){this.fragmentTracker.removeAllFragments(),i.once(g.BUFFER_FLUSHED,()=>{this.hls&&this.hls.trigger(g.AUDIO_TRACK_SWITCHED,t);}),i.trigger(g.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null});return}i.trigger(g.AUDIO_TRACK_SWITCHED,t);}}onAudioTrackSwitched(e,t){let i=Wo(t.url,this.hls);if(i){let r=this.videoBuffer;r&&this.mediaBuffer!==r&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=r);}this.altAudio=i?2:0,this.tick();}onBufferCreated(e,t){let i=t.tracks,r,n,a=false;for(let o in i){let l=i[o];if(l.id==="main"){if(n=o,r=l,o==="video"){let d=i[o];d&&(this.videoBuffer=d.buffer);}}else a=true;}a&&r?(this.log(`Alternate track found, use ${n}.buffered to schedule main fragment loading`),this.mediaBuffer=r.buffer):this.mediaBuffer=this.media;}onFragBuffered(e,t){let{frag:i,part:r}=t,n=i.type===W.MAIN;if(n){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===C.PARSED&&(this.state=C.IDLE);return}let o=r?r.stats:i.stats;this.fragLastKbps=Math.round(8*o.total/(o.buffering.end-o.loading.first)),Ue(i)&&(this.fragPrevious=i),this.fragBufferedComplete(i,r);}let a=this.media;a&&(!this._hasEnoughToStart&&re.getBuffered(a).length&&(this._hasEnoughToStart=true,this.seekToStartPos()),n&&this.tick());}get hasEnoughToStart(){return this._hasEnoughToStart}onError(e,t){var i;if(t.fatal){this.state=C.ERROR;return}switch(t.details){case x.FRAG_GAP:case x.FRAG_PARSING_ERROR:case x.FRAG_DECRYPT_ERROR:case x.FRAG_LOAD_ERROR:case x.FRAG_LOAD_TIMEOUT:case x.KEY_LOAD_ERROR:case x.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(W.MAIN,t);break;case x.LEVEL_LOAD_ERROR:case x.LEVEL_LOAD_TIMEOUT:case x.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===C.WAITING_LEVEL&&((i=t.context)==null?void 0:i.type)===ce.LEVEL&&(this.state=C.IDLE);break;case x.BUFFER_ADD_CODEC_ERROR:case x.BUFFER_APPEND_ERROR:if(t.parent!=="main")return;this.reduceLengthAndFlushBuffer(t)&&this.resetLoadingState();break;case x.BUFFER_FULL_ERROR:if(t.parent!=="main")return;this.reduceLengthAndFlushBuffer(t)&&(!this.config.interstitialsController&&this.config.assetPlayerId?this._hasEnoughToStart=true:this.flushMainBuffer(0,Number.POSITIVE_INFINITY));break;case x.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}onFragLoadEmergencyAborted(){this.state=C.IDLE,this._hasEnoughToStart||(this.startFragRequested=false,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate();}onBufferFlushed(e,{type:t}){if(t!==Se.AUDIO||!this.altAudio){let i=(t===Se.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;i&&(this.afterBufferFlushed(i,t,W.MAIN),this.tick());}}onLevelsUpdated(e,t){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level,this.level===-1&&this.resetWhenMissingContext(this.fragCurrent)),this.levels=t.levels;}swapAudioCodec(){this.audioCodecSwap=!this.audioCodecSwap;}seekToStartPos(){let{media:e}=this;if(!e)return;let t=e.currentTime,i=this.startPosition;if(i>=0&&t<i){if(e.seeking){this.log(`could not seek to ${i}, already seeking at ${t}`);return}let r=this.timelineOffset;r&&i&&(i+=r);let n=this.getLevelDetails(),a=re.getBuffered(e),o=a.length?a.start(0):0,l=o-i,d=Math.max(this.config.maxBufferHole,this.config.maxFragLookUpTolerance);(this.config.startOnSegmentBoundary||l>0&&(l<d||this.loadingParts&&l<2*(n?.partTarget||0)))&&(this.log(`adjusting start position by ${l} to match buffer start`),i+=l,this.startPosition=i),t<i&&(this.log(`seek to target start position ${i} from current time ${t} buffer start ${o}`),e.currentTime=i);}}_getAudioCodec(e){let t=this.config.defaultAudioCodec||e.audioCodec;return this.audioCodecSwap&&t&&(this.log("Swapping audio codec"),t.indexOf("mp4a.40.5")!==-1?t="mp4a.40.2":t="mp4a.40.5"),t}_loadBitrateTestFrag(e,t){e.bitrateTest=true,this._doFragLoad(e,t).then(i=>{let{hls:r}=this,n=i?.frag;if(!n||this.fragContextChanged(n))return;t.fragmentError=0,this.state=C.IDLE,this.startFragRequested=false,this.bitrateTest=false;let a=n.stats;a.parsing.start=a.parsing.end=a.buffering.start=a.buffering.end=self.performance.now(),r.trigger(g.FRAG_LOADED,i),n.bitrateTest=false;}).catch(i=>{this.state===C.STOPPED||this.state===C.ERROR||(this.warn(i),this.resetFragmentLoading(e));});}_handleTransmuxComplete(e){let t=this.playlistType,{hls:i}=this,{remuxResult:r,chunkMeta:n}=e,a=this.getCurrentContext(n);if(!a){this.resetWhenMissingContext(n);return}let{frag:o,part:l,level:d}=a,{video:c,text:u,id3:h,initSegment:f}=r,{details:m}=d,p=this.altAudio?void 0:r.audio;if(this.fragContextChanged(o)){this.fragmentTracker.removeFragment(o);return}if(this.state=C.PARSING,f){let E=f.tracks;if(E){let A=o.initSegment||o;if(this.unhandledEncryptionError(f,o))return;this._bufferInitSegment(d,E,A,n),i.trigger(g.FRAG_PARSING_INIT_SEGMENT,{frag:A,id:t,tracks:E});}let v=f.initPTS,T=f.timescale,S=this.initPTS[o.cc];if(G(v)&&(!S||S.baseTime!==v||S.timescale!==T)){let A=f.trackId;this.initPTS[o.cc]={baseTime:v,timescale:T,trackId:A},i.trigger(g.INIT_PTS_FOUND,{frag:o,id:t,initPTS:v,timescale:T,trackId:A});}}if(c&&m){p&&c.type==="audiovideo"&&this.logMuxedErr(o);let E=m.fragments[o.sn-1-m.startSN],v=o.sn===m.startSN,T=!E||o.cc>E.cc;if(r.independent!==false){let{startPTS:S,endPTS:A,startDTS:b,endDTS:D}=c;if(l)l.elementaryStreams[c.type]={startPTS:S,endPTS:A,startDTS:b,endDTS:D};else if(c.firstKeyFrame&&c.independent&&n.id===1&&!T&&(this.couldBacktrack=true),c.dropped&&c.independent){let I=this.getMainFwdBufferInfo(),k=(I?I.end:this.getLoadPosition())+this.config.maxBufferHole,R=c.firstKeyFramePTS?c.firstKeyFramePTS:S;if(!v&&k<R-this.config.maxBufferHole&&!T){this.backtrack(o);return}else T&&(o.gap=true);o.setElementaryStreamInfo(c.type,o.start,A,o.start,D,true);}else v&&S-(m.appliedTimelineOffset||0)>Bo&&(o.gap=true);o.setElementaryStreamInfo(c.type,S,A,b,D),this.backtrackFragment&&(this.backtrackFragment=o),this.bufferFragmentData(c,o,l,n,v||T);}else if(v||T)o.gap=true;else {this.backtrack(o);return}}if(p){let{startPTS:E,endPTS:v,startDTS:T,endDTS:S}=p;l&&(l.elementaryStreams[Se.AUDIO]={startPTS:E,endPTS:v,startDTS:T,endDTS:S}),o.setElementaryStreamInfo(Se.AUDIO,E,v,T,S),this.bufferFragmentData(p,o,l,n);}if(m&&h!=null&&h.samples.length){let E={id:t,frag:o,details:m,samples:h.samples};i.trigger(g.FRAG_PARSING_METADATA,E);}if(m&&u){let E={id:t,frag:o,details:m,samples:u.samples};i.trigger(g.FRAG_PARSING_USERDATA,E);}}logMuxedErr(e){this.warn(`${Ue(e)?"Media":"Init"} segment with muxed audiovideo where only video expected: ${e.url}`);}_bufferInitSegment(e,t,i,r){if(this.state!==C.PARSING)return;this.audioOnly=!!t.audio&&!t.video,this.altAudio&&!this.audioOnly&&(delete t.audio,t.audiovideo&&this.logMuxedErr(i));let{audio:n,video:a,audiovideo:o}=t;if(n){let d=e.audioCodec,c=Po(n.codec,d);c==="mp4a"&&(c="mp4a.40.5");let u=navigator.userAgent.toLowerCase();if(this.audioCodecSwitch){c&&(c.indexOf("mp4a.40.5")!==-1?c="mp4a.40.2":c="mp4a.40.5");let h=n.metadata;h&&"channelCount"in h&&(h.channelCount||1)!==1&&u.indexOf("firefox")===-1&&(c="mp4a.40.5");}c&&c.indexOf("mp4a.40.5")!==-1&&u.indexOf("android")!==-1&&n.container!=="audio/mpeg"&&(c="mp4a.40.2",this.log(`Android: force audio codec to ${c}`)),d&&d!==c&&this.log(`Swapping manifest audio codec "${d}" for "${c}"`),n.levelCodec=c,n.id=W.MAIN,this.log(`Init audio buffer, container:${n.container}, codecs[selected/level/parsed]=[${c||""}/${d||""}/${n.codec}]`),delete t.audiovideo;}if(a){a.levelCodec=e.videoCodec,a.id=W.MAIN;let d=a.codec;if(d?.length===4)switch(d){case "hvc1":case "hev1":a.codec="hvc1.1.6.L120.90";break;case "av01":a.codec="av01.0.04M.08";break;case "avc1":a.codec="avc1.42e01e";break}this.log(`Init video buffer, container:${a.container}, codecs[level/parsed]=[${e.videoCodec||""}/${d}]${a.codec!==d?" parsed-corrected="+a.codec:""}${a.supplemental?" supplemental="+a.supplemental:""}`),delete t.audiovideo;}o&&(this.log(`Init audiovideo buffer, container:${o.container}, codecs[level/parsed]=[${e.codecs}/${o.codec}]`),delete t.video,delete t.audio);let l=Object.keys(t);if(l.length){if(this.hls.trigger(g.BUFFER_CODECS,t),!this.hls)return;l.forEach(d=>{let u=t[d].initSegment;u!=null&&u.byteLength&&this.hls.trigger(g.BUFFER_APPENDING,{type:d,data:u,frag:i,part:null,chunkMeta:r,parent:i.type});});}this.tickImmediate();}getMainFwdBufferInfo(){let e=this.mediaBuffer&&this.altAudio===2?this.mediaBuffer:this.media;return this.getFwdBufferInfo(e,W.MAIN)}get maxBufferLength(){let{levels:e,level:t}=this,i=e?.[t];return i?this.getMaxBufferLength(i.maxBitrate):this.config.maxBufferLength}backtrack(e){this.couldBacktrack=true,this.backtrackFragment=e,this.resetTransmuxer(),this.flushBufferGap(e),this.fragmentTracker.removeFragment(e),this.fragPrevious=null,this.nextLoadPosition=e.start,this.state=C.IDLE;}checkFragmentChanged(){let e=this.media,t=null;if(e&&e.readyState>1&&e.seeking===false){let i=e.currentTime;if(re.isBuffered(e,i)?t=this.getAppendedFrag(i):re.isBuffered(e,i+.1)&&(t=this.getAppendedFrag(i+.1)),t){this.backtrackFragment=null;let r=this.fragPlaying,n=t.level;(!r||t.sn!==r.sn||r.level!==n)&&(this.fragPlaying=t,this.hls.trigger(g.FRAG_CHANGED,{frag:t}),(!r||r.level!==n)&&this.hls.trigger(g.LEVEL_SWITCHED,{level:n}));}}}get nextLevel(){let e=this.nextBufferedFrag;return e?e.level:-1}get currentFrag(){var e;if(this.fragPlaying)return this.fragPlaying;let t=((e=this.media)==null?void 0:e.currentTime)||this.lastCurrentTime;return G(t)?this.getAppendedFrag(t):null}get currentProgramDateTime(){var e;let t=((e=this.media)==null?void 0:e.currentTime)||this.lastCurrentTime;if(G(t)){let i=this.getLevelDetails(),r=this.currentFrag||(i?cs(null,i.fragments,t):null);if(r){let n=r.programDateTime;if(n!==null){let a=n+(t-r.start)*1e3;return new Date(a)}}}return null}get currentLevel(){let e=this.currentFrag;return e?e.level:-1}get nextBufferedFrag(){let e=this.currentFrag;return e?this.followingBufferedFrag(e):null}get forceStartLoad(){return this._forceStartLoad}},Du=class extends ht{constructor(e,t){super("key-loader",t),this.config=void 0,this.keyIdToKeyInfo={},this.emeController=null,this.config=e;}abort(e){for(let i in this.keyIdToKeyInfo){let r=this.keyIdToKeyInfo[i].loader;if(r){var t;if(e&&e!==((t=r.context)==null?void 0:t.frag.type))return;r.abort();}}}detach(){for(let e in this.keyIdToKeyInfo){let t=this.keyIdToKeyInfo[e];(t.mediaKeySessionContext||t.decryptdata.isCommonEncryption)&&delete this.keyIdToKeyInfo[e];}}destroy(){this.detach();for(let e in this.keyIdToKeyInfo){let t=this.keyIdToKeyInfo[e].loader;t&&t.destroy();}this.keyIdToKeyInfo={};}createKeyLoadError(e,t=x.KEY_LOAD_ERROR,i,r,n){return new Ht({type:z.NETWORK_ERROR,details:t,fatal:false,frag:e,response:n,error:i,networkDetails:r})}loadClear(e,t,i){if(this.emeController&&this.config.emeEnabled&&!this.emeController.getSelectedKeySystemFormats().length){if(t.length)for(let r=0,n=t.length;r<n;r++){let a=t[r];if(e.cc<=a.cc&&(!Ue(e)||!Ue(a)||e.sn<a.sn)||!i&&r==n-1)return this.emeController.selectKeySystemFormat(a).then(o=>{if(!this.emeController)return;a.setKeyFormat(o);let l=Oo(o);if(l)return this.emeController.getKeySystemAccess([l])})}if(this.config.requireKeySystemAccessOnStart){let r=dn(this.config);if(r.length)return this.emeController.getKeySystemAccess(r)}}return null}load(e){return !e.decryptdata&&e.encrypted&&this.emeController&&this.config.emeEnabled?this.emeController.selectKeySystemFormat(e).then(t=>this.loadInternal(e,t)):this.loadInternal(e)}loadInternal(e,t){var i,r;t&&e.setKeyFormat(t);let n=e.decryptdata;if(!n){let d=new Error(t?`Expected frag.decryptdata to be defined after setting format ${t}`:`Missing decryption data on fragment in onKeyLoading (emeEnabled with controller: ${this.emeController&&this.config.emeEnabled})`);return Promise.reject(this.createKeyLoadError(e,x.KEY_LOAD_ERROR,d))}let a=n.uri;if(!a)return Promise.reject(this.createKeyLoadError(e,x.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${a}"`)));let o=uc(n),l=this.keyIdToKeyInfo[o];if((i=l)!=null&&i.decryptdata.key)return n.key=l.decryptdata.key,Promise.resolve({frag:e,keyInfo:l});if(this.emeController&&(r=l)!=null&&r.keyLoadPromise)switch(this.emeController.getKeyStatus(l.decryptdata)){case "usable":case "usable-in-future":return l.keyLoadPromise.then(c=>{let{keyInfo:u}=c;return n.key=u.decryptdata.key,{frag:e,keyInfo:u}})}switch(this.log(`${this.keyIdToKeyInfo[o]?"Rel":"L"}oading${n.keyId?" keyId: "+rt(n.keyId):""} URI: ${n.uri} from ${e.type} ${e.level}`),l=this.keyIdToKeyInfo[o]={decryptdata:n,keyLoadPromise:null,loader:null,mediaKeySessionContext:null},n.method){case "SAMPLE-AES":case "SAMPLE-AES-CENC":case "SAMPLE-AES-CTR":return n.keyFormat==="identity"?this.loadKeyHTTP(l,e):this.loadKeyEME(l,e);case "AES-128":case "AES-256":case "AES-256-CTR":return this.loadKeyHTTP(l,e);default:return Promise.reject(this.createKeyLoadError(e,x.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${n.method}"`)))}}loadKeyEME(e,t){let i={frag:t,keyInfo:e};if(this.emeController&&this.config.emeEnabled){var r;if(!e.decryptdata.keyId&&(r=t.initSegment)!=null&&r.data){let a=oT(t.initSegment.data);if(a.length){let o=a[0];o.some(l=>l!==0)&&(this.log(`Using keyId found in init segment ${rt(o)}`),e.decryptdata.keyId=o,Tn.setKeyIdForUri(e.decryptdata.uri,o));}}let n=this.emeController.loadKey(i);return (e.keyLoadPromise=n.then(a=>(e.mediaKeySessionContext=a,i))).catch(a=>{throw e.keyLoadPromise=null,"data"in a&&(a.data.frag=t),a})}return Promise.resolve(i)}loadKeyHTTP(e,t){let i=this.config,r=i.loader,n=new r(i);return t.keyLoader=e.loader=n,e.keyLoadPromise=new Promise((a,o)=>{let l={keyInfo:e,frag:t,responseType:"arraybuffer",url:e.decryptdata.uri},d=i.keyLoadPolicy.default,c={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},u={onSuccess:(h,f,m,p)=>{let{frag:E,keyInfo:v}=m,T=uc(v.decryptdata);if(!E.decryptdata||v!==this.keyIdToKeyInfo[T])return o(this.createKeyLoadError(E,x.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),p));v.decryptdata.key=E.decryptdata.key=new Uint8Array(h.data),E.keyLoader=null,v.loader=null,a({frag:E,keyInfo:v});},onError:(h,f,m,p)=>{this.resetLoader(f),o(this.createKeyLoadError(t,x.KEY_LOAD_ERROR,new Error(`HTTP Error ${h.code} loading key ${h.text}`),m,ve({url:l.url,data:void 0},h)));},onTimeout:(h,f,m)=>{this.resetLoader(f),o(this.createKeyLoadError(t,x.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),m));},onAbort:(h,f,m)=>{this.resetLoader(f),o(this.createKeyLoadError(t,x.INTERNAL_ABORTED,new Error("key loading aborted"),m));}};n.load(l,c,u);})}resetLoader(e){let{frag:t,keyInfo:i,url:r}=e,n=i.loader;t.keyLoader===n&&(t.keyLoader=null,i.loader=null);let a=uc(i.decryptdata)||r;delete this.keyIdToKeyInfo[a],n&&n.destroy();}};function uc(s){if(s.keyFormat!==Xe.FAIRPLAY){let e=s.keyId;if(e)return rt(e)}return s.uri}function Ag(s){let{type:e}=s;switch(e){case ce.AUDIO_TRACK:return W.AUDIO;case ce.SUBTITLE_TRACK:return W.SUBTITLE;default:return W.MAIN}}function hc(s,e){let t=s.url;return (t===void 0||t.indexOf("data:")===0)&&(t=e.url),t}var Cu=class{constructor(e){this.hls=void 0,this.loaders=Object.create(null),this.variableList=null,this.onManifestLoaded=this.checkAutostartLoad,this.hls=e,this.registerListeners();}startLoad(e){}stopLoad(){this.destroyInternalLoaders();}registerListeners(){let{hls:e}=this;e.on(g.MANIFEST_LOADING,this.onManifestLoading,this),e.on(g.LEVEL_LOADING,this.onLevelLoading,this),e.on(g.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.on(g.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.on(g.LEVELS_UPDATED,this.onLevelsUpdated,this);}unregisterListeners(){let{hls:e}=this;e.off(g.MANIFEST_LOADING,this.onManifestLoading,this),e.off(g.LEVEL_LOADING,this.onLevelLoading,this),e.off(g.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.off(g.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.off(g.LEVELS_UPDATED,this.onLevelsUpdated,this);}createInternalLoader(e){let t=this.hls.config,i=t.pLoader,r=t.loader,n=i||r,a=new n(t);return this.loaders[e.type]=a,a}getInternalLoader(e){return this.loaders[e.type]}resetInternalLoader(e){this.loaders[e]&&delete this.loaders[e];}destroyInternalLoaders(){for(let e in this.loaders){let t=this.loaders[e];t&&t.destroy(),this.resetInternalLoader(e);}}destroy(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders();}onManifestLoading(e,t){let{url:i}=t;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:ce.MANIFEST,url:i,deliveryDirectives:null,levelOrTrack:null});}onLevelLoading(e,t){let{id:i,level:r,pathwayId:n,url:a,deliveryDirectives:o,levelInfo:l}=t;this.load({id:i,level:r,pathwayId:n,responseType:"text",type:ce.LEVEL,url:a,deliveryDirectives:o,levelOrTrack:l});}onAudioTrackLoading(e,t){let{id:i,groupId:r,url:n,deliveryDirectives:a,track:o}=t;this.load({id:i,groupId:r,level:null,responseType:"text",type:ce.AUDIO_TRACK,url:n,deliveryDirectives:a,levelOrTrack:o});}onSubtitleTrackLoading(e,t){let{id:i,groupId:r,url:n,deliveryDirectives:a,track:o}=t;this.load({id:i,groupId:r,level:null,responseType:"text",type:ce.SUBTITLE_TRACK,url:n,deliveryDirectives:a,levelOrTrack:o});}onLevelsUpdated(e,t){let i=this.loaders[ce.LEVEL];if(i){let r=i.context;r&&!t.levels.some(n=>n===r.levelOrTrack)&&(i.abort(),delete this.loaders[ce.LEVEL]);}}load(e){var t;let i=this.hls.config,r=this.getInternalLoader(e);if(r){let d=this.hls.logger,c=r.context;if(c&&c.levelOrTrack===e.levelOrTrack&&(c.url===e.url||c.deliveryDirectives&&!e.deliveryDirectives)){c.url===e.url?d.log(`[playlist-loader]: ignore ${e.url} ongoing request`):d.log(`[playlist-loader]: ignore ${e.url} in favor of ${c.url}`);return}d.log(`[playlist-loader]: aborting previous loader for type: ${e.type}`),r.abort();}let n;if(e.type===ce.MANIFEST?n=i.manifestLoadPolicy.default:n=ye({},i.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),r=this.createInternalLoader(e),G((t=e.deliveryDirectives)==null?void 0:t.part)){let d;if(e.type===ce.LEVEL&&e.level!==null?d=this.hls.levels[e.level].details:e.type===ce.AUDIO_TRACK&&e.id!==null?d=this.hls.audioTracks[e.id].details:e.type===ce.SUBTITLE_TRACK&&e.id!==null&&(d=this.hls.subtitleTracks[e.id].details),d){let c=d.partTarget,u=d.targetduration;if(c&&u){let h=Math.max(c*3,u*.8)*1e3;n=ye({},n,{maxTimeToFirstByteMs:Math.min(h,n.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(h,n.maxTimeToFirstByteMs)});}}}let a=n.errorRetry||n.timeoutRetry||{},o={loadPolicy:n,timeout:n.maxLoadTimeMs,maxRetry:a.maxNumRetry||0,retryDelay:a.retryDelayMs||0,maxRetryDelay:a.maxRetryDelayMs||0},l={onSuccess:(d,c,u,h)=>{let f=this.getInternalLoader(u);this.resetInternalLoader(u.type);let m=d.data;c.parsing.start=performance.now(),as.isMediaPlaylist(m)||u.type!==ce.MANIFEST?this.handleTrackOrLevelPlaylist(d,c,u,h||null,f):this.handleMasterPlaylist(d,c,u,h);},onError:(d,c,u,h)=>{this.handleNetworkError(c,u,false,d,h);},onTimeout:(d,c,u)=>{this.handleNetworkError(c,u,true,void 0,d);}};r.load(e,o,l);}checkAutostartLoad(){if(!this.hls)return;let{config:{autoStartLoad:e,startPosition:t},forceStartLoad:i}=this.hls;(e||i)&&(this.hls.logger.log(`${e?"auto":"force"} startLoad with configured startPosition ${t}`),this.hls.startLoad(t));}handleMasterPlaylist(e,t,i,r){let n=this.hls,a=e.data,o=hc(e,i),l=as.parseMasterPlaylist(a,o);if(l.playlistParsingError){t.parsing.end=performance.now(),this.handleManifestParsingError(e,i,l.playlistParsingError,r,t);return}let{contentSteering:d,levels:c,sessionData:u,sessionKeys:h,startTimeOffset:f,variableList:m}=l;this.variableList=m,c.forEach(T=>{let{unknownCodecs:S}=T;if(S){let{preferManagedMediaSource:A}=this.hls.config,{audioCodec:b,videoCodec:D}=T;for(let I=S.length;I--;){let k=S[I];gn(k,"audio",A)?(T.audioCodec=b=b?`${b},${k}`:k,ar.audio[b.substring(0,4)]=2,S.splice(I,1)):gn(k,"video",A)&&(T.videoCodec=D=D?`${D},${k}`:k,ar.video[D.substring(0,4)]=2,S.splice(I,1));}}});let{AUDIO:p=[],SUBTITLES:E,"CLOSED-CAPTIONS":v}=as.parseMasterPlaylistMedia(a,o,l);p.length&&!p.some(S=>!S.url)&&c[0].audioCodec&&!c[0].attrs.AUDIO&&(this.hls.logger.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),p.unshift({type:"main",name:"main",groupId:"main",default:false,autoselect:false,forced:false,id:-1,attrs:new Re({}),bitrate:0,url:""})),n.trigger(g.MANIFEST_LOADED,{levels:c,audioTracks:p,subtitles:E,captions:v,contentSteering:d,url:o,stats:t,networkDetails:r,sessionData:u,sessionKeys:h,startTimeOffset:f,variableList:m});}handleTrackOrLevelPlaylist(e,t,i,r,n){let a=this.hls,{id:o,level:l,type:d}=i,c=hc(e,i),u=G(l)?l:G(o)?o:0,h=Ag(i),f=as.parseLevelPlaylist(e.data,c,u,h,0,this.variableList);if(d===ce.MANIFEST){let m={attrs:new Re({}),bitrate:0,details:f,name:"",url:c};f.requestScheduled=t.loading.start+Xg(f,0),a.trigger(g.MANIFEST_LOADED,{levels:[m],audioTracks:[],url:c,stats:t,networkDetails:r,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null});}t.parsing.end=performance.now(),i.levelDetails=f,this.handlePlaylistLoaded(f,e,t,i,r,n);}handleManifestParsingError(e,t,i,r,n){this.hls.trigger(g.ERROR,{type:z.NETWORK_ERROR,details:x.MANIFEST_PARSING_ERROR,fatal:t.type===ce.MANIFEST,url:e.url,err:i,error:i,reason:i.message,response:e,context:t,networkDetails:r,stats:n});}handleNetworkError(e,t,i=false,r,n){let a=`A network ${i?"timeout":"error"+(r?" (status "+r.code+")":"")} occurred while loading ${e.type}`;e.type===ce.LEVEL?a+=`: ${e.level} id: ${e.id}`:(e.type===ce.AUDIO_TRACK||e.type===ce.SUBTITLE_TRACK)&&(a+=` id: ${e.id} group-id: "${e.groupId}"`);let o=new Error(a);this.hls.logger.warn(`[playlist-loader]: ${a}`);let l=x.UNKNOWN,d=false,c=this.getInternalLoader(e);switch(e.type){case ce.MANIFEST:l=i?x.MANIFEST_LOAD_TIMEOUT:x.MANIFEST_LOAD_ERROR,d=true;break;case ce.LEVEL:l=i?x.LEVEL_LOAD_TIMEOUT:x.LEVEL_LOAD_ERROR,d=false;break;case ce.AUDIO_TRACK:l=i?x.AUDIO_TRACK_LOAD_TIMEOUT:x.AUDIO_TRACK_LOAD_ERROR,d=false;break;case ce.SUBTITLE_TRACK:l=i?x.SUBTITLE_TRACK_LOAD_TIMEOUT:x.SUBTITLE_LOAD_ERROR,d=false;break}c&&this.resetInternalLoader(e.type);let u={type:z.NETWORK_ERROR,details:l,fatal:d,url:e.url,loader:c,context:e,error:o,networkDetails:t,stats:n};if(r){let h=t?.url||e.url;u.response=ve({url:h,data:void 0},r);}this.hls.trigger(g.ERROR,u);}handlePlaylistLoaded(e,t,i,r,n,a){let o=this.hls,{type:l,level:d,levelOrTrack:c,id:u,groupId:h,deliveryDirectives:f}=r,m=hc(t,r),p=Ag(r),E=typeof r.level=="number"&&p===W.MAIN?d:void 0,v=e.playlistParsingError;if(v){if(this.hls.logger.warn(`${v} ${e.url}`),!o.config.ignorePlaylistParsingErrors){o.trigger(g.ERROR,{type:z.NETWORK_ERROR,details:x.LEVEL_PARSING_ERROR,fatal:false,url:m,error:v,reason:v.message,response:t,context:r,level:E,parent:p,networkDetails:n,stats:i});return}e.playlistParsingError=null;}if(!e.fragments.length){let T=e.playlistParsingError=new Error("No Segments found in Playlist");o.trigger(g.ERROR,{type:z.NETWORK_ERROR,details:x.LEVEL_EMPTY_ERROR,fatal:false,url:m,error:T,reason:T.message,response:t,context:r,level:E,parent:p,networkDetails:n,stats:i});return}switch(e.live&&a&&(a.getCacheAge&&(e.ageHeader=a.getCacheAge()||0),(!a.getCacheAge||isNaN(e.ageHeader))&&(e.ageHeader=0)),l){case ce.MANIFEST:case ce.LEVEL:if(E){if(!c)E=0;else if(c!==o.levels[E]){let T=o.levels.indexOf(c);T>-1&&(E=T);}}o.trigger(g.LEVEL_LOADED,{details:e,levelInfo:c||o.levels[0],level:E||0,id:u||0,stats:i,networkDetails:n,deliveryDirectives:f,withoutMultiVariant:l===ce.MANIFEST});break;case ce.AUDIO_TRACK:o.trigger(g.AUDIO_TRACK_LOADED,{details:e,track:c,id:u||0,groupId:h||"",stats:i,networkDetails:n,deliveryDirectives:f});break;case ce.SUBTITLE_TRACK:o.trigger(g.SUBTITLE_TRACK_LOADED,{details:e,track:c,id:u||0,groupId:h||"",stats:i,networkDetails:n,deliveryDirectives:f});break}}},ui=class s{static get version(){return Sn}static isMSESupported(){return Vp()}static isSupported(){return WA()}static getMediaSource(){return Fi()}static get Events(){return g}static get MetadataSchema(){return At}static get ErrorTypes(){return z}static get ErrorDetails(){return x}static get DefaultConfig(){return s.defaultConfig?s.defaultConfig:NA}static set DefaultConfig(e){s.defaultConfig=e;}constructor(e={}){this.config=void 0,this.userConfig=void 0,this.logger=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this._emitter=new Bu,this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.abrController=void 0,this.bufferController=void 0,this.capLevelController=void 0,this.latencyController=void 0,this.levelController=void 0,this.streamController=void 0,this.audioStreamController=void 0,this.subtititleStreamController=void 0,this.audioTrackController=void 0,this.subtitleTrackController=void 0,this.interstitialsController=void 0,this.gapController=void 0,this.emeController=void 0,this.cmcdController=void 0,this._media=null,this._url=null,this._sessionId=void 0,this.triggeringException=void 0,this.started=false;let t=this.logger=Qv(e.debug||false,"Hls instance",e.assetPlayerId),i=this.config=BA(s.DefaultConfig,e,t);this.userConfig=e,i.progressive&&$A(i,t);let{abrController:r,bufferController:n,capLevelController:a,errorController:o,fpsController:l}=i,d=new o(this),c=this.abrController=new r(this),u=new Ac(this),h=i.interstitialsController,f=h?this.interstitialsController=new h(this,s):null,m=this.bufferController=new n(this,u),p=this.capLevelController=new a(this),E=new l(this),v=new Cu(this),T=i.contentSteeringController,S=T?new T(this):null,A=this.levelController=new Ru(this,S),b=new Lu(this),D=new Du(this.config,this.logger),I=this.streamController=new ku(this,u,D),k=this.gapController=new _u(this,u);p.setStreamController(I),E.setStreamController(I);let R=[v,A,I];f&&R.splice(1,0,f),S&&R.splice(1,0,S),this.networkControllers=R;let L=[c,m,k,p,E,b,u];this.audioTrackController=this.createController(i.audioTrackController,R);let M=i.audioStreamController;M&&R.push(this.audioStreamController=new M(this,u,D)),this.subtitleTrackController=this.createController(i.subtitleTrackController,R);let B=i.subtitleStreamController;B&&R.push(this.subtititleStreamController=new B(this,u,D)),this.createController(i.timelineController,L),D.emeController=this.emeController=this.createController(i.emeController,L),this.cmcdController=this.createController(i.cmcdController,L),this.latencyController=this.createController(xu,L),this.coreComponents=L,R.push(d);let H=d.onErrorOut;typeof H=="function"&&this.on(g.ERROR,H,d),this.on(g.MANIFEST_LOADED,v.onManifestLoaded,v);}createController(e,t){if(e){let i=new e(this);return t&&t.push(i),i}return null}on(e,t,i=this){this._emitter.on(e,t,i);}once(e,t,i=this){this._emitter.once(e,t,i);}removeAllListeners(e){this._emitter.removeAllListeners(e);}off(e,t,i=this,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(this.logger.error("An internal error happened while handling event "+e+'. Error message: "'+i.message+'". Here is a stacktrace:',i),!this.triggeringException){this.triggeringException=true;let r=e===g.ERROR;this.trigger(g.ERROR,{type:z.OTHER_ERROR,details:x.INTERNAL_EXCEPTION,fatal:r,event:e,error:i}),this.triggeringException=false;}}return false}listenerCount(e){return this._emitter.listenerCount(e)}destroy(){this.logger.log("destroy"),this.trigger(g.DESTROYING,void 0),this.detachMedia(),this.removeAllListeners(),this._autoLevelCapping=-1,this._url=null,this.networkControllers.forEach(t=>t.destroy()),this.networkControllers.length=0,this.coreComponents.forEach(t=>t.destroy()),this.coreComponents.length=0;let e=this.config;e.xhrSetup=e.fetchSetup=void 0,this.userConfig=null;}attachMedia(e){if(!e||"media"in e&&!e.media){let n=new Error(`attachMedia failed: invalid argument (${e})`);this.trigger(g.ERROR,{type:z.OTHER_ERROR,details:x.ATTACH_MEDIA_ERROR,fatal:true,error:n});return}this.logger.log("attachMedia"),this._media&&(this.logger.warn("media must be detached before attaching"),this.detachMedia());let t="media"in e,i=t?e.media:e,r=t?e:{media:i};this._media=i,this.trigger(g.MEDIA_ATTACHING,r);}detachMedia(){this.logger.log("detachMedia"),this.trigger(g.MEDIA_DETACHING,{}),this._media=null;}transferMedia(){this._media=null;let e=this.bufferController.transferMedia();return this.trigger(g.MEDIA_DETACHING,{transferMedia:e}),e}loadSource(e){this.stopLoad();let t=this.media,i=this._url,r=this._url=Mu.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:true});this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.logger.log(`loadSource:${r}`),t&&i&&(i!==r||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(t)),this.trigger(g.MANIFEST_LOADING,{url:e});}get url(){return this._url}get hasEnoughToStart(){return this.streamController.hasEnoughToStart}get startPosition(){return this.streamController.startPositionValue}startLoad(e=-1,t){this.logger.log(`startLoad(${e+(t?", <skip seek to start>":"")})`),this.started=true,this.resumeBuffering();for(let i=0;i<this.networkControllers.length&&(this.networkControllers[i].startLoad(e,t),!(!this.started||!this.networkControllers));i++);}stopLoad(){this.logger.log("stopLoad"),this.started=false;for(let e=0;e<this.networkControllers.length&&(this.networkControllers[e].stopLoad(),!(this.started||!this.networkControllers));e++);}get loadingEnabled(){return this.started}get bufferingEnabled(){return this.streamController.bufferingEnabled}resumeBuffering(){this.bufferingEnabled||(this.logger.log("resume buffering"),this.networkControllers.forEach(e=>{e.resumeBuffering&&e.resumeBuffering();}));}pauseBuffering(){this.bufferingEnabled&&(this.logger.log("pause buffering"),this.networkControllers.forEach(e=>{e.pauseBuffering&&e.pauseBuffering();}));}get inFlightFragments(){let e={[W.MAIN]:this.streamController.inFlightFrag};return this.audioStreamController&&(e[W.AUDIO]=this.audioStreamController.inFlightFrag),this.subtititleStreamController&&(e[W.SUBTITLE]=this.subtititleStreamController.inFlightFrag),e}swapAudioCodec(){this.logger.log("swapAudioCodec"),this.streamController.swapAudioCodec();}recoverMediaError(){this.logger.log("recoverMediaError");let e=this._media,t=e?.currentTime;this.detachMedia(),e&&(this.attachMedia(e),t&&this.startLoad(t));}removeLevel(e){this.levelController.removeLevel(e);}get sessionId(){let e=this._sessionId;return e||(e=this._sessionId=nA()),e}get levels(){let e=this.levelController.levels;return e||[]}get latestLevelDetails(){return this.streamController.getLevelDetails()||null}get loadLevelObj(){return this.levelController.loadLevelObj}get currentLevel(){return this.streamController.currentLevel}set currentLevel(e){this.logger.log(`set currentLevel:${e}`),this.levelController.manualLevel=e,this.streamController.immediateLevelSwitch();}get nextLevel(){return this.streamController.nextLevel}set nextLevel(e){this.logger.log(`set nextLevel:${e}`),this.levelController.manualLevel=e,this.streamController.nextLevelSwitch();}get loadLevel(){return this.levelController.level}set loadLevel(e){this.logger.log(`set loadLevel:${e}`),this.levelController.manualLevel=e;}get nextLoadLevel(){return this.levelController.nextLoadLevel}set nextLoadLevel(e){this.levelController.nextLoadLevel=e;}get firstLevel(){return Math.max(this.levelController.firstLevel,this.minAutoLevel)}set firstLevel(e){this.logger.log(`set firstLevel:${e}`),this.levelController.firstLevel=e;}get startLevel(){let e=this.levelController.startLevel;return e===-1&&this.abrController.forcedAutoLevel>-1?this.abrController.forcedAutoLevel:e}set startLevel(e){this.logger.log(`set startLevel:${e}`),e!==-1&&(e=Math.max(e,this.minAutoLevel)),this.levelController.startLevel=e;}get capLevelToPlayerSize(){return this.config.capLevelToPlayerSize}set capLevelToPlayerSize(e){let t=!!e;t!==this.config.capLevelToPlayerSize&&(t?this.capLevelController.startCapping():(this.capLevelController.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=t);}get autoLevelCapping(){return this._autoLevelCapping}get bandwidthEstimate(){let{bwEstimator:e}=this.abrController;return e?e.getEstimate():NaN}set bandwidthEstimate(e){this.abrController.resetEstimator(e);}get abrEwmaDefaultEstimate(){let{bwEstimator:e}=this.abrController;return e?e.defaultEstimate:NaN}get ttfbEstimate(){let{bwEstimator:e}=this.abrController;return e?e.getEstimateTTFB():NaN}set autoLevelCapping(e){this._autoLevelCapping!==e&&(this.logger.log(`set autoLevelCapping:${e}`),this._autoLevelCapping=e,this.levelController.checkMaxAutoUpdated());}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(e){RT(e)&&this._maxHdcpLevel!==e&&(this._maxHdcpLevel=e,this.levelController.checkMaxAutoUpdated());}get autoLevelEnabled(){return this.levelController.manualLevel===-1}get manualLevel(){return this.levelController.manualLevel}get minAutoLevel(){let{levels:e,config:{minAutoBitrate:t}}=this;if(!e)return 0;let i=e.length;for(let r=0;r<i;r++)if(e[r].maxBitrate>=t)return r;return 0}get maxAutoLevel(){let{levels:e,autoLevelCapping:t,maxHdcpLevel:i}=this,r;if(t===-1&&e!=null&&e.length?r=e.length-1:r=t,i)for(let n=r;n--;){let 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()}get maxBufferLength(){return this.streamController.maxBufferLength}setAudioOption(e){var t;return ((t=this.audioTrackController)==null?void 0:t.setAudioOption(e))||null}setSubtitleOption(e){var t;return ((t=this.subtitleTrackController)==null?void 0:t.setSubtitleOption(e))||null}get allAudioTracks(){let e=this.audioTrackController;return e?e.allAudioTracks:[]}get audioTracks(){let e=this.audioTrackController;return e?e.audioTracks:[]}get audioTrack(){let e=this.audioTrackController;return e?e.audioTrack:-1}set audioTrack(e){let t=this.audioTrackController;t&&(t.audioTrack=e);}get allSubtitleTracks(){let e=this.subtitleTrackController;return e?e.allSubtitleTracks:[]}get subtitleTracks(){let e=this.subtitleTrackController;return e?e.subtitleTracks:[]}get subtitleTrack(){let e=this.subtitleTrackController;return e?e.subtitleTrack:-1}get media(){return this._media}set subtitleTrack(e){let t=this.subtitleTrackController;t&&(t.subtitleTrack=e);}get subtitleDisplay(){let e=this.subtitleTrackController;return e?e.subtitleDisplay:false}set subtitleDisplay(e){let t=this.subtitleTrackController;t&&(t.subtitleDisplay=e);}get lowLatencyMode(){return this.config.lowLatencyMode}set lowLatencyMode(e){this.config.lowLatencyMode=e;}get liveSyncPosition(){return this.latencyController.liveSyncPosition}get latency(){return this.latencyController.latency}get maxLatency(){return this.latencyController.maxLatency}get targetLatency(){return this.latencyController.targetLatency}set targetLatency(e){this.latencyController.targetLatency=e;}get drift(){return this.latencyController.drift}get forceStartLoad(){return this.streamController.forceStartLoad}get pathways(){return this.levelController.pathways}get pathwayPriority(){return this.levelController.pathwayPriority}set pathwayPriority(e){this.levelController.pathwayPriority=e;}get bufferedToEnd(){var e;return !!((e=this.bufferController)!=null&&e.bufferedToEnd)}get interstitialsManager(){var e;return ((e=this.interstitialsController)==null?void 0:e.interstitialsManager)||null}getMediaDecodingInfo(e,t=this.allAudioTracks){let i=Ug(t);return Fg(e,i,navigator.mediaCapabilities)}};ui.defaultConfig=void 0;var Yp=Symbol.for(""),jA=s=>{if(s?.r===Yp)return s?._$litStatic$},zu=s=>({_$litStatic$:s,r:Yp});var Wp=new Map,qp=s=>(e,...t)=>{let i=t.length,r,n,a=[],o=[],l,d=0,c=false;for(;d<i;){for(l=e[d];d<i&&(n=t[d],(r=jA(n))!==void 0);)l+=r+e[++d],c=true;d!==i&&o.push(n),a.push(l),d++;}if(d===i&&a.push(e[i]),c){let u=a.join("$$lit$$");(e=Wp.get(u))===void 0&&(a.raw=a,Wp.set(u,e=a)),t=o;}return s(e,...t)},jp=qp(chunk5NSCV6C2_cjs.c);var V,zp,Qp,gl,Xp,Zp,Jp,e0,Qu,Xu,Zu,pl,t0,Ju,eh,i0,th,El,ih,Rn,lr,sh,s0,r0,_e=class extends chunkEOHKHSQ3_cjs.a{constructor(){super(...arguments);chunkJHSFSCC2_cjs.e(this,V);this._controls=["play","time","seek","volume","audio-tracks","fullscreen","subtitles"];this.popped=false;this._startedPlaying=false;this._audioTrackCount=0;this._hlsAudioTracks=[];this._hlsAudioTrackIdMap=new Map;this._intersectionObserver=new chunkKVMGCTLR_cjs.a(this,{callback:chunkJHSFSCC2_cjs.g(this,V,Jp).bind(this)});this.embedController=new chunkYT56YDUY_cjs.b(this);this._intersected=false;this._queue=[];}get embed(){return this._embedId}set embed(t){this._embedId!=t&&(this._embedId=t,this.embedController.embed=this.embed,this.updateStylePoster(),this.loadTheme());}get token(){return this._token}set token(t){this._token!=t&&(this._token=t,this.requestUpdate("token"),this.embedController.token=this._token);}set loop(t){this._loop=(t===""||t=="true"||t==true)??false;}get loop(){return this._loop}get controls(){return this._controls}set controls(t){typeof t=="string"?this._controls=t.split(" "):this._controls=t;}get cache(){return this._cache}set cache(t){this._cache!=t&&(typeof t=="string"?this._cache=t==="true"||t==="":this._cache=false,this.requestUpdate("caching"),this.embedController.caching=this._cache);}get quality(){return this._quality}set quality(t){this._quality!=t&&(this._quality=t);}get theme(){return this._theme||"default"}set theme(t){this._theme!=t&&(this._theme=t,this.requestUpdate("theme"),this.loadTheme());}get poster(){return !this.embed||!this._embedObj?"":this._poster&&this._poster=="custom"?this.embedController.embedFile(chunkJHSFSCC2_cjs.g(this,V,gl).call(this,"custom_thumbnail")):this._poster&&(!Number.isNaN(parseFloat(this._poster))||!Number.isNaN(parseInt(this._poster)))?this._embedObj.poster&&this._embedObj.poster.renditions&&this._embedObj.poster.renditions.find(t=>t.type=="custom_thumbnail")?this.embedController.embedFile(chunkJHSFSCC2_cjs.g(this,V,gl).call(this,"custom_thumbnail")):`https://image.mave.io/${this.embedController.spaceId}${this.embedController.embedId}.jpg?time=${this._poster}`:this._poster?this._poster:this.embedController.embedFile(chunkJHSFSCC2_cjs.g(this,V,gl).call(this,"thumbnail"))}set poster(t){t&&(this._poster=t,this.requestUpdate("poster"));}pop(){this.popped=true;}close(){this.popped=false;}set muted(t){let i=(t===""||t=="true"||t==true)??false;this._videoElement?this._videoElement.muted=i:this._queue.push(()=>this._videoElement.muted=i);}get muted(){return this._videoElement?.muted||false}set currentTime(t){this._videoElement?this._videoElement.currentTime=t:this._queue.push(()=>this._videoElement.currentTime=t);}get currentTime(){return this._videoElement?this._videoElement?.currentTime:0}get duration(){return new Promise((t,i)=>{if(this._videoElement&&!isNaN(this._videoElement.duration))return t(this._videoElement.duration);let r=()=>{this._videoElement?.addEventListener("loadedmetadata",()=>{this._videoElement&&t(this._videoElement.duration);}),this._videoElement?.addEventListener("error",()=>{i(new Error("Failed to load video metadata."));});};this._videoElement?r():this.addEventListener("mave:video_element_ready",()=>{r();});})}get paused(){return this._videoElement?this._videoElement.paused:true}play(){this._videoElement&&!this.embedController.loading?chunkJHSFSCC2_cjs.g(this,V,pl).call(this):this._queue.push(()=>chunkJHSFSCC2_cjs.g(this,V,pl).call(this));}restart(){this._videoElement&&(this.pause(),this._videoElement.currentTime=0,this.play());}pause(){this._videoElement?this._videoElement.pause():this._queue.push(()=>this._videoElement?.pause());}updateStylePoster(){this.style.setProperty("background",`center / contain no-repeat url(${this.poster})`);}connectedCallback(){super.connectedCallback(),this.loadTheme(),this.addEventListener("mave:video_element_ready",chunkJHSFSCC2_cjs.g(this,V,Qp).bind(this));}disconnectedCallback(){super.disconnectedCallback(),this._metricsInstance?.demonitor(),this._cleanupHlsAudioTracks?.(),this._cleanupHlsAudioTracks=void 0,this._pendingAudioTrackSetup!=null&&(cancelAnimationFrame(this._pendingAudioTrackSetup),this._pendingAudioTrackSetup=void 0),this._hlsAudioTrackIdMap.clear(),this._hlsAudioTracks=[],this._currentAudioTrackMenu=void 0,this._themeMutationObserver?.disconnect(),this._themeMutationObserver=void 0,this._themeMutationObserverRoot=void 0;}loadTheme(){this.embed&&this._themeLoaded!=this.theme&&(this.theme&&this.theme.endsWith(".js")?chunkBVMU4ZXD_cjs.a.external(this.theme):chunkBVMU4ZXD_cjs.a.get(this.theme,`${this.embedController.cdnRoot}/themes/player`),this._themeLoaded=chunkBVMU4ZXD_cjs.a.getTheme());}updateEmbed(t){this._embedObj=t,this._audioTrackCount=t.audio_tracks?.length??0,this.updateStylePoster(),this.poster=this._embedObj.settings.poster,this.attributes.getNamedItem("color")||(this.color=this._embedObj.settings.color),this.attributes.getNamedItem("opacity")||(this.opacity=this._embedObj.settings.opacity?this._embedObj.settings.opacity:void 0),this.attributes.getNamedItem("aspect-ratio")||(this.aspect_ratio=this._embedObj.settings.aspect_ratio),this.attributes.getNamedItem("width")||(this.width=this._embedObj.settings.width),this.attributes.getNamedItem("height")||(this.height=this._embedObj.settings.height),this.attributes.getNamedItem("autoplay")||(this.autoplay=this._embedObj.settings.autoplay=="on_show"?"lazy":this._embedObj.settings.autoplay),this.attributes.getNamedItem("controls")||(this.controls=this._embedObj.settings.controls),this.attributes.getNamedItem("loop")||(this.loop=this._embedObj.settings.loop);}get styles(){let t={},i=!!this._embedObj?.subtitles?.length,r=this.subtitles==="none"||this.subtitles==="off"||!i,n=this.controls.includes("volume")||this.controls.includes("full");(this.color||this._embedObj?.settings.color)&&(t["--primary-color"]=`${this.color||this._embedObj?.settings.color}${this.opacity||this._embedObj?.settings.opacity?this._embedObj?.settings.opacity:""}`),this.aspect_ratio=="auto"||this._embedObj?.settings.aspect_ratio=="auto"&&!this.aspect_ratio?t["--aspect-ratio"]=this._embedObj?.video.aspect_ratio:t["--aspect-ratio"]=this.aspect_ratio||this._embedObj?.settings.aspect_ratio,(this.width||this._embedObj?.settings.width)&&(t["--width"]=this.width||this._embedObj?.settings.width),(this.height||this._embedObj?.settings.height)&&(t["--height"]=this.height||this._embedObj?.settings.height),!this.controls.includes("full")&&!this.controls.includes("big")&&!this.controls.includes("none")&&(t["--play-display"]=this.controls.includes("play")?"flex":"none",t["--time-display"]=this.controls.includes("time")?"flex":"none",t["--seek-bar-visibility"]=this.controls.includes("seek")?"visible":"hidden",t["--volume-display"]=this.controls.includes("volume")?"flex":"none",t["--fullscreen-display"]=this.controls.includes("fullscreen")?"flex":"none",t["--media-captions-menu-button-display"]=this.controls.includes("subtitles")?"flex":"none"),t["--playbackrate-display"]=this.controls.includes("rate")?"flex":"none",(r||this._embedObj?.created_at<1740674988&&!this.subtitles&&!this.active_subtitle)&&(t["--media-captions-menu-button-display"]="none"),this.controls.includes("full")||this._embedObj?.settings.controls=="full"&&!this.controls.includes("big")&&!this.controls.includes("none")?t["--media-control-bar-display"]="flex":t["--media-control-bar-display"]="none",this.controls.includes("big")||this._embedObj?.settings.controls=="big"&&!this.controls.includes("full")&&!this.controls.includes("none")?t["--big-button-display"]="flex":t["--big-button-display"]="none",this._embedObj?.video.audio===false?t["--media-mute-button-display"]="none":n?t["--media-mute-button-display"]="flex":t["--media-mute-button-display"]="none";let a=this._audioTrackCount??0,o=this.controls.includes("audio-tracks")||this.controls.includes("full");return t["--media-audio-track-menu-button-display"]=a>1&&o?"flex":"none",chunkQ22T22LT_cjs.a(t)}render(){if(!this.embed)return;let t=this.querySelector('[slot="start-screen"], [data-slot="start-screen"]');return chunk5NSCV6C2_cjs.c`
1386
+ `),d=[],c=e?Zy(e.baseTime,e.timescale):0,u="00:00.000",h=0,f=0,m,p=true;o.oncue=function(E){let v=t[i],T=t.ccOffset,S=(h-c)/9e4;if(v!=null&&v.new&&(f!==void 0?T=t.ccOffset=v.start:yA(t,i,S)),S){if(!e){m=new Error("Missing initPTS for VTT MPEGTS");return}T=S-t.presentationOffset;}let A=E.endTime-E.startTime,b=St((E.startTime+T-f)*9e4,r*9e4)/9e4;E.startTime=Math.max(b,0),E.endTime=Math.max(b+A,0);let D=E.text.trim();E.text=decodeURIComponent(encodeURIComponent(D)),E.id||(E.id=ju(E.startTime,E.endTime,D)),E.endTime>0&&d.push(E);},o.onparsingerror=function(E){m=E;},o.onflush=function(){if(m){a(m);return}n(d);},l.forEach(E=>{if(p)if(nc(E,"X-TIMESTAMP-MAP=")){p=false,E.slice(16).split(",").forEach(v=>{nc(v,"LOCAL:")?u=v.slice(6):nc(v,"MPEGTS:")&&(h=parseInt(v.slice(7)));});try{f=TA(u)/1e3;}catch(v){m=v;}return}else E===""&&(p=false);o.parse(E+`
1387
+ `);}),o.flush();}var ac="stpp.ttml.im1t",$p=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,Gp=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,AA={left:"start",center:"center",right:"end",start:"start",end:"end"};function gg(s,e,t,i){let r=le(new Uint8Array(s),["mdat"]);if(r.length===0){i(new Error("Could not parse IMSC1 mdat"));return}let n=r.map(o=>bt(o)),a=Xy(e.baseTime,1,e.timescale);try{n.forEach(o=>t(bA(o,a)));}catch(o){i(o);}}function bA(s,e){let r=new DOMParser().parseFromString(s,"text/xml").getElementsByTagName("tt")[0];if(!r)throw new Error("Invalid ttml");let n={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:0},a=Object.keys(n).reduce((u,h)=>(u[h]=r.getAttribute(`ttp:${h}`)||n[h],u),{}),o=r.getAttribute("xml:space")!=="preserve",l=pg(oc(r,"styling","style")),d=pg(oc(r,"layout","region")),c=oc(r,"body","[begin]");return [].map.call(c,u=>{let h=Hp(u,o);if(!h||!u.hasAttribute("begin"))return null;let f=dc(u.getAttribute("begin"),a),m=dc(u.getAttribute("dur"),a),p=dc(u.getAttribute("end"),a);if(f===null)throw Eg(u);if(p===null){if(m===null)throw Eg(u);p=f+m;}let E=new qu(f-e,p-e,h);E.id=ju(E.startTime,E.endTime,E.text);let v=d[u.getAttribute("region")],T=l[u.getAttribute("style")],S=_A(v,T,l),{textAlign:A}=S;if(A){let b=AA[A];b&&(E.lineAlign=b),E.align=A;}return ye(E,S),E}).filter(u=>u!==null)}function oc(s,e,t){let i=s.getElementsByTagName(e)[0];return i?[].slice.call(i.querySelectorAll(t)):[]}function pg(s){return s.reduce((e,t)=>{let i=t.getAttribute("xml:id");return i&&(e[i]=t),e},{})}function Hp(s,e){return [].slice.call(s.childNodes).reduce((t,i,r)=>{var n;return i.nodeName==="br"&&r?t+`
1388
+ `:(n=i.childNodes)!=null&&n.length?Hp(i,e):e?t+i.textContent.trim().replace(/\s+/g," "):t+i.textContent},"")}function _A(s,e,t){let i="http://www.w3.org/ns/ttml#styling",r=null,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)=>{let d=lc(e,i,l)||lc(s,i,l)||lc(r,i,l);return d&&(o[l]=d),o},{})}function lc(s,e,t){return s&&s.hasAttributeNS(e,t)?s.getAttributeNS(e,t):null}function Eg(s){return new Error(`Could not parse ttml timestamp ${s}`)}function dc(s,e){if(!s)return null;let t=Np(s);return t===null&&($p.test(s)?t=IA(s,e):Gp.test(s)&&(t=LA(s,e))),t}function IA(s,e){let t=$p.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 LA(s,e){let t=Gp.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}var tr=class{constructor(e,t){this.timelineController=void 0,this.cueRanges=[],this.trackName=void 0,this.startTime=null,this.endTime=null,this.screen=null,this.timelineController=e,this.trackName=t;}dispatchCue(){this.startTime!==null&&(this.timelineController.addCues(this.trackName,this.startTime,this.endTime,this.screen,this.cueRanges),this.startTime=null);}newCue(e,t,i){(this.startTime===null||this.startTime>e)&&(this.startTime=e),this.endTime=t,this.screen=i,this.timelineController.createCaptionsTrack(this.trackName);}reset(){this.cueRanges=[],this.startTime=null;}},Su=class{constructor(e){this.hls=void 0,this.media=null,this.config=void 0,this.enabled=true,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=Tg(),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(g.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(g.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(g.MANIFEST_LOADING,this.onManifestLoading,this),e.on(g.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(g.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(g.FRAG_LOADING,this.onFragLoading,this),e.on(g.FRAG_LOADED,this.onFragLoaded,this),e.on(g.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.on(g.FRAG_DECRYPTED,this.onFragDecrypted,this),e.on(g.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(g.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.on(g.BUFFER_FLUSHING,this.onBufferFlushing,this);}destroy(){let{hls:e}=this;e.off(g.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(g.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(g.MANIFEST_LOADING,this.onManifestLoading,this),e.off(g.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(g.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(g.FRAG_LOADING,this.onFragLoading,this),e.off(g.FRAG_LOADED,this.onFragLoaded,this),e.off(g.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.off(g.FRAG_DECRYPTED,this.onFragDecrypted,this),e.off(g.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(g.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.off(g.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.media=null,this.cea608Parser1=this.cea608Parser2=void 0;}initCea608Parsers(){let e=new tr(this,"textTrack1"),t=new tr(this,"textTrack2"),i=new tr(this,"textTrack3"),r=new tr(this,"textTrack4");this.cea608Parser1=new dl(1,e,t),this.cea608Parser2=new dl(3,i,r);}addCues(e,t,i,r,n){let a=false;for(let o=n.length;o--;){let l=n[o],d=xA(l[0],l[1],t,i);if(d>=0&&(l[0]=Math.min(l[0],t),l[1]=Math.max(l[1],i),a=true,d/(i-t)>.5))return}if(a||n.push([t,i]),this.config.renderTextTracksNatively){let o=this.captionsTracks[e];this.Cues.newCue(o,t,i,r);}else {let o=this.Cues.newCue(null,t,i,r);this.hls.trigger(g.CUES_PARSED,{type:"captions",cues:o,track:e});}}onInitPtsFound(e,{frag:t,id:i,initPTS:r,timescale:n,trackId:a}){let{unparsedVttFrags:o}=this;i===W.MAIN&&(this.initPTS[t.cc]={baseTime:r,timescale:n,trackId:a}),o.length&&(this.unparsedVttFrags=[],o.forEach(l=>{this.initPTS[l.frag.cc]?this.onFragLoaded(g.FRAG_LOADED,l):this.hls.trigger(g.SUBTITLE_FRAG_PROCESSED,{success:false,frag:l.frag,error:new Error("Subtitle discontinuity domain does not match main")});}));}getExistingTrack(e,t){let{media:i}=this;if(i)for(let r=0;r<i.textTracks.length;r++){let n=i.textTracks[r];if(vg(n,{name:e,lang:t,characteristics:"transcribes-spoken-dialog,describes-music-and-sound"}))return n}return null}createCaptionsTrack(e){this.config.renderTextTracksNatively?this.createNativeTrack(e):this.createNonNativeTrack(e);}createNativeTrack(e){if(this.captionsTracks[e])return;let{captionsProperties:t,captionsTracks:i,media:r}=this,{label:n,languageCode:a}=t[e],o=this.getExistingTrack(n,a);if(o)i[e]=o,er(i[e]),Pp(i[e],r);else {let l=this.createTextTrack("captions",n,a);l&&(l[e]=true,i[e]=l);}}createNonNativeTrack(e){if(this.nonNativeCaptionsTracks[e])return;let t=this.captionsProperties[e];if(!t)return;let i=t.label,r={_id:e,label:i,kind:"captions",default:t.media?!!t.media.default:false,closedCaptions:t.media};this.nonNativeCaptionsTracks[e]=r,this.hls.trigger(g.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[r]});}createTextTrack(e,t,i){let r=this.media;if(r)return r.addTextTrack(e,t,i)}onMediaAttaching(e,t){this.media=t.media,t.mediaSource||this._cleanTracks();}onMediaDetaching(e,t){let i=!!t.transferMedia;if(this.media=null,i)return;let{captionsTracks:r}=this;Object.keys(r).forEach(n=>{er(r[n]),delete r[n];}),this.nonNativeCaptionsTracks={};}onManifestLoading(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=Tg(),this._cleanTracks(),this.tracks=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.textTracks=[],this.unparsedVttFrags=[],this.initPTS=[],this.cea608Parser1&&this.cea608Parser2&&(this.cea608Parser1.reset(),this.cea608Parser2.reset());}_cleanTracks(){let{media:e}=this;if(!e)return;let t=e.textTracks;if(t)for(let i=0;i<t.length;i++)er(t[i]);}onSubtitleTracksUpdated(e,t){let i=t.subtitleTracks||[],r=i.some(n=>n.textCodec===ac);if(this.config.enableWebVTT||r&&this.config.enableIMSC1){if(Sp(this.tracks,i)){this.tracks=i;return}if(this.textTracks=[],this.tracks=i,this.config.renderTextTracksNatively){let a=this.media,o=a?Uo(a.textTracks):null;if(this.tracks.forEach((l,d)=>{let c;if(o){let u=null;for(let h=0;h<o.length;h++)if(o[h]&&vg(o[h],l)){u=o[h],o[h]=null;break}u&&(c=u);}if(c)er(c);else {let u=Kp(l);c=this.createTextTrack(u,l.name,l.lang),c&&(c.mode="disabled");}c&&this.textTracks.push(c);}),o!=null&&o.length){let l=o.filter(d=>d!==null).map(d=>d.label);l.length&&this.hls.logger.warn(`Media element contains unused subtitle tracks: ${l.join(", ")}. Replace media element for each source to clear TextTracks and captions menu.`);}}else if(this.tracks.length){let a=this.tracks.map(o=>({label:o.name,kind:o.type.toLowerCase(),default:o.default,subtitleTrack:o}));this.hls.trigger(g.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:a});}}}onManifestLoaded(e,t){this.config.enableCEA708Captions&&t.captions&&t.captions.forEach(i=>{let r=/(?:CC|SERVICE)([1-4])/.exec(i.instreamId);if(!r)return;let n=`textTrack${r[1]}`,a=this.captionsProperties[n];a&&(a.label=i.name,i.lang&&(a.languageCode=i.lang),a.media=i);});}closedCaptionsForLevel(e){let t=this.hls.levels[e.level];return t?.attrs["CLOSED-CAPTIONS"]}onFragLoading(e,t){if(this.enabled&&t.frag.type===W.MAIN){var i,r;let{cea608Parser1:n,cea608Parser2:a,lastSn:o}=this,{cc:l,sn:d}=t.frag,c=(i=(r=t.part)==null?void 0:r.index)!=null?i:-1;n&&a&&(d!==o+1||d===o&&c!==this.lastPartIndex+1||l!==this.lastCc)&&(n.reset(),a.reset()),this.lastCc=l,this.lastSn=d,this.lastPartIndex=c;}}onFragLoaded(e,t){let{frag:i,payload:r}=t;if(i.type===W.SUBTITLE)if(r.byteLength){let n=i.decryptdata,a="stats"in t;if(n==null||!n.encrypted||a){let o=this.tracks[i.level],l=this.vttCCs;l[i.cc]||(l[i.cc]={start:i.start,prevCC:this.prevCC,new:true},this.prevCC=i.cc),o&&o.textCodec===ac?this._parseIMSC1(i,r):this._parseVTTs(t);}}else this.hls.trigger(g.SUBTITLE_FRAG_PROCESSED,{success:false,frag:i,error:new Error("Empty subtitle payload")});}_parseIMSC1(e,t){let i=this.hls;gg(t,this.initPTS[e.cc],r=>{this._appendCues(r,e.level),i.trigger(g.SUBTITLE_FRAG_PROCESSED,{success:true,frag:e});},r=>{i.logger.log(`Failed to parse IMSC1: ${r}`),i.trigger(g.SUBTITLE_FRAG_PROCESSED,{success:false,frag:e,error:r});});}_parseVTTs(e){var t;let{frag:i,payload:r}=e,{initPTS:n,unparsedVttFrags:a}=this,o=n.length-1;if(!n[i.cc]&&o===-1){a.push(e);return}let l=this.hls,d=(t=i.initSegment)!=null&&t.data?Dt(i.initSegment.data,new Uint8Array(r)).buffer:r;SA(d,this.initPTS[i.cc],this.vttCCs,i.cc,i.start,c=>{this._appendCues(c,i.level),l.trigger(g.SUBTITLE_FRAG_PROCESSED,{success:true,frag:i});},c=>{let u=c.message==="Missing initPTS for VTT MPEGTS";u?a.push(e):this._fallbackToIMSC1(i,r),l.logger.log(`Failed to parse VTT cue: ${c}`),!(u&&o>i.cc)&&l.trigger(g.SUBTITLE_FRAG_PROCESSED,{success:false,frag:i,error:c});});}_fallbackToIMSC1(e,t){let i=this.tracks[e.level];i.textCodec||gg(t,this.initPTS[e.cc],()=>{i.textCodec=ac,this._parseIMSC1(e,t);},()=>{i.textCodec="wvtt";});}_appendCues(e,t){let i=this.hls;if(this.config.renderTextTracksNatively){let r=this.textTracks[t];if(!r||r.mode==="disabled")return;e.forEach(n=>wp(r,n));}else {let r=this.tracks[t];if(!r)return;let n=r.default?"default":"subtitles"+t;i.trigger(g.CUES_PARSED,{type:"subtitles",cues:e,track:n});}}onFragDecrypted(e,t){let{frag:i}=t;i.type===W.SUBTITLE&&this.onFragLoaded(g.FRAG_LOADED,t);}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={};}onFragParsingUserdata(e,t){if(!this.enabled||!this.config.enableCEA708Captions)return;let{frag:i,samples:r}=t;if(!(i.type===W.MAIN&&this.closedCaptionsForLevel(i)==="NONE"))for(let n=0;n<r.length;n++){let a=r[n].bytes;if(a){this.cea608Parser1||this.initCea608Parsers();let o=this.extractCea608Data(a);this.cea608Parser1.addData(r[n].pts,o[0]),this.cea608Parser2.addData(r[n].pts,o[1]);}}}onBufferFlushing(e,{startOffset:t,endOffset:i,endOffsetSubtitles:r,type:n}){let{media:a}=this;if(!(!a||a.currentTime<i)){if(!n||n==="video"){let{captionsTracks:o}=this;Object.keys(o).forEach(l=>nu(o[l],t,i));}if(this.config.renderTextTracksNatively&&t===0&&r!==void 0){let{textTracks:o}=this;Object.keys(o).forEach(l=>nu(o[l],t,r));}}}extractCea608Data(e){let t=[[],[]],i=e[0]&31,r=2;for(let n=0;n<i;n++){let a=e[r++],o=127&e[r++],l=127&e[r++];if(o===0&&l===0)continue;if((4&a)!==0){let c=3&a;(c===0||c===1)&&(t[c].push(o),t[c].push(l));}}return t}};function Kp(s){return s.characteristics&&/transcribes-spoken-dialog/gi.test(s.characteristics)&&/describes-music-and-sound/gi.test(s.characteristics)?"captions":"subtitles"}function vg(s,e){return !!s&&s.kind===Kp(e)&&qc(e,s)}function xA(s,e,t,i){return Math.min(e,i)-Math.max(s,t)}function Tg(){return {ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:true}}}var RA=/\s/,kA={newCue(s,e,t,i){let r=[],n,a,o,l,d,c=self.VTTCue||self.TextTrackCue;for(let h=0;h<i.rows.length;h++)if(n=i.rows[h],o=true,l=0,d="",!n.isEmpty()){var u;for(let p=0;p<n.chars.length;p++)RA.test(n.chars[p].uchar)&&o?l++:(d+=n.chars[p].uchar,o=false);n.cueStartTime=e,e===t&&(t+=1e-4),l>=16?l--:l++;let f=Bp(d.trim()),m=ju(e,t,f);s!=null&&(u=s.cues)!=null&&u.getCueById(m)||(a=new c(e,t,f),a.id=m,a.line=h+1,a.align="left",a.position=10+Math.min(80,Math.floor(l*8/32)*10),r.push(a));}return s&&r.length&&(r.sort((h,f)=>h.line==="auto"||f.line==="auto"?0:h.line>8&&f.line>8?f.line-h.line:h.line-f.line),r.forEach(h=>wp(s,h))),r}};function DA(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch{}return false}var CA=/(\d+)-(\d+)\/(\d+)/,cl=class{constructor(e){this.fetchSetup=void 0,this.requestTimeout=void 0,this.request=null,this.response=null,this.controller=void 0,this.context=null,this.config=null,this.callbacks=null,this.stats=void 0,this.loader=null,this.fetchSetup=e.fetchSetup||OA,this.controller=new self.AbortController,this.stats=new mn;}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=true,this.controller.abort());}abort(){var e;this.abortInternal(),(e=this.callbacks)!=null&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.response);}load(e,t,i){let r=this.stats;if(r.loading.start)throw new Error("Loader can only be used once.");r.loading.start=self.performance.now();let n=MA(e,this.controller.signal),a=e.responseType==="arraybuffer",o=a?"byteLength":"length",{maxTimeToFirstByteMs:l,maxLoadTimeMs:d}=t.loadPolicy;this.context=e,this.config=t,this.callbacks=i,this.request=this.fetchSetup(e,n),self.clearTimeout(this.requestTimeout),t.timeout=l&&G(l)?l:d,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(r,e,this.response));},t.timeout),(_n(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then(u=>{var h;this.response=this.loader=u;let f=Math.max(self.performance.now(),r.loading.start);if(self.clearTimeout(this.requestTimeout),t.timeout=d,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(r,e,this.response));},d-(f-r.loading.start)),!u.ok){let{status:p,statusText:E}=u;throw new Au(E||"fetch, bad network response",p,u)}r.loading.first=f,r.total=wA(u.headers)||r.total;let m=(h=this.callbacks)==null?void 0:h.onProgress;return m&&G(t.highWaterMark)?this.loadProgressively(u,r,e,t.highWaterMark,m):a?u.arrayBuffer():e.responseType==="json"?u.json():u.text()}).then(u=>{var h,f;let m=this.response;if(!m)throw new Error("loader destroyed");self.clearTimeout(this.requestTimeout),r.loading.end=Math.max(self.performance.now(),r.loading.first);let p=u[o];p&&(r.loaded=r.total=p);let E={url:m.url,data:u,code:m.status},v=(h=this.callbacks)==null?void 0:h.onProgress;v&&!G(t.highWaterMark)&&v(r,e,u,m),(f=this.callbacks)==null||f.onSuccess(E,r,e,m);}).catch(u=>{var h;if(self.clearTimeout(this.requestTimeout),r.aborted)return;let f=u&&u.code||0,m=u?u.message:null;(h=this.callbacks)==null||h.onError({code:f,text:m},e,u?u.details:null,r);});}getCacheAge(){let e=null;if(this.response){let t=this.response.headers.get("age");e=t?parseFloat(t):null;}return e}getResponseHeader(e){return this.response?this.response.headers.get(e):null}loadProgressively(e,t,i,r=0,n){let a=new Jo,o=e.body.getReader(),l=()=>o.read().then(d=>{if(d.done)return a.dataLength&&n(t,i,a.flush().buffer,e),Promise.resolve(new ArrayBuffer(0));let c=d.value,u=c.length;return t.loaded+=u,u<r||a.dataLength?(a.push(c),a.dataLength>=r&&n(t,i,a.flush().buffer,e)):n(t,i,c.buffer,e),l()}).catch(()=>Promise.reject());return l()}};function MA(s,e){let t={method:"GET",mode:"cors",credentials:"same-origin",signal:e,headers:new self.Headers(ye({},s.headers))};return s.rangeEnd&&t.headers.set("Range","bytes="+s.rangeStart+"-"+String(s.rangeEnd-1)),t}function PA(s){let e=CA.exec(s);if(e)return parseInt(e[2])-parseInt(e[1])+1}function wA(s){let e=s.get("Content-Range");if(e){let i=PA(e);if(G(i))return i}let t=s.get("Content-Length");if(t)return parseInt(t)}function OA(s,e){return new self.Request(s.url,e)}var Au=class extends Error{constructor(e,t,i){super(e),this.code=void 0,this.details=void 0,this.code=t,this.details=i;}},FA=/^age:\s*[\d.]+\s*$/im,ul=class{constructor(e){this.xhrSetup=void 0,this.requestTimeout=void 0,this.retryTimeout=void 0,this.retryDelay=void 0,this.config=null,this.callbacks=null,this.context=null,this.loader=null,this.stats=void 0,this.xhrSetup=e&&e.xhrSetup||null,this.stats=new mn,this.retryDelay=0;}destroy(){this.callbacks=null,this.abortInternal(),this.loader=null,this.config=null,this.context=null,this.xhrSetup=null;}abortInternal(){let e=this.loader;self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),e&&(e.onreadystatechange=null,e.onprogress=null,e.readyState!==4&&(this.stats.aborted=true,e.abort()));}abort(){var e;this.abortInternal(),(e=this.callbacks)!=null&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.loader);}load(e,t,i){if(this.stats.loading.start)throw new Error("Loader can only be used once.");this.stats.loading.start=self.performance.now(),this.context=e,this.config=t,this.callbacks=i,this.loadInternal();}loadInternal(){let{config:e,context:t}=this;if(!e||!t)return;let i=this.loader=new self.XMLHttpRequest,r=this.stats;r.loading.first=0,r.loaded=0,r.aborted=false;let n=this.xhrSetup;n?Promise.resolve().then(()=>{if(!(this.loader!==i||this.stats.aborted))return n(i,t.url)}).catch(a=>{if(!(this.loader!==i||this.stats.aborted))return i.open("GET",t.url,true),n(i,t.url)}).then(()=>{this.loader!==i||this.stats.aborted||this.openAndSendXhr(i,t,e);}).catch(a=>{var o;(o=this.callbacks)==null||o.onError({code:i.status,text:a.message},t,i,r);}):this.openAndSendXhr(i,t,e);}openAndSendXhr(e,t,i){e.readyState||e.open("GET",t.url,true);let r=t.headers,{maxTimeToFirstByteMs:n,maxLoadTimeMs:a}=i.loadPolicy;if(r)for(let o in r)e.setRequestHeader(o,r[o]);t.rangeEnd&&e.setRequestHeader("Range","bytes="+t.rangeStart+"-"+(t.rangeEnd-1)),e.onreadystatechange=this.readystatechange.bind(this),e.onprogress=this.loadprogress.bind(this),e.responseType=t.responseType,self.clearTimeout(this.requestTimeout),i.timeout=n&&G(n)?n:a,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),i.timeout),e.send();}readystatechange(){let{context:e,loader:t,stats:i}=this;if(!e||!t)return;let 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;let d=t.status,c=t.responseType==="text"?t.responseText:null;if(d>=200&&d<300){let m=c??t.response;if(m!=null){var a,o;i.loading.end=Math.max(self.performance.now(),i.loading.first);let p=t.responseType==="arraybuffer"?m.byteLength:m.length;i.loaded=i.total=p,i.bwEstimate=i.total*8e3/(i.loading.end-i.loading.first);let E=(a=this.callbacks)==null?void 0:a.onProgress;E&&E(i,e,m,t);let v={url:t.responseURL,data:m,code:d};(o=this.callbacks)==null||o.onSuccess(v,i,e,t);return}}let u=n.loadPolicy.errorRetry,h=i.retry,f={url:e.url,data:void 0,code:d};if(qo(u,h,false,f))this.retry(u);else {var l;Te.error(`${d} while loading ${e.url}`),(l=this.callbacks)==null||l.onError({code:d,text:t.statusText},e,t,i);}}}loadtimeout(){if(!this.config)return;let e=this.config.loadPolicy.timeoutRetry,t=this.stats.retry;if(qo(e,t,true))this.retry(e);else {var i;Te.warn(`timeout while loading ${(i=this.context)==null?void 0:i.url}`);let r=this.callbacks;r&&(this.abortInternal(),r.onTimeout(this.stats,this.context,this.loader));}}retry(e){let{context:t,stats:i}=this;this.retryDelay=Fu(e,i.retry),i.retry++,Te.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${t?.url}, retrying ${i.retry}/${e.maxNumRetry} in ${this.retryDelay}ms`),this.abortInternal(),this.loader=null,self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(this.loadInternal.bind(this),this.retryDelay);}loadprogress(e){let t=this.stats;t.loaded=e.loaded,e.lengthComputable&&(t.total=e.total);}getCacheAge(){let e=null;if(this.loader&&FA.test(this.loader.getAllResponseHeaders())){let t=this.loader.getResponseHeader("age");e=t?parseFloat(t):null;}return e}getResponseHeader(e){return this.loader&&new RegExp(`^${e}:\\s*[\\d.]+\\s*$`,"im").test(this.loader.getAllResponseHeaders())?this.loader.getResponseHeader(e):null}},NA={maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null},UA=ve(ve({autoStartLoad:true,startPosition:-1,defaultAudioCodec:void 0,debug:false,capLevelOnFPSDrop:false,capLevelToPlayerSize:false,ignoreDevicePixelRatio:false,maxDevicePixelRatio:Number.POSITIVE_INFINITY,preferManagedMediaSource:true,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,frontBufferFlushThreshold:1/0,startOnSegmentBoundary:false,maxBufferSize:60*1e3*1e3,maxFragLookUpTolerance:.25,maxBufferHole:.1,detectStallWithCurrentTimeMs:1250,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,nudgeOnVideoHole:true,liveSyncMode:"edge",liveSyncDurationCount:3,liveSyncOnStallIncrease:1,liveMaxLatencyDurationCount:1/0,liveSyncDuration:void 0,liveMaxLatencyDuration:void 0,maxLiveSyncPlaybackRate:1,liveDurationInfinity:false,liveBackBufferLength:null,maxMaxBufferLength:600,enableWorker:true,workerPath:null,enableSoftwareAES:true,startLevel:void 0,startFragPrefetch:false,fpsDroppedMonitoringPeriod:5e3,fpsDroppedMonitoringThreshold:.2,appendErrorMaxRetry:3,ignorePlaylistParsingErrors:false,loader:ul,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:Tc,bufferController:Xc,capLevelController:Zc,errorController:Sc,fpsController:ru,stretchShortVideoTrack:false,maxAudioFramesDrift:1,forceKeyFrameOnDiscontinuity:true,abrEwmaFastLive:3,abrEwmaSlowLive:9,abrEwmaFastVoD:3,abrEwmaSlowVoD:9,abrEwmaDefaultEstimate:5e5,abrEwmaDefaultEstimateMax:5e6,abrBandWidthFactor:.95,abrBandWidthUpFactor:.7,abrMaxWithRealBitrate:false,maxStarvationDelay:4,maxLoadingDelay:4,minAutoBitrate:0,emeEnabled:false,widevineLicenseUrl:void 0,drmSystems:{},drmSystemOptions:{},requestMediaKeySystemAccessFunc:qg,requireKeySystemAccessOnStart:false,testBandwidth:true,progressive:false,lowLatencyMode:true,cmcd:void 0,enableDateRangeMetadataCues:true,enableEmsgMetadataCues:true,enableEmsgKLVMetadata:false,enableID3MetadataCues:true,enableInterstitialPlayback:true,interstitialAppendInPlace:true,interstitialLiveLookAhead:10,useMediaCapabilities:true,preserveManualLevelOnError:false,certLoadPolicy:{default:NA},keyLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"},errorRetry:{maxNumRetry:8,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"}}},manifestLoadPolicy:{default:{maxTimeToFirstByteMs:1/0,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},playlistLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:2,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},fragLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:12e4,timeoutRetry:{maxNumRetry:4,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:6,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},steeringManifestLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},interstitialAssetListLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:3e4,timeoutRetry:{maxNumRetry:0,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:0,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},manifestLoadingTimeOut:1e4,manifestLoadingMaxRetry:1,manifestLoadingRetryDelay:1e3,manifestLoadingMaxRetryTimeout:64e3,levelLoadingTimeOut:1e4,levelLoadingMaxRetry:4,levelLoadingRetryDelay:1e3,levelLoadingMaxRetryTimeout:64e3,fragLoadingTimeOut:2e4,fragLoadingMaxRetry:6,fragLoadingRetryDelay:1e3,fragLoadingMaxRetryTimeout:64e3},BA()),{},{subtitleStreamController:hu,subtitleTrackController:au,timelineController:Su,audioStreamController:Yc,audioTrackController:jc,emeController:nl,cmcdController:iu,contentSteeringController:su,interstitialsController:uu});function BA(){return {cueHandler:kA,enableWebVTT:true,enableIMSC1:true,enableCEA708Captions:true,captionsTextTrack1Label:"English",captionsTextTrack1LanguageCode:"en",captionsTextTrack2Label:"Spanish",captionsTextTrack2LanguageCode:"es",captionsTextTrack3Label:"Unknown CC",captionsTextTrack3LanguageCode:"",captionsTextTrack4Label:"Unknown CC",captionsTextTrack4LanguageCode:"",renderTextTracksNatively:true}}function $A(s,e,t){if((e.liveSyncDurationCount||e.liveMaxLatencyDurationCount)&&(e.liveSyncDuration||e.liveMaxLatencyDuration))throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");if(e.liveMaxLatencyDurationCount!==void 0&&(e.liveSyncDurationCount===void 0||e.liveMaxLatencyDurationCount<=e.liveSyncDurationCount))throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(e.liveMaxLatencyDuration!==void 0&&(e.liveSyncDuration===void 0||e.liveMaxLatencyDuration<=e.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');let i=bu(s),r=["manifest","level","frag"],n=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return r.forEach(a=>{let o=`${a==="level"?"playlist":a}LoadPolicy`,l=e[o]===void 0,d=[];n.forEach(c=>{let u=`${a}Loading${c}`,h=e[u];if(h!==void 0&&l){d.push(u);let f=i[o].default;switch(e[o]={default:f},c){case "TimeOut":f.maxLoadTimeMs=h,f.maxTimeToFirstByteMs=h;break;case "MaxRetry":f.errorRetry.maxNumRetry=h,f.timeoutRetry.maxNumRetry=h;break;case "RetryDelay":f.errorRetry.retryDelayMs=h,f.timeoutRetry.retryDelayMs=h;break;case "MaxRetryTimeout":f.errorRetry.maxRetryDelayMs=h,f.timeoutRetry.maxRetryDelayMs=h;break}}}),d.length&&t.warn(`hls.js config: "${d.join('", "')}" setting(s) are deprecated, use "${o}": ${Ae(e[o])}`);}),ve(ve({},i),e)}function bu(s){return s&&typeof s=="object"?Array.isArray(s)?s.map(bu):Object.keys(s).reduce((e,t)=>(e[t]=bu(s[t]),e),{}):s}function GA(s,e){let t=s.loader;t!==cl&&t!==ul?(e.log("[config]: Custom loader detected, cannot enable progressive streaming"),s.progressive=false):DA()&&(s.loader=cl,s.progressive=true,s.enableSoftwareAES=true,e.log("[config]: Progressive streaming enabled, using FetchLoader"));}var Bo=2,HA=.1,KA=.05,VA=100,_u=class extends jo{constructor(e,t){super("gap-controller",e.logger),this.hls=void 0,this.fragmentTracker=void 0,this.media=null,this.mediaSource=void 0,this.nudgeRetry=0,this.stallReported=false,this.stalled=null,this.moved=false,this.seeking=false,this.buffered={},this.lastCurrentTime=0,this.ended=0,this.waiting=0,this.onMediaPlaying=()=>{this.ended=0,this.waiting=0;},this.onMediaWaiting=()=>{var i;(i=this.media)!=null&&i.seeking||(this.waiting=self.performance.now(),this.tick());},this.onMediaEnded=()=>{if(this.hls){var i;this.ended=((i=this.media)==null?void 0:i.currentTime)||1,this.hls.trigger(g.MEDIA_ENDED,{stalled:false});}},this.hls=e,this.fragmentTracker=t,this.registerListeners();}registerListeners(){let{hls:e}=this;e&&(e.on(g.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(g.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(g.BUFFER_APPENDED,this.onBufferAppended,this));}unregisterListeners(){let{hls:e}=this;e&&(e.off(g.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(g.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(g.BUFFER_APPENDED,this.onBufferAppended,this));}destroy(){super.destroy(),this.unregisterListeners(),this.media=this.hls=this.fragmentTracker=null,this.mediaSource=void 0;}onMediaAttached(e,t){this.setInterval(VA),this.mediaSource=t.mediaSource;let i=this.media=t.media;nt(i,"playing",this.onMediaPlaying),nt(i,"waiting",this.onMediaWaiting),nt(i,"ended",this.onMediaEnded);}onMediaDetaching(e,t){this.clearInterval();let{media:i}=this;i&&(ut(i,"playing",this.onMediaPlaying),ut(i,"waiting",this.onMediaWaiting),ut(i,"ended",this.onMediaEnded),this.media=null),this.mediaSource=void 0;}onBufferAppended(e,t){this.buffered=t.timeRanges;}get hasBuffered(){return Object.keys(this.buffered).length>0}tick(){var e;if(!((e=this.media)!=null&&e.readyState)||!this.hasBuffered)return;let t=this.media.currentTime;this.poll(t,this.lastCurrentTime),this.lastCurrentTime=t;}poll(e,t){var i,r;let n=(i=this.hls)==null?void 0:i.config;if(!n)return;let a=this.media;if(!a)return;let{seeking:o}=a,l=this.seeking&&!o,d=!this.seeking&&o,c=a.paused&&!o||a.ended||a.playbackRate===0;if(this.seeking=o,e!==t){t&&(this.ended=0),this.moved=true,o||(this.nudgeRetry=0,n.nudgeOnVideoHole&&!c&&e>t&&this.nudgeOnVideoHole(e,t)),this.waiting===0&&this.stallResolved(e);return}if(d||l){l&&this.stallResolved(e);return}if(c){this.nudgeRetry=0,this.stallResolved(e),!this.ended&&a.ended&&this.hls&&(this.ended=e||1,this.hls.trigger(g.MEDIA_ENDED,{stalled:false}));return}if(!re.getBuffered(a).length){this.nudgeRetry=0;return}let u=re.bufferInfo(a,e,0),h=u.nextStart||0,f=this.fragmentTracker;if(o&&f&&this.hls){let D=yg(this.hls.inFlightFragments,e),I=u.len>Bo,k=!h||D||h-e>Bo&&!f.getPartialFragment(e);if(I||k)return;this.moved=false;}let m=(r=this.hls)==null?void 0:r.latestLevelDetails;if(!this.moved&&this.stalled!==null&&f){if(!(u.len>0)&&!h)return;let I=Math.max(h,u.start||0)-e,R=!!(m!=null&&m.live)?m.targetduration*2:Bo,L=Co(e,f);if(I>0&&(I<=R||L)){a.paused||this._trySkipBufferHole(L);return}}let p=n.detectStallWithCurrentTimeMs,E=self.performance.now(),v=this.waiting,T=this.stalled;if(T===null)if(v>0&&E-v<p)T=this.stalled=v;else {this.stalled=E;return}let S=E-T;if(!o&&(S>=p||v)&&this.hls){var A;if(((A=this.mediaSource)==null?void 0:A.readyState)==="ended"&&!(m!=null&&m.live)&&Math.abs(e-(m?.edge||0))<1){if(this.ended)return;this.ended=e||1,this.hls.trigger(g.MEDIA_ENDED,{stalled:true});return}if(this._reportStall(u),!this.media||!this.hls)return}let b=re.bufferInfo(a,e,n.maxBufferHole);this._tryFixBufferStall(b,S,e);}stallResolved(e){let t=this.stalled;if(t&&this.hls&&(this.stalled=null,this.stallReported)){let i=self.performance.now()-t;this.log(`playback not stuck anymore @${e}, after ${Math.round(i)}ms`),this.stallReported=false,this.waiting=0,this.hls.trigger(g.STALL_RESOLVED,{});}}nudgeOnVideoHole(e,t){var i;let r=this.buffered.video;if(this.hls&&this.media&&this.fragmentTracker&&(i=this.buffered.audio)!=null&&i.length&&r&&r.length>1&&e>r.end(0)){let n=re.bufferedInfo(re.timeRangesToArray(this.buffered.audio),e,0);if(n.len>1&&t>=n.start){let a=re.timeRangesToArray(r),o=re.bufferedInfo(a,t,0).bufferedIndex;if(o>-1&&o<a.length-1){let l=re.bufferedInfo(a,e,0).bufferedIndex,d=a[o].end,c=a[o+1].start;if((l===-1||l>o)&&c-d<1&&e-d<2){let u=new Error(`nudging playhead to flush pipeline after video hole. currentTime: ${e} hole: ${d} -> ${c} buffered index: ${l}`);this.warn(u.message),this.media.currentTime+=1e-6;let h=Co(e,this.fragmentTracker);h&&"fragment"in h?h=h.fragment:h||(h=void 0);let f=re.bufferInfo(this.media,e,0);this.hls.trigger(g.ERROR,{type:z.MEDIA_ERROR,details:x.BUFFER_SEEK_OVER_HOLE,fatal:false,error:u,reason:u.message,frag:h,buffer:f.len,bufferInfo:f});}}}}}_tryFixBufferStall(e,t,i){var r,n;let{fragmentTracker:a,media:o}=this,l=(r=this.hls)==null?void 0:r.config;if(!o||!a||!l)return;let d=(n=this.hls)==null?void 0:n.latestLevelDetails,c=Co(i,a);if((c||d!=null&&d.live&&i<d.fragmentStart)&&(this._trySkipBufferHole(c)||!this.media))return;let u=e.buffered,h=this.adjacentTraversal(e,i);(u&&u.length>1&&e.len>l.maxBufferHole||e.nextStart&&(e.nextStart-i<l.maxBufferHole||h))&&(t>l.highBufferWatchdogPeriod*1e3||this.waiting)&&(this.warn("Trying to nudge playhead over buffer-hole"),this._tryNudgeBuffer(e));}adjacentTraversal(e,t){let i=this.fragmentTracker,r=e.nextStart;if(i&&r){let n=i.getFragAtPos(t,W.MAIN),a=i.getFragAtPos(r,W.MAIN);if(n&&a)return a.sn-n.sn<2}return false}_reportStall(e){let{hls:t,media:i,stallReported:r,stalled:n}=this;if(!r&&n!==null&&i&&t){this.stallReported=true;let a=new Error(`Playback stalling at @${i.currentTime} due to low buffer (${Ae(e)})`);this.warn(a.message),t.trigger(g.ERROR,{type:z.MEDIA_ERROR,details:x.BUFFER_STALLED_ERROR,fatal:false,error:a,buffer:e.len,bufferInfo:e,stalled:{start:n}});}}_trySkipBufferHole(e){var t;let{fragmentTracker:i,media:r}=this,n=(t=this.hls)==null?void 0:t.config;if(!r||!i||!n)return 0;let a=r.currentTime,o=re.bufferInfo(r,a,0),l=a<o.start?o.start:o.nextStart;if(l&&this.hls){let c=o.len<=n.maxBufferHole,u=o.len>0&&o.len<1&&r.readyState<3,h=l-a;if(h>0&&(c||u)){if(h>n.maxBufferHole){let m=false;if(a===0){let p=i.getAppendedFrag(0,W.MAIN);p&&l<p.end&&(m=true);}if(!m&&e){var d;if(!((d=this.hls.loadLevelObj)!=null&&d.details)||yg(this.hls.inFlightFragments,l))return 0;let E=false,v=e.end;for(;v<l;){let T=Co(v,i);if(T)v+=T.duration;else {E=true;break}}if(E)return 0}}let f=Math.max(l+KA,a+HA);if(this.warn(`skipping hole, adjusting currentTime from ${a} to ${f}`),this.moved=true,r.currentTime=f,!(e!=null&&e.gap)){let m=new Error(`fragment loaded with buffer holes, seeking from ${a} to ${f}`),p={type:z.MEDIA_ERROR,details:x.BUFFER_SEEK_OVER_HOLE,fatal:false,error:m,reason:m.message,buffer:o.len,bufferInfo:o};e&&("fragment"in e?p.part=e:p.frag=e),this.hls.trigger(g.ERROR,p);}return f}}return 0}_tryNudgeBuffer(e){let{hls:t,media:i,nudgeRetry:r}=this,n=t?.config;if(!i||!n)return 0;let a=i.currentTime;if(this.nudgeRetry++,r<n.nudgeMaxRetry){let o=a+(r+1)*n.nudgeOffset,l=new Error(`Nudging 'currentTime' from ${a} to ${o}`);this.warn(l.message),i.currentTime=o,t.trigger(g.ERROR,{type:z.MEDIA_ERROR,details:x.BUFFER_NUDGE_ON_STALL,error:l,fatal:false,buffer:e.len,bufferInfo:e});}else {let o=new Error(`Playhead still not moving while enough data buffered @${a} after ${n.nudgeMaxRetry} nudges`);this.error(o.message),t.trigger(g.ERROR,{type:z.MEDIA_ERROR,details:x.BUFFER_STALLED_ERROR,error:o,fatal:true,buffer:e.len,bufferInfo:e});}}};function yg(s,e){let t=Sg(s.main);if(t&&t.start<=e)return t;let i=Sg(s.audio);return i&&i.start<=e?i:null}function Sg(s){if(!s)return null;switch(s.state){case C.IDLE:case C.STOPPED:case C.ENDED:case C.ERROR:return null}return s.frag}function Co(s,e){return e.getAppendedFrag(s,W.MAIN)||e.getPartialFragment(s)}var WA=.25;function Iu(){if(!(typeof self>"u"))return self.VTTCue||self.TextTrackCue}function cc(s,e,t,i,r){let n=new s(e,t,"");try{n.value=i,r&&(n.type=r);}catch{n=new s(e,t,Ae(r?ve({type:r},i):i));}return n}var Mo=(()=>{let s=Iu();try{s&&new s(0,Number.POSITIVE_INFINITY,"");}catch{return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})(),Lu=class{constructor(e){this.hls=void 0,this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.removeCues=true,this.assetCue=void 0,this.onEventCueEnter=()=>{this.hls&&this.hls.trigger(g.EVENT_CUE_ENTER,{});},this.hls=e,this._registerListeners();}destroy(){this._unregisterListeners(),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=this.onEventCueEnter=null;}_registerListeners(){let{hls:e}=this;e&&(e.on(g.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(g.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(g.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(g.MANIFEST_LOADING,this.onManifestLoading,this),e.on(g.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.on(g.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(g.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(g.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this));}_unregisterListeners(){let{hls:e}=this;e&&(e.off(g.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(g.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(g.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(g.MANIFEST_LOADING,this.onManifestLoading,this),e.off(g.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.off(g.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(g.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(g.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this));}onMediaAttaching(e,t){var i;this.media=t.media,((i=t.overrides)==null?void 0:i.cueRemoval)===false&&(this.removeCues=false);}onMediaAttached(){var e;let t=(e=this.hls)==null?void 0:e.latestLevelDetails;t&&this.updateDateRangeCues(t);}onMediaDetaching(e,t){this.media=null,!t.transferMedia&&(this.id3Track&&(this.removeCues&&er(this.id3Track,this.onEventCueEnter),this.id3Track=null),this.dateRangeCuesAppended={});}onManifestLoading(){this.dateRangeCuesAppended={};}createTrack(e){let t=this.getID3Track(e.textTracks);return t.mode="hidden",t}getID3Track(e){if(this.media){for(let t=0;t<e.length;t++){let i=e[t];if(i.kind==="metadata"&&i.label==="id3")return Pp(i,this.media),i}return this.media.addTextTrack("metadata","id3")}}onFragParsingMetadata(e,t){if(!this.media||!this.hls)return;let{enableEmsgMetadataCues:i,enableID3MetadataCues:r}=this.hls.config;if(!i&&!r)return;let{samples:n}=t;this.id3Track||(this.id3Track=this.createTrack(this.media));let a=Iu();if(a)for(let o=0;o<n.length;o++){let l=n[o].type;if(l===At.emsg&&!i||!r)continue;let d=cp(n[o].data),c=n[o].pts,u=c+n[o].duration;u>Mo&&(u=Mo),u-c<=0&&(u=c+WA);for(let f=0;f<d.length;f++){let m=d[f];if(!up(m)){this.updateId3CueEnds(c,l);let p=cc(a,c,u,m,l);p&&this.id3Track.addCue(p);}}}}updateId3CueEnds(e,t){var i;let r=(i=this.id3Track)==null?void 0:i.cues;if(r)for(let n=r.length;n--;){let a=r[n];a.type===t&&a.startTime<e&&a.endTime===Mo&&(a.endTime=e);}}onBufferFlushing(e,{startOffset:t,endOffset:i,type:r}){let{id3Track:n,hls:a}=this;if(!a)return;let{config:{enableEmsgMetadataCues:o,enableID3MetadataCues:l}}=a;if(n&&(o||l)){let d;r==="audio"?d=c=>c.type===At.audioId3&&l:r==="video"?d=c=>c.type===At.emsg&&o:d=c=>c.type===At.audioId3&&l||c.type===At.emsg&&o,nu(n,t,i,d);}}onLevelUpdated(e,{details:t}){this.updateDateRangeCues(t,true);}onLevelPtsUpdated(e,t){Math.abs(t.drift)>.01&&this.updateDateRangeCues(t.details);}updateDateRangeCues(e,t){if(!this.hls||!this.media)return;let{assetPlayerId:i,timelineOffset:r,enableDateRangeMetadataCues:n,interstitialsController:a}=this.hls.config;if(!n)return;let o=Iu();if(i&&r&&!a){let{fragmentStart:p,fragmentEnd:E}=e,v=this.assetCue;v?(v.startTime=p,v.endTime=E):o&&(v=this.assetCue=cc(o,p,E,{assetPlayerId:this.hls.config.assetPlayerId},"hlsjs.interstitial.asset"),v&&(v.id=i,this.id3Track||(this.id3Track=this.createTrack(this.media)),this.id3Track.addCue(v),v.addEventListener("enter",this.onEventCueEnter)));}if(!e.hasProgramDateTime)return;let{id3Track:l}=this,{dateRanges:d}=e,c=Object.keys(d),u=this.dateRangeCuesAppended;if(l&&t){var h;if((h=l.cues)!=null&&h.length){let p=Object.keys(u).filter(E=>!c.includes(E));for(let E=p.length;E--;){var f;let v=p[E],T=(f=u[v])==null?void 0:f.cues;delete u[v],T&&Object.keys(T).forEach(S=>{let A=T[S];if(A){A.removeEventListener("enter",this.onEventCueEnter);try{l.removeCue(A);}catch{}}});}}else u=this.dateRangeCuesAppended={};}let m=e.fragments[e.fragments.length-1];if(!(c.length===0||!G(m?.programDateTime))){this.id3Track||(this.id3Track=this.createTrack(this.media));for(let p=0;p<c.length;p++){let E=c[p],v=d[E],T=v.startTime,S=u[E],A=S?.cues||{},b=S?.durationKnown||false,D=Mo,{duration:I,endDate:k}=v;if(k&&I!==null)D=T+I,b=true;else if(v.endOnNext&&!b){let L=c.reduce((M,B)=>{if(B!==v.id){let K=d[B];if(K.class===v.class&&K.startDate>v.startDate&&(!M||v.startDate<M.startDate))return K}return M},null);L&&(D=L.startTime,b=true);}let R=Object.keys(v.attr);for(let L=0;L<R.length;L++){let M=R[L];if(!QT(M))continue;let B=A[M];if(B)b&&!(S!=null&&S.durationKnown)?B.endTime=D:Math.abs(B.startTime-T)>.01&&(B.startTime=T,B.endTime=D);else if(o){let K=v.attr[M];XT(M)&&(K=Ig(K));let V=cc(o,T,D,{key:M,data:K},At.dateRange);V&&(V.id=E,this.id3Track.addCue(V),A[M]=V,a&&(M==="X-ASSET-LIST"||M==="X-ASSET-URL")&&V.addEventListener("enter",this.onEventCueEnter));}}u[E]={cues:A,dateRange:v,durationKnown:b};}}}},xu=class{constructor(e){this.hls=void 0,this.config=void 0,this.media=null,this.currentTime=0,this.stallCount=0,this._latency=null,this._targetLatencyUpdated=false,this.onTimeupdate=()=>{let{media:t}=this,i=this.levelDetails;if(!t||!i)return;this.currentTime=t.currentTime;let r=this.computeLatency();if(r===null)return;this._latency=r;let{lowLatencyMode:n,maxLiveSyncPlaybackRate:a}=this.config;if(!n||a===1||!i.live)return;let o=this.targetLatency;if(o===null)return;let l=r-o,d=Math.min(this.maxLatency,o+i.targetduration);if(l<d&&l>.05&&this.forwardBufferLength>1){let u=Math.min(2,Math.max(1,a)),h=Math.round(2/(1+Math.exp(-0.75*l-this.edgeStalled))*20)/20,f=Math.min(u,Math.max(1,h));this.changeMediaPlaybackRate(t,f);}else t.playbackRate!==1&&t.playbackRate!==0&&this.changeMediaPlaybackRate(t,1);},this.hls=e,this.config=e.config,this.registerListeners();}get levelDetails(){var e;return ((e=this.hls)==null?void 0:e.latestLevelDetails)||null}get latency(){return this._latency||0}get maxLatency(){let{config:e}=this;if(e.liveMaxLatencyDuration!==void 0)return e.liveMaxLatencyDuration;let t=this.levelDetails;return t?e.liveMaxLatencyDurationCount*t.targetduration:0}get targetLatency(){let e=this.levelDetails;if(e===null||this.hls===null)return null;let{holdBack:t,partHoldBack:i,targetduration:r}=e,{liveSyncDuration:n,liveSyncDurationCount:a,lowLatencyMode:o}=this.config,l=this.hls.userConfig,d=o&&i||t;(this._targetLatencyUpdated||l.liveSyncDuration||l.liveSyncDurationCount||d===0)&&(d=n!==void 0?n:a*r);let c=r;return d+Math.min(this.stallCount*this.config.liveSyncOnStallIncrease,c)}set targetLatency(e){this.stallCount=0,this.config.liveSyncDuration=e,this._targetLatencyUpdated=true;}get liveSyncPosition(){let e=this.estimateLiveEdge(),t=this.targetLatency;if(e===null||t===null)return null;let i=this.levelDetails;if(i===null)return null;let r=i.edge,n=e-t-this.edgeStalled,a=r-i.totalduration,o=r-(this.config.lowLatencyMode&&i.partTarget||i.targetduration);return Math.min(Math.max(a,n),o)}get drift(){let e=this.levelDetails;return e===null?1:e.drift}get edgeStalled(){let e=this.levelDetails;if(e===null)return 0;let t=(this.config.lowLatencyMode&&e.partTarget||e.targetduration)*3;return Math.max(e.age-t,0)}get forwardBufferLength(){let{media:e}=this,t=this.levelDetails;if(!e||!t)return 0;let i=e.buffered.length;return (i?e.buffered.end(i-1):t.edge)-this.currentTime}destroy(){this.unregisterListeners(),this.onMediaDetaching(),this.hls=null;}registerListeners(){let{hls:e}=this;e&&(e.on(g.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(g.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(g.MANIFEST_LOADING,this.onManifestLoading,this),e.on(g.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(g.ERROR,this.onError,this));}unregisterListeners(){let{hls:e}=this;e&&(e.off(g.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(g.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(g.MANIFEST_LOADING,this.onManifestLoading,this),e.off(g.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(g.ERROR,this.onError,this));}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener("timeupdate",this.onTimeupdate);}onMediaDetaching(){this.media&&(this.media.removeEventListener("timeupdate",this.onTimeupdate),this.media=null);}onManifestLoading(){this._latency=null,this.stallCount=0;}onLevelUpdated(e,{details:t}){t.advanced&&this.onTimeupdate(),!t.live&&this.media&&this.media.removeEventListener("timeupdate",this.onTimeupdate);}onError(e,t){var i;t.details===x.BUFFER_STALLED_ERROR&&(this.stallCount++,this.hls&&(i=this.levelDetails)!=null&&i.live&&this.hls.logger.warn("[latency-controller]: Stall detected, adjusting target latency"));}changeMediaPlaybackRate(e,t){var i,r;e.playbackRate!==t&&((i=this.hls)==null||i.logger.debug(`[latency-controller]: latency=${this.latency.toFixed(3)}, targetLatency=${(r=this.targetLatency)==null?void 0:r.toFixed(3)}, forwardBufferLength=${this.forwardBufferLength.toFixed(3)}: adjusting playback rate from ${e.playbackRate} to ${t}`),e.playbackRate=t);}estimateLiveEdge(){let e=this.levelDetails;return e===null?null:e.edge+e.age}computeLatency(){let e=this.estimateLiveEdge();return e===null?null:e-this.currentTime}},Ru=class extends In{constructor(e,t){super(e,"level-controller"),this._levels=[],this._firstLevel=-1,this._maxAutoLevel=-1,this._startLevel=void 0,this.currentLevel=null,this.currentLevelIndex=-1,this.manualLevelIndex=-1,this.steering=void 0,this.onParsedComplete=void 0,this.steering=t,this._registerListeners();}_registerListeners(){let{hls:e}=this;e.on(g.MANIFEST_LOADING,this.onManifestLoading,this),e.on(g.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(g.LEVEL_LOADED,this.onLevelLoaded,this),e.on(g.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(g.FRAG_BUFFERED,this.onFragBuffered,this),e.on(g.ERROR,this.onError,this);}_unregisterListeners(){let{hls:e}=this;e.off(g.MANIFEST_LOADING,this.onManifestLoading,this),e.off(g.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(g.LEVEL_LOADED,this.onLevelLoaded,this),e.off(g.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(g.FRAG_BUFFERED,this.onFragBuffered,this),e.off(g.ERROR,this.onError,this);}destroy(){this._unregisterListeners(),this.steering=null,this.resetLevels(),super.destroy();}stopLoad(){this._levels.forEach(t=>{t.loadError=0,t.fragmentError=0;}),super.stopLoad();}resetLevels(){this._startLevel=void 0,this.manualLevelIndex=-1,this.currentLevelIndex=-1,this.currentLevel=null,this._levels=[],this._maxAutoLevel=-1;}onManifestLoading(e,t){this.resetLevels();}onManifestLoaded(e,t){let i=this.hls.config.preferManagedMediaSource,r=[],n={},a={},o=false,l=false,d=false;t.levels.forEach(c=>{let u=c.attrs,{audioCodec:h,videoCodec:f}=c;h&&(c.audioCodec=h=Ho(h,i)||void 0),f&&(f=c.videoCodec=yT(f));let{width:m,height:p,unknownCodecs:E}=c,v=E?.length||0;if(o||(o=!!(m&&p)),l||(l=!!f),d||(d=!!h),v||h&&!this.isAudioSupported(h)||f&&!this.isVideoSupported(f)){this.log(`Some or all CODECS not supported "${u.CODECS}"`);return}let{CODECS:T,"FRAME-RATE":S,"HDCP-LEVEL":A,"PATHWAY-ID":b,RESOLUTION:D,"VIDEO-RANGE":I}=u,R=`${`${b||"."}-`}${c.bitrate}-${D}-${S}-${T}-${I}-${A}`;if(n[R])if(n[R].uri!==c.url&&!c.attrs["PATHWAY-ID"]){let L=a[R]+=1;c.attrs["PATHWAY-ID"]=new Array(L+1).join(".");let M=this.createLevel(c);n[R]=M,r.push(M);}else n[R].addGroupId("audio",u.AUDIO),n[R].addGroupId("text",u.SUBTITLES);else {let L=this.createLevel(c);n[R]=L,a[R]=1,r.push(L);}}),this.filterAndSortMediaOptions(r,t,o,l,d);}createLevel(e){let t=new ds(e),i=e.supplemental;if(i!=null&&i.videoCodec&&!this.isVideoSupported(i.videoCodec)){let r=new Error(`SUPPLEMENTAL-CODECS not supported "${i.videoCodec}"`);this.log(r.message),t.supportedResult=Fg(r,[]);}return t}isAudioSupported(e){return gn(e,"audio",this.hls.config.preferManagedMediaSource)}isVideoSupported(e){return gn(e,"video",this.hls.config.preferManagedMediaSource)}filterAndSortMediaOptions(e,t,i,r,n){var a;let o=[],l=[],d=e,c=((a=t.stats)==null?void 0:a.parsing)||{};if((i||r)&&n&&(d=d.filter(({videoCodec:T,videoRange:S,width:A,height:b})=>(!!T||!!(A&&b))&&DT(S))),d.length===0){Promise.resolve().then(()=>{if(this.hls){let T="no level with compatible codecs found in manifest",S=T;t.levels.length&&(S=`one or more CODECS in variant not supported: ${Ae(t.levels.map(b=>b.attrs.CODECS).filter((b,D,I)=>I.indexOf(b)===D))}`,this.warn(S),T+=` (${S})`);let A=new Error(T);this.hls.trigger(g.ERROR,{type:z.MEDIA_ERROR,details:x.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:true,url:t.url,error:A,reason:S});}}),c.end=performance.now();return}t.audioTracks&&(o=t.audioTracks.filter(T=>!T.audioCodec||this.isAudioSupported(T.audioCodec)),Ag(o)),t.subtitles&&(l=t.subtitles,Ag(l));let u=d.slice(0);d.sort((T,S)=>{if(T.attrs["HDCP-LEVEL"]!==S.attrs["HDCP-LEVEL"])return (T.attrs["HDCP-LEVEL"]||"")>(S.attrs["HDCP-LEVEL"]||"")?1:-1;if(i&&T.height!==S.height)return T.height-S.height;if(T.frameRate!==S.frameRate)return T.frameRate-S.frameRate;if(T.videoRange!==S.videoRange)return Ko.indexOf(T.videoRange)-Ko.indexOf(S.videoRange);if(T.videoCodec!==S.videoCodec){let A=vm(T.videoCodec),b=vm(S.videoCodec);if(A!==b)return b-A}if(T.uri===S.uri&&T.codecSet!==S.codecSet){let A=Go(T.codecSet),b=Go(S.codecSet);if(A!==b)return b-A}return T.averageBitrate!==S.averageBitrate?T.averageBitrate-S.averageBitrate:0});let h=u[0];if(this.steering&&(d=this.steering.filterParsedLevels(d),d.length!==u.length)){for(let T=0;T<u.length;T++)if(u[T].pathwayId===d[0].pathwayId){h=u[T];break}}this._levels=d;for(let T=0;T<d.length;T++)if(d[T]===h){var f;this._firstLevel=T;let S=h.bitrate,A=this.hls.bandwidthEstimate;if(this.log(`manifest loaded, ${d.length} level(s) found, first bitrate: ${S}`),((f=this.hls.userConfig)==null?void 0:f.abrEwmaDefaultEstimate)===void 0){let b=Math.min(S,this.hls.config.abrEwmaDefaultEstimateMax);b>A&&A===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=b);}break}let m=n&&!r,p=this.hls.config,E=!!(p.audioStreamController&&p.audioTrackController),v={levels:d,audioTracks:o,subtitleTracks:l,sessionData:t.sessionData,sessionKeys:t.sessionKeys,firstLevel:this._firstLevel,stats:t.stats,audio:n,video:r,altAudio:E&&!m&&o.some(T=>!!T.url)};c.end=performance.now(),this.hls.trigger(g.MANIFEST_PARSED,v);}get levels(){return this._levels.length===0?null:this._levels}get loadLevelObj(){return this.currentLevel}get level(){return this.currentLevelIndex}set level(e){let t=this._levels;if(t.length===0)return;if(e<0||e>=t.length){let c=new Error("invalid level idx"),u=e<0;if(this.hls.trigger(g.ERROR,{type:z.OTHER_ERROR,details:x.LEVEL_SWITCH_ERROR,level:e,fatal:u,error:c,reason:c.message}),u)return;e=Math.min(e,t.length-1);}let 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&&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:""}`);let l={level:e,attrs:a.attrs,details:a.details,bitrate:a.bitrate,averageBitrate:a.averageBitrate,maxBitrate:a.maxBitrate,realBitrate:a.realBitrate,width:a.width,height:a.height,codecSet:a.codecSet,audioCodec:a.audioCodec,videoCodec:a.videoCodec,audioGroups:a.audioGroups,subtitleGroups:a.subtitleGroups,loaded:a.loaded,loadError:a.loadError,fragmentError:a.fragmentError,name:a.name,id:a.id,uri:a.uri,url:a.url,urlId:0,audioGroupIds:a.audioGroupIds,textGroupIds:a.textGroupIds};this.hls.trigger(g.LEVEL_SWITCHING,l);let d=a.details;if(!d||d.live){let c=this.switchParams(a.uri,r?.details,d);this.loadPlaylist(c);}}get manualLevel(){return this.manualLevelIndex}set manualLevel(e){this.manualLevelIndex=e,this._startLevel===void 0&&(this._startLevel=e),e!==-1&&(this.level=e);}get firstLevel(){return this._firstLevel}set firstLevel(e){this._firstLevel=e;}get startLevel(){if(this._startLevel===void 0){let e=this.hls.config.startLevel;return e!==void 0?e:this.hls.firstAutoLevel}return this._startLevel}set startLevel(e){this._startLevel=e;}get pathways(){return this.steering?this.steering.pathways():[]}get pathwayPriority(){return this.steering?this.steering.pathwayPriority:null}set pathwayPriority(e){if(this.steering){let t=this.steering.pathways(),i=e.filter(r=>t.indexOf(r)!==-1);if(e.length<1){this.warn(`pathwayPriority ${e} should contain at least one pathway from list: ${t}`);return}this.steering.pathwayPriority=i;}}onError(e,t){t.fatal||!t.context||t.context.type===ce.LEVEL&&t.context.level===this.level&&this.checkRetry(t);}onFragBuffered(e,{frag:t}){if(t!==void 0&&t.type===W.MAIN){let i=t.elementaryStreams;if(!Object.keys(i).some(n=>!!i[n]))return;let r=this._levels[t.level];r!=null&&r.loadError&&(this.log(`Resetting level error count of ${r.loadError} on frag buffered`),r.loadError=0);}}onLevelLoaded(e,t){var i;let{level:r,details:n}=t,a=t.levelInfo;if(!a){var o;this.warn(`Invalid level index ${r}`),(o=t.deliveryDirectives)!=null&&o.skip&&(n.deltaUpdateFailed=true);return}if(a===this.currentLevel||t.withoutMultiVariant){a.fragmentError===0&&(a.loadError=0);let l=a.details;l===t.details&&l.advanced&&(l=void 0),this.playlistLoaded(r,t,l);}else (i=t.deliveryDirectives)!=null&&i.skip&&(n.deltaUpdateFailed=true);}loadPlaylist(e){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentLevel)&&this.scheduleLoading(this.currentLevel,e);}loadingPlaylist(e,t){super.loadingPlaylist(e,t);let i=this.getUrlWithDirectives(e.uri,t),r=this.currentLevelIndex,n=e.attrs["PATHWAY-ID"],a=e.details,o=a?.age;this.log(`Loading level index ${r}${t?.msn!==void 0?" at sn "+t.msn+" part "+t.part:""}${n?" Pathway "+n:""}${o&&a.live?" age "+o.toFixed(1)+(a.type&&" "+a.type||""):""} ${i}`),this.hls.trigger(g.LEVEL_LOADING,{url:i,level:r,levelInfo:e,pathwayId:e.attrs["PATHWAY-ID"],id:0,deliveryDirectives:t||null});}get nextLoadLevel(){return this.manualLevelIndex!==-1?this.manualLevelIndex:this.hls.nextAutoLevel}set nextLoadLevel(e){this.level=e,this.manualLevelIndex===-1&&(this.hls.nextAutoLevel=e);}removeLevel(e){var t;if(this._levels.length===1)return;let i=this._levels.filter((n,a)=>a!==e?true:(this.steering&&this.steering.removeLevel(n),n===this.currentLevel&&(this.currentLevel=null,this.currentLevelIndex=-1,n.details&&n.details.fragments.forEach(o=>o.level=-1)),false));tp(i),this._levels=i,this.currentLevelIndex>-1&&(t=this.currentLevel)!=null&&t.details&&(this.currentLevelIndex=this.currentLevel.details.fragments[0].level),this.manualLevelIndex>-1&&(this.manualLevelIndex=this.currentLevelIndex);let r=i.length-1;this._firstLevel=Math.min(this._firstLevel,r),this._startLevel&&(this._startLevel=Math.min(this._startLevel,r)),this.hls.trigger(g.LEVELS_UPDATED,{levels:i});}onLevelsUpdated(e,{levels:t}){this._levels=t;}checkMaxAutoUpdated(){let{autoLevelCapping:e,maxAutoLevel:t,maxHdcpLevel:i}=this.hls;this._maxAutoLevel!==t&&(this._maxAutoLevel=t,this.hls.trigger(g.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:e,levels:this.levels,maxAutoLevel:t,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:i}));}};function Ag(s){let e={};s.forEach(t=>{let i=t.groupId||"";t.id=e[i]=e[i]||0,e[i]++;});}function Vp(){return self.SourceBuffer||self.WebKitSourceBuffer}function Wp(){if(!Fi())return false;let e=Vp();return !e||e.prototype&&typeof e.prototype.appendBuffer=="function"&&typeof e.prototype.remove=="function"}function YA(){if(!Wp())return false;let s=Fi();return typeof s?.isTypeSupported=="function"&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some(e=>s.isTypeSupported(pn(e,"video")))||["mp4a.40.2","fLaC"].some(e=>s.isTypeSupported(pn(e,"audio"))))}function qA(){var s;let e=Vp();return typeof(e==null||(s=e.prototype)==null?void 0:s.changeType)=="function"}var jA=100,ku=class extends yn{constructor(e,t,i){super(e,t,i,"stream-controller",W.MAIN),this.audioCodecSwap=false,this.level=-1,this._forceStartLoad=false,this._hasEnoughToStart=false,this.altAudio=0,this.audioOnly=false,this.fragPlaying=null,this.fragLastKbps=0,this.couldBacktrack=false,this.backtrackFragment=null,this.audioCodecSwitch=false,this.videoBuffer=null,this.onMediaPlaying=()=>{this.tick();},this.onMediaSeeked=()=>{let r=this.media,n=r?r.currentTime:null;if(n===null||!G(n)||(this.log(`Media seeked to ${n.toFixed(3)}`),!this.getBufferedFrag(n)))return;let a=this.getFwdBufferInfoAtPos(r,n,W.MAIN,0);if(a===null||a.len===0){this.warn(`Main forward buffer length at ${n} on "seeked" event ${a?a.len:"empty"})`);return}this.tick();},this.registerListeners();}registerListeners(){super.registerListeners();let{hls:e}=this;e.on(g.MANIFEST_PARSED,this.onManifestParsed,this),e.on(g.LEVEL_LOADING,this.onLevelLoading,this),e.on(g.LEVEL_LOADED,this.onLevelLoaded,this),e.on(g.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.on(g.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(g.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.on(g.BUFFER_CREATED,this.onBufferCreated,this),e.on(g.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(g.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(g.FRAG_BUFFERED,this.onFragBuffered,this);}unregisterListeners(){super.unregisterListeners();let{hls:e}=this;e.off(g.MANIFEST_PARSED,this.onManifestParsed,this),e.off(g.LEVEL_LOADED,this.onLevelLoaded,this),e.off(g.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.off(g.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(g.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.off(g.BUFFER_CREATED,this.onBufferCreated,this),e.off(g.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(g.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(g.FRAG_BUFFERED,this.onFragBuffered,this);}onHandlerDestroying(){this.onMediaPlaying=this.onMediaSeeked=null,this.unregisterListeners(),super.onHandlerDestroying();}startLoad(e,t){if(this.levels){let{lastCurrentTime:i,hls:r}=this;if(this.stopLoad(),this.setInterval(jA),this.level=-1,!this.startFragRequested){let n=r.startLevel;n===-1&&(r.config.testBandwidth&&this.levels.length>1?(n=0,this.bitrateTest=true):n=r.firstAutoLevel),r.nextLoadLevel=n,this.level=r.loadLevel,this._hasEnoughToStart=!!t;}i>0&&e===-1&&!t&&(this.log(`Override startPosition with lastCurrentTime @${i.toFixed(3)}`),e=i),this.state=C.IDLE,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick();}else this._forceStartLoad=true,this.state=C.STOPPED;}stopLoad(){this._forceStartLoad=false,super.stopLoad();}doTick(){switch(this.state){case C.WAITING_LEVEL:{let{levels:e,level:t}=this,i=e?.[t],r=i?.details;if(r&&(!r.live||this.levelLastLoaded===i&&!this.waitForLive(i))){if(this.waitForCdnTuneIn(r))break;this.state=C.IDLE;break}else if(this.hls.nextLoadLevel!==this.level){this.state=C.IDLE;break}break}case C.FRAG_LOADING_WAITING_RETRY:this.checkRetryDate();break}this.state===C.IDLE&&this.doTickIdle(),this.onTickEnd();}onTickEnd(){var e;super.onTickEnd(),(e=this.media)!=null&&e.readyState&&this.media.seeking===false&&(this.lastCurrentTime=this.media.currentTime),this.checkFragmentChanged();}doTickIdle(){let{hls:e,levelLastLoaded:t,levels:i,media:r}=this;if(t===null||!r&&!this.primaryPrefetch&&(this.startFragRequested||!e.config.startFragPrefetch)||this.altAudio&&this.audioOnly)return;let n=this.buffering?e.nextLoadLevel:e.loadLevel;if(!(i!=null&&i[n]))return;let a=i[n],o=this.getMainFwdBufferInfo();if(o===null)return;let l=this.getLevelDetails();if(l&&this._streamEnded(o,l)){let p={};this.altAudio===2&&(p.type="video"),this.hls.trigger(g.BUFFER_EOS,p),this.state=C.ENDED;return}if(!this.buffering)return;e.loadLevel!==n&&e.manualLevel===-1&&this.log(`Adapting to level ${n} from level ${this.level}`),this.level=e.nextLoadLevel=n;let d=a.details;if(!d||this.state===C.WAITING_LEVEL||this.waitForLive(a)){this.level=n,this.state=C.WAITING_LEVEL,this.startFragRequested=false;return}let c=o.len,u=this.getMaxBufferLength(a.maxBitrate);if(c>=u)return;this.backtrackFragment&&this.backtrackFragment.start>o.end&&(this.backtrackFragment=null);let h=this.backtrackFragment?this.backtrackFragment.start:o.end,f=this.getNextFragment(h,d);if(this.couldBacktrack&&!this.fragPrevious&&f&&Ue(f)&&this.fragmentTracker.getState(f)!==Ke.OK){var m;let E=((m=this.backtrackFragment)!=null?m:f).sn-d.startSN,v=d.fragments[E-1];v&&f.cc===v.cc&&(f=v,this.fragmentTracker.removeFragment(v));}else this.backtrackFragment&&o.len&&(this.backtrackFragment=null);if(f&&this.isLoopLoading(f,h)){if(!f.gap){let E=this.audioOnly&&!this.altAudio?Se.AUDIO:Se.VIDEO,v=(E===Se.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;v&&this.afterBufferFlushed(v,E,W.MAIN);}f=this.getNextFragmentLoopLoading(f,d,o,W.MAIN,u);}f&&(f.initSegment&&!f.initSegment.data&&!this.bitrateTest&&(f=f.initSegment),this.loadFragment(f,a,h));}loadFragment(e,t,i){let r=this.fragmentTracker.getState(e);r===Ke.NOT_LOADED||r===Ke.PARTIAL?Ue(e)?this.bitrateTest?(this.log(`Fragment ${e.sn} of level ${e.level} is being downloaded to test bitrate and will not be buffered`),this._loadBitrateTestFrag(e,t)):super.loadFragment(e,t,i):this._loadInitSegment(e,t):this.clearTrackerIfNeeded(e);}getBufferedFrag(e){return this.fragmentTracker.getBufferedFrag(e,W.MAIN)}followingBufferedFrag(e){return e?this.getBufferedFrag(e.end+.5):null}immediateLevelSwitch(){this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY);}nextLevelSwitch(){let{levels:e,media:t}=this;if(t!=null&&t.readyState){let i,r=this.getAppendedFrag(t.currentTime);r&&r.start>1&&this.flushMainBuffer(0,r.start-1);let n=this.getLevelDetails();if(n!=null&&n.live){let o=this.getMainFwdBufferInfo();if(!o||o.len<n.targetduration*2)return}if(!t.paused&&e){let o=this.hls.nextLoadLevel,l=e[o],d=this.fragLastKbps;d&&this.fragCurrent?i=this.fragCurrent.duration*l.maxBitrate/(1e3*d)+1:i=0;}else i=0;let a=this.getBufferedFrag(t.currentTime+i);if(a){let o=this.followingBufferedFrag(a);if(o){this.abortCurrentFrag();let l=o.maxStartPTS?o.maxStartPTS:o.start,d=o.duration,c=Math.max(a.end,l+Math.min(Math.max(d-this.config.maxFragLookUpTolerance,d*(this.couldBacktrack?.5:.125)),d*(this.couldBacktrack?.75:.25)));this.flushMainBuffer(c,Number.POSITIVE_INFINITY);}}}}abortCurrentFrag(){let e=this.fragCurrent;switch(this.fragCurrent=null,this.backtrackFragment=null,e&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.state){case C.KEY_LOADING:case C.FRAG_LOADING:case C.FRAG_LOADING_WAITING_RETRY:case C.PARSING:case C.PARSED:this.state=C.IDLE;break}this.nextLoadPosition=this.getLoadPosition();}flushMainBuffer(e,t){super.flushMainBuffer(e,t,this.altAudio===2?"video":null);}onMediaAttached(e,t){super.onMediaAttached(e,t);let i=t.media;nt(i,"playing",this.onMediaPlaying),nt(i,"seeked",this.onMediaSeeked);}onMediaDetaching(e,t){let{media:i}=this;i&&(ut(i,"playing",this.onMediaPlaying),ut(i,"seeked",this.onMediaSeeked)),this.videoBuffer=null,this.fragPlaying=null,super.onMediaDetaching(e,t),!t.transferMedia&&(this._hasEnoughToStart=false);}onManifestLoading(){super.onManifestLoading(),this.log("Trigger BUFFER_RESET"),this.hls.trigger(g.BUFFER_RESET,void 0),this.couldBacktrack=false,this.fragLastKbps=0,this.fragPlaying=this.backtrackFragment=null,this.altAudio=0,this.audioOnly=false;}onManifestParsed(e,t){let i=false,r=false;for(let n=0;n<t.levels.length;n++){let a=t.levels[n].audioCodec;a&&(i=i||a.indexOf("mp4a.40.2")!==-1,r=r||a.indexOf("mp4a.40.5")!==-1);}this.audioCodecSwitch=i&&r&&!qA(),this.audioCodecSwitch&&this.log("Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC"),this.levels=t.levels,this.startFragRequested=false;}onLevelLoading(e,t){let{levels:i}=this;if(!i||this.state!==C.IDLE)return;let r=t.levelInfo;(!r.details||r.details.live&&(this.levelLastLoaded!==r||r.details.expired)||this.waitForCdnTuneIn(r.details))&&(this.state=C.WAITING_LEVEL);}onLevelLoaded(e,t){var i;let{levels:r,startFragRequested:n}=this,a=t.level,o=t.details,l=o.totalduration;if(!r){this.warn(`Levels were reset while loading level ${a}`);return}this.log(`Level ${a} loaded [${o.startSN},${o.endSN}]${o.lastPartSn?`[part-${o.lastPartSn}-${o.lastPartIndex}]`:""}, cc [${o.startCC}, ${o.endCC}] duration:${l}`);let d=t.levelInfo,c=this.fragCurrent;c&&(this.state===C.FRAG_LOADING||this.state===C.FRAG_LOADING_WAITING_RETRY)&&c.level!==t.level&&c.loader&&this.abortCurrentFrag();let u=0;if(o.live||(i=d.details)!=null&&i.live){var h;if(this.checkLiveUpdate(o),o.deltaUpdateFailed)return;u=this.alignPlaylists(o,d.details,(h=this.levelLastLoaded)==null?void 0:h.details);}if(d.details=o,this.levelLastLoaded=d,n||this.setStartPosition(o,u),this.hls.trigger(g.LEVEL_UPDATED,{details:o,level:a}),this.state===C.WAITING_LEVEL){if(this.waitForCdnTuneIn(o))return;this.state=C.IDLE;}n&&o.live&&this.synchronizeToLiveEdge(o),this.tick();}synchronizeToLiveEdge(e){let{config:t,media:i}=this;if(!i)return;let r=this.hls.liveSyncPosition,n=this.getLoadPosition(),a=e.fragmentStart,o=e.edge,l=n>=a-t.maxFragLookUpTolerance&&n<=o;if(r!==null&&i.duration>r&&(n<r||!l)){let c=t.liveMaxLatencyDuration!==void 0?t.liveMaxLatencyDuration:t.liveMaxLatencyDurationCount*e.targetduration;if((!l&&i.readyState<4||n<o-c)&&(this._hasEnoughToStart||(this.nextLoadPosition=r),i.readyState))if(this.warn(`Playback: ${n.toFixed(3)} is located too far from the end of live sliding playlist: ${o}, reset currentTime to : ${r.toFixed(3)}`),this.config.liveSyncMode==="buffered"){var d;let u=re.bufferInfo(i,r,0);if(!((d=u.buffered)!=null&&d.length)){i.currentTime=r;return}if(u.start<=n){i.currentTime=r;return}let{nextStart:f}=re.bufferedInfo(u.buffered,n,0);f&&(i.currentTime=f);}else i.currentTime=r;}}_handleFragmentLoadProgress(e){var t;let i=e.frag,{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}let o=a[i.level];if(!o){this.warn(`Level ${i.level} not found on progress`);return}let l=o.details;if(!l){this.warn(`Dropping fragment ${i.sn} of level ${i.level} after level details were reset`),this.fragmentTracker.removeFragment(i);return}let d=o.videoCodec,c=l.PTSKnown||!l.live,u=(t=i.initSegment)==null?void 0:t.data,h=this._getAudioCodec(o),f=this.transmuxer=this.transmuxer||new sl(this.hls,W.MAIN,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),m=r?r.index:-1,p=m!==-1,E=new vn(i.level,i.sn,i.stats.chunkCount,n.byteLength,m,p),v=this.initPTS[i.cc];f.push(n,u,h,d,i,r,l.totalduration,c,E,v);}onAudioTrackSwitching(e,t){let i=this.hls,r=this.altAudio===2;if(Wo(t.url,i))this.altAudio=1;else {if(this.mediaBuffer!==this.media){this.log("Switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;let a=this.fragCurrent;a&&(this.log("Switching to main audio track, cancel main fragment load"),a.abortRequests(),this.fragmentTracker.removeFragment(a)),this.resetTransmuxer(),this.resetLoadingState();}else this.audioOnly&&this.resetTransmuxer();if(r){this.fragmentTracker.removeAllFragments(),i.once(g.BUFFER_FLUSHED,()=>{this.hls&&this.hls.trigger(g.AUDIO_TRACK_SWITCHED,t);}),i.trigger(g.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null});return}i.trigger(g.AUDIO_TRACK_SWITCHED,t);}}onAudioTrackSwitched(e,t){let i=Wo(t.url,this.hls);if(i){let r=this.videoBuffer;r&&this.mediaBuffer!==r&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=r);}this.altAudio=i?2:0,this.tick();}onBufferCreated(e,t){let i=t.tracks,r,n,a=false;for(let o in i){let l=i[o];if(l.id==="main"){if(n=o,r=l,o==="video"){let d=i[o];d&&(this.videoBuffer=d.buffer);}}else a=true;}a&&r?(this.log(`Alternate track found, use ${n}.buffered to schedule main fragment loading`),this.mediaBuffer=r.buffer):this.mediaBuffer=this.media;}onFragBuffered(e,t){let{frag:i,part:r}=t,n=i.type===W.MAIN;if(n){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===C.PARSED&&(this.state=C.IDLE);return}let o=r?r.stats:i.stats;this.fragLastKbps=Math.round(8*o.total/(o.buffering.end-o.loading.first)),Ue(i)&&(this.fragPrevious=i),this.fragBufferedComplete(i,r);}let a=this.media;a&&(!this._hasEnoughToStart&&re.getBuffered(a).length&&(this._hasEnoughToStart=true,this.seekToStartPos()),n&&this.tick());}get hasEnoughToStart(){return this._hasEnoughToStart}onError(e,t){var i;if(t.fatal){this.state=C.ERROR;return}switch(t.details){case x.FRAG_GAP:case x.FRAG_PARSING_ERROR:case x.FRAG_DECRYPT_ERROR:case x.FRAG_LOAD_ERROR:case x.FRAG_LOAD_TIMEOUT:case x.KEY_LOAD_ERROR:case x.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(W.MAIN,t);break;case x.LEVEL_LOAD_ERROR:case x.LEVEL_LOAD_TIMEOUT:case x.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===C.WAITING_LEVEL&&((i=t.context)==null?void 0:i.type)===ce.LEVEL&&(this.state=C.IDLE);break;case x.BUFFER_ADD_CODEC_ERROR:case x.BUFFER_APPEND_ERROR:if(t.parent!=="main")return;this.reduceLengthAndFlushBuffer(t)&&this.resetLoadingState();break;case x.BUFFER_FULL_ERROR:if(t.parent!=="main")return;this.reduceLengthAndFlushBuffer(t)&&(!this.config.interstitialsController&&this.config.assetPlayerId?this._hasEnoughToStart=true:this.flushMainBuffer(0,Number.POSITIVE_INFINITY));break;case x.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}onFragLoadEmergencyAborted(){this.state=C.IDLE,this._hasEnoughToStart||(this.startFragRequested=false,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate();}onBufferFlushed(e,{type:t}){if(t!==Se.AUDIO||!this.altAudio){let i=(t===Se.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;i&&(this.afterBufferFlushed(i,t,W.MAIN),this.tick());}}onLevelsUpdated(e,t){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level,this.level===-1&&this.resetWhenMissingContext(this.fragCurrent)),this.levels=t.levels;}swapAudioCodec(){this.audioCodecSwap=!this.audioCodecSwap;}seekToStartPos(){let{media:e}=this;if(!e)return;let t=e.currentTime,i=this.startPosition;if(i>=0&&t<i){if(e.seeking){this.log(`could not seek to ${i}, already seeking at ${t}`);return}let r=this.timelineOffset;r&&i&&(i+=r);let n=this.getLevelDetails(),a=re.getBuffered(e),o=a.length?a.start(0):0,l=o-i,d=Math.max(this.config.maxBufferHole,this.config.maxFragLookUpTolerance);(this.config.startOnSegmentBoundary||l>0&&(l<d||this.loadingParts&&l<2*(n?.partTarget||0)))&&(this.log(`adjusting start position by ${l} to match buffer start`),i+=l,this.startPosition=i),t<i&&(this.log(`seek to target start position ${i} from current time ${t} buffer start ${o}`),e.currentTime=i);}}_getAudioCodec(e){let t=this.config.defaultAudioCodec||e.audioCodec;return this.audioCodecSwap&&t&&(this.log("Swapping audio codec"),t.indexOf("mp4a.40.5")!==-1?t="mp4a.40.2":t="mp4a.40.5"),t}_loadBitrateTestFrag(e,t){e.bitrateTest=true,this._doFragLoad(e,t).then(i=>{let{hls:r}=this,n=i?.frag;if(!n||this.fragContextChanged(n))return;t.fragmentError=0,this.state=C.IDLE,this.startFragRequested=false,this.bitrateTest=false;let a=n.stats;a.parsing.start=a.parsing.end=a.buffering.start=a.buffering.end=self.performance.now(),r.trigger(g.FRAG_LOADED,i),n.bitrateTest=false;}).catch(i=>{this.state===C.STOPPED||this.state===C.ERROR||(this.warn(i),this.resetFragmentLoading(e));});}_handleTransmuxComplete(e){let t=this.playlistType,{hls:i}=this,{remuxResult:r,chunkMeta:n}=e,a=this.getCurrentContext(n);if(!a){this.resetWhenMissingContext(n);return}let{frag:o,part:l,level:d}=a,{video:c,text:u,id3:h,initSegment:f}=r,{details:m}=d,p=this.altAudio?void 0:r.audio;if(this.fragContextChanged(o)){this.fragmentTracker.removeFragment(o);return}if(this.state=C.PARSING,f){let E=f.tracks;if(E){let A=o.initSegment||o;if(this.unhandledEncryptionError(f,o))return;this._bufferInitSegment(d,E,A,n),i.trigger(g.FRAG_PARSING_INIT_SEGMENT,{frag:A,id:t,tracks:E});}let v=f.initPTS,T=f.timescale,S=this.initPTS[o.cc];if(G(v)&&(!S||S.baseTime!==v||S.timescale!==T)){let A=f.trackId;this.initPTS[o.cc]={baseTime:v,timescale:T,trackId:A},i.trigger(g.INIT_PTS_FOUND,{frag:o,id:t,initPTS:v,timescale:T,trackId:A});}}if(c&&m){p&&c.type==="audiovideo"&&this.logMuxedErr(o);let E=m.fragments[o.sn-1-m.startSN],v=o.sn===m.startSN,T=!E||o.cc>E.cc;if(r.independent!==false){let{startPTS:S,endPTS:A,startDTS:b,endDTS:D}=c;if(l)l.elementaryStreams[c.type]={startPTS:S,endPTS:A,startDTS:b,endDTS:D};else if(c.firstKeyFrame&&c.independent&&n.id===1&&!T&&(this.couldBacktrack=true),c.dropped&&c.independent){let I=this.getMainFwdBufferInfo(),k=(I?I.end:this.getLoadPosition())+this.config.maxBufferHole,R=c.firstKeyFramePTS?c.firstKeyFramePTS:S;if(!v&&k<R-this.config.maxBufferHole&&!T){this.backtrack(o);return}else T&&(o.gap=true);o.setElementaryStreamInfo(c.type,o.start,A,o.start,D,true);}else v&&S-(m.appliedTimelineOffset||0)>Bo&&(o.gap=true);o.setElementaryStreamInfo(c.type,S,A,b,D),this.backtrackFragment&&(this.backtrackFragment=o),this.bufferFragmentData(c,o,l,n,v||T);}else if(v||T)o.gap=true;else {this.backtrack(o);return}}if(p){let{startPTS:E,endPTS:v,startDTS:T,endDTS:S}=p;l&&(l.elementaryStreams[Se.AUDIO]={startPTS:E,endPTS:v,startDTS:T,endDTS:S}),o.setElementaryStreamInfo(Se.AUDIO,E,v,T,S),this.bufferFragmentData(p,o,l,n);}if(m&&h!=null&&h.samples.length){let E={id:t,frag:o,details:m,samples:h.samples};i.trigger(g.FRAG_PARSING_METADATA,E);}if(m&&u){let E={id:t,frag:o,details:m,samples:u.samples};i.trigger(g.FRAG_PARSING_USERDATA,E);}}logMuxedErr(e){this.warn(`${Ue(e)?"Media":"Init"} segment with muxed audiovideo where only video expected: ${e.url}`);}_bufferInitSegment(e,t,i,r){if(this.state!==C.PARSING)return;this.audioOnly=!!t.audio&&!t.video,this.altAudio&&!this.audioOnly&&(delete t.audio,t.audiovideo&&this.logMuxedErr(i));let{audio:n,video:a,audiovideo:o}=t;if(n){let d=e.audioCodec,c=Po(n.codec,d);c==="mp4a"&&(c="mp4a.40.5");let u=navigator.userAgent.toLowerCase();if(this.audioCodecSwitch){c&&(c.indexOf("mp4a.40.5")!==-1?c="mp4a.40.2":c="mp4a.40.5");let h=n.metadata;h&&"channelCount"in h&&(h.channelCount||1)!==1&&u.indexOf("firefox")===-1&&(c="mp4a.40.5");}c&&c.indexOf("mp4a.40.5")!==-1&&u.indexOf("android")!==-1&&n.container!=="audio/mpeg"&&(c="mp4a.40.2",this.log(`Android: force audio codec to ${c}`)),d&&d!==c&&this.log(`Swapping manifest audio codec "${d}" for "${c}"`),n.levelCodec=c,n.id=W.MAIN,this.log(`Init audio buffer, container:${n.container}, codecs[selected/level/parsed]=[${c||""}/${d||""}/${n.codec}]`),delete t.audiovideo;}if(a){a.levelCodec=e.videoCodec,a.id=W.MAIN;let d=a.codec;if(d?.length===4)switch(d){case "hvc1":case "hev1":a.codec="hvc1.1.6.L120.90";break;case "av01":a.codec="av01.0.04M.08";break;case "avc1":a.codec="avc1.42e01e";break}this.log(`Init video buffer, container:${a.container}, codecs[level/parsed]=[${e.videoCodec||""}/${d}]${a.codec!==d?" parsed-corrected="+a.codec:""}${a.supplemental?" supplemental="+a.supplemental:""}`),delete t.audiovideo;}o&&(this.log(`Init audiovideo buffer, container:${o.container}, codecs[level/parsed]=[${e.codecs}/${o.codec}]`),delete t.video,delete t.audio);let l=Object.keys(t);if(l.length){if(this.hls.trigger(g.BUFFER_CODECS,t),!this.hls)return;l.forEach(d=>{let u=t[d].initSegment;u!=null&&u.byteLength&&this.hls.trigger(g.BUFFER_APPENDING,{type:d,data:u,frag:i,part:null,chunkMeta:r,parent:i.type});});}this.tickImmediate();}getMainFwdBufferInfo(){let e=this.mediaBuffer&&this.altAudio===2?this.mediaBuffer:this.media;return this.getFwdBufferInfo(e,W.MAIN)}get maxBufferLength(){let{levels:e,level:t}=this,i=e?.[t];return i?this.getMaxBufferLength(i.maxBitrate):this.config.maxBufferLength}backtrack(e){this.couldBacktrack=true,this.backtrackFragment=e,this.resetTransmuxer(),this.flushBufferGap(e),this.fragmentTracker.removeFragment(e),this.fragPrevious=null,this.nextLoadPosition=e.start,this.state=C.IDLE;}checkFragmentChanged(){let e=this.media,t=null;if(e&&e.readyState>1&&e.seeking===false){let i=e.currentTime;if(re.isBuffered(e,i)?t=this.getAppendedFrag(i):re.isBuffered(e,i+.1)&&(t=this.getAppendedFrag(i+.1)),t){this.backtrackFragment=null;let r=this.fragPlaying,n=t.level;(!r||t.sn!==r.sn||r.level!==n)&&(this.fragPlaying=t,this.hls.trigger(g.FRAG_CHANGED,{frag:t}),(!r||r.level!==n)&&this.hls.trigger(g.LEVEL_SWITCHED,{level:n}));}}}get nextLevel(){let e=this.nextBufferedFrag;return e?e.level:-1}get currentFrag(){var e;if(this.fragPlaying)return this.fragPlaying;let t=((e=this.media)==null?void 0:e.currentTime)||this.lastCurrentTime;return G(t)?this.getAppendedFrag(t):null}get currentProgramDateTime(){var e;let t=((e=this.media)==null?void 0:e.currentTime)||this.lastCurrentTime;if(G(t)){let i=this.getLevelDetails(),r=this.currentFrag||(i?cs(null,i.fragments,t):null);if(r){let n=r.programDateTime;if(n!==null){let a=n+(t-r.start)*1e3;return new Date(a)}}}return null}get currentLevel(){let e=this.currentFrag;return e?e.level:-1}get nextBufferedFrag(){let e=this.currentFrag;return e?this.followingBufferedFrag(e):null}get forceStartLoad(){return this._forceStartLoad}},Du=class extends ht{constructor(e,t){super("key-loader",t),this.config=void 0,this.keyIdToKeyInfo={},this.emeController=null,this.config=e;}abort(e){for(let i in this.keyIdToKeyInfo){let r=this.keyIdToKeyInfo[i].loader;if(r){var t;if(e&&e!==((t=r.context)==null?void 0:t.frag.type))return;r.abort();}}}detach(){for(let e in this.keyIdToKeyInfo){let t=this.keyIdToKeyInfo[e];(t.mediaKeySessionContext||t.decryptdata.isCommonEncryption)&&delete this.keyIdToKeyInfo[e];}}destroy(){this.detach();for(let e in this.keyIdToKeyInfo){let t=this.keyIdToKeyInfo[e].loader;t&&t.destroy();}this.keyIdToKeyInfo={};}createKeyLoadError(e,t=x.KEY_LOAD_ERROR,i,r,n){return new Ht({type:z.NETWORK_ERROR,details:t,fatal:false,frag:e,response:n,error:i,networkDetails:r})}loadClear(e,t,i){if(this.emeController&&this.config.emeEnabled&&!this.emeController.getSelectedKeySystemFormats().length){if(t.length)for(let r=0,n=t.length;r<n;r++){let a=t[r];if(e.cc<=a.cc&&(!Ue(e)||!Ue(a)||e.sn<a.sn)||!i&&r==n-1)return this.emeController.selectKeySystemFormat(a).then(o=>{if(!this.emeController)return;a.setKeyFormat(o);let l=Oo(o);if(l)return this.emeController.getKeySystemAccess([l])})}if(this.config.requireKeySystemAccessOnStart){let r=dn(this.config);if(r.length)return this.emeController.getKeySystemAccess(r)}}return null}load(e){return !e.decryptdata&&e.encrypted&&this.emeController&&this.config.emeEnabled?this.emeController.selectKeySystemFormat(e).then(t=>this.loadInternal(e,t)):this.loadInternal(e)}loadInternal(e,t){var i,r;t&&e.setKeyFormat(t);let n=e.decryptdata;if(!n){let d=new Error(t?`Expected frag.decryptdata to be defined after setting format ${t}`:`Missing decryption data on fragment in onKeyLoading (emeEnabled with controller: ${this.emeController&&this.config.emeEnabled})`);return Promise.reject(this.createKeyLoadError(e,x.KEY_LOAD_ERROR,d))}let a=n.uri;if(!a)return Promise.reject(this.createKeyLoadError(e,x.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${a}"`)));let o=uc(n),l=this.keyIdToKeyInfo[o];if((i=l)!=null&&i.decryptdata.key)return n.key=l.decryptdata.key,Promise.resolve({frag:e,keyInfo:l});if(this.emeController&&(r=l)!=null&&r.keyLoadPromise)switch(this.emeController.getKeyStatus(l.decryptdata)){case "usable":case "usable-in-future":return l.keyLoadPromise.then(c=>{let{keyInfo:u}=c;return n.key=u.decryptdata.key,{frag:e,keyInfo:u}})}switch(this.log(`${this.keyIdToKeyInfo[o]?"Rel":"L"}oading${n.keyId?" keyId: "+rt(n.keyId):""} URI: ${n.uri} from ${e.type} ${e.level}`),l=this.keyIdToKeyInfo[o]={decryptdata:n,keyLoadPromise:null,loader:null,mediaKeySessionContext:null},n.method){case "SAMPLE-AES":case "SAMPLE-AES-CENC":case "SAMPLE-AES-CTR":return n.keyFormat==="identity"?this.loadKeyHTTP(l,e):this.loadKeyEME(l,e);case "AES-128":case "AES-256":case "AES-256-CTR":return this.loadKeyHTTP(l,e);default:return Promise.reject(this.createKeyLoadError(e,x.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${n.method}"`)))}}loadKeyEME(e,t){let i={frag:t,keyInfo:e};if(this.emeController&&this.config.emeEnabled){var r;if(!e.decryptdata.keyId&&(r=t.initSegment)!=null&&r.data){let a=lT(t.initSegment.data);if(a.length){let o=a[0];o.some(l=>l!==0)&&(this.log(`Using keyId found in init segment ${rt(o)}`),e.decryptdata.keyId=o,Tn.setKeyIdForUri(e.decryptdata.uri,o));}}let n=this.emeController.loadKey(i);return (e.keyLoadPromise=n.then(a=>(e.mediaKeySessionContext=a,i))).catch(a=>{throw e.keyLoadPromise=null,"data"in a&&(a.data.frag=t),a})}return Promise.resolve(i)}loadKeyHTTP(e,t){let i=this.config,r=i.loader,n=new r(i);return t.keyLoader=e.loader=n,e.keyLoadPromise=new Promise((a,o)=>{let l={keyInfo:e,frag:t,responseType:"arraybuffer",url:e.decryptdata.uri},d=i.keyLoadPolicy.default,c={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},u={onSuccess:(h,f,m,p)=>{let{frag:E,keyInfo:v}=m,T=uc(v.decryptdata);if(!E.decryptdata||v!==this.keyIdToKeyInfo[T])return o(this.createKeyLoadError(E,x.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),p));v.decryptdata.key=E.decryptdata.key=new Uint8Array(h.data),E.keyLoader=null,v.loader=null,a({frag:E,keyInfo:v});},onError:(h,f,m,p)=>{this.resetLoader(f),o(this.createKeyLoadError(t,x.KEY_LOAD_ERROR,new Error(`HTTP Error ${h.code} loading key ${h.text}`),m,ve({url:l.url,data:void 0},h)));},onTimeout:(h,f,m)=>{this.resetLoader(f),o(this.createKeyLoadError(t,x.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),m));},onAbort:(h,f,m)=>{this.resetLoader(f),o(this.createKeyLoadError(t,x.INTERNAL_ABORTED,new Error("key loading aborted"),m));}};n.load(l,c,u);})}resetLoader(e){let{frag:t,keyInfo:i,url:r}=e,n=i.loader;t.keyLoader===n&&(t.keyLoader=null,i.loader=null);let a=uc(i.decryptdata)||r;delete this.keyIdToKeyInfo[a],n&&n.destroy();}};function uc(s){if(s.keyFormat!==Xe.FAIRPLAY){let e=s.keyId;if(e)return rt(e)}return s.uri}function bg(s){let{type:e}=s;switch(e){case ce.AUDIO_TRACK:return W.AUDIO;case ce.SUBTITLE_TRACK:return W.SUBTITLE;default:return W.MAIN}}function hc(s,e){let t=s.url;return (t===void 0||t.indexOf("data:")===0)&&(t=e.url),t}var Cu=class{constructor(e){this.hls=void 0,this.loaders=Object.create(null),this.variableList=null,this.onManifestLoaded=this.checkAutostartLoad,this.hls=e,this.registerListeners();}startLoad(e){}stopLoad(){this.destroyInternalLoaders();}registerListeners(){let{hls:e}=this;e.on(g.MANIFEST_LOADING,this.onManifestLoading,this),e.on(g.LEVEL_LOADING,this.onLevelLoading,this),e.on(g.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.on(g.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.on(g.LEVELS_UPDATED,this.onLevelsUpdated,this);}unregisterListeners(){let{hls:e}=this;e.off(g.MANIFEST_LOADING,this.onManifestLoading,this),e.off(g.LEVEL_LOADING,this.onLevelLoading,this),e.off(g.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.off(g.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.off(g.LEVELS_UPDATED,this.onLevelsUpdated,this);}createInternalLoader(e){let t=this.hls.config,i=t.pLoader,r=t.loader,n=i||r,a=new n(t);return this.loaders[e.type]=a,a}getInternalLoader(e){return this.loaders[e.type]}resetInternalLoader(e){this.loaders[e]&&delete this.loaders[e];}destroyInternalLoaders(){for(let e in this.loaders){let t=this.loaders[e];t&&t.destroy(),this.resetInternalLoader(e);}}destroy(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders();}onManifestLoading(e,t){let{url:i}=t;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:ce.MANIFEST,url:i,deliveryDirectives:null,levelOrTrack:null});}onLevelLoading(e,t){let{id:i,level:r,pathwayId:n,url:a,deliveryDirectives:o,levelInfo:l}=t;this.load({id:i,level:r,pathwayId:n,responseType:"text",type:ce.LEVEL,url:a,deliveryDirectives:o,levelOrTrack:l});}onAudioTrackLoading(e,t){let{id:i,groupId:r,url:n,deliveryDirectives:a,track:o}=t;this.load({id:i,groupId:r,level:null,responseType:"text",type:ce.AUDIO_TRACK,url:n,deliveryDirectives:a,levelOrTrack:o});}onSubtitleTrackLoading(e,t){let{id:i,groupId:r,url:n,deliveryDirectives:a,track:o}=t;this.load({id:i,groupId:r,level:null,responseType:"text",type:ce.SUBTITLE_TRACK,url:n,deliveryDirectives:a,levelOrTrack:o});}onLevelsUpdated(e,t){let i=this.loaders[ce.LEVEL];if(i){let r=i.context;r&&!t.levels.some(n=>n===r.levelOrTrack)&&(i.abort(),delete this.loaders[ce.LEVEL]);}}load(e){var t;let i=this.hls.config,r=this.getInternalLoader(e);if(r){let d=this.hls.logger,c=r.context;if(c&&c.levelOrTrack===e.levelOrTrack&&(c.url===e.url||c.deliveryDirectives&&!e.deliveryDirectives)){c.url===e.url?d.log(`[playlist-loader]: ignore ${e.url} ongoing request`):d.log(`[playlist-loader]: ignore ${e.url} in favor of ${c.url}`);return}d.log(`[playlist-loader]: aborting previous loader for type: ${e.type}`),r.abort();}let n;if(e.type===ce.MANIFEST?n=i.manifestLoadPolicy.default:n=ye({},i.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),r=this.createInternalLoader(e),G((t=e.deliveryDirectives)==null?void 0:t.part)){let d;if(e.type===ce.LEVEL&&e.level!==null?d=this.hls.levels[e.level].details:e.type===ce.AUDIO_TRACK&&e.id!==null?d=this.hls.audioTracks[e.id].details:e.type===ce.SUBTITLE_TRACK&&e.id!==null&&(d=this.hls.subtitleTracks[e.id].details),d){let c=d.partTarget,u=d.targetduration;if(c&&u){let h=Math.max(c*3,u*.8)*1e3;n=ye({},n,{maxTimeToFirstByteMs:Math.min(h,n.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(h,n.maxTimeToFirstByteMs)});}}}let a=n.errorRetry||n.timeoutRetry||{},o={loadPolicy:n,timeout:n.maxLoadTimeMs,maxRetry:a.maxNumRetry||0,retryDelay:a.retryDelayMs||0,maxRetryDelay:a.maxRetryDelayMs||0},l={onSuccess:(d,c,u,h)=>{let f=this.getInternalLoader(u);this.resetInternalLoader(u.type);let m=d.data;c.parsing.start=performance.now(),as.isMediaPlaylist(m)||u.type!==ce.MANIFEST?this.handleTrackOrLevelPlaylist(d,c,u,h||null,f):this.handleMasterPlaylist(d,c,u,h);},onError:(d,c,u,h)=>{this.handleNetworkError(c,u,false,d,h);},onTimeout:(d,c,u)=>{this.handleNetworkError(c,u,true,void 0,d);}};r.load(e,o,l);}checkAutostartLoad(){if(!this.hls)return;let{config:{autoStartLoad:e,startPosition:t},forceStartLoad:i}=this.hls;(e||i)&&(this.hls.logger.log(`${e?"auto":"force"} startLoad with configured startPosition ${t}`),this.hls.startLoad(t));}handleMasterPlaylist(e,t,i,r){let n=this.hls,a=e.data,o=hc(e,i),l=as.parseMasterPlaylist(a,o);if(l.playlistParsingError){t.parsing.end=performance.now(),this.handleManifestParsingError(e,i,l.playlistParsingError,r,t);return}let{contentSteering:d,levels:c,sessionData:u,sessionKeys:h,startTimeOffset:f,variableList:m}=l;this.variableList=m,c.forEach(T=>{let{unknownCodecs:S}=T;if(S){let{preferManagedMediaSource:A}=this.hls.config,{audioCodec:b,videoCodec:D}=T;for(let I=S.length;I--;){let k=S[I];gn(k,"audio",A)?(T.audioCodec=b=b?`${b},${k}`:k,ar.audio[b.substring(0,4)]=2,S.splice(I,1)):gn(k,"video",A)&&(T.videoCodec=D=D?`${D},${k}`:k,ar.video[D.substring(0,4)]=2,S.splice(I,1));}}});let{AUDIO:p=[],SUBTITLES:E,"CLOSED-CAPTIONS":v}=as.parseMasterPlaylistMedia(a,o,l);p.length&&!p.some(S=>!S.url)&&c[0].audioCodec&&!c[0].attrs.AUDIO&&(this.hls.logger.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),p.unshift({type:"main",name:"main",groupId:"main",default:false,autoselect:false,forced:false,id:-1,attrs:new Re({}),bitrate:0,url:""})),n.trigger(g.MANIFEST_LOADED,{levels:c,audioTracks:p,subtitles:E,captions:v,contentSteering:d,url:o,stats:t,networkDetails:r,sessionData:u,sessionKeys:h,startTimeOffset:f,variableList:m});}handleTrackOrLevelPlaylist(e,t,i,r,n){let a=this.hls,{id:o,level:l,type:d}=i,c=hc(e,i),u=G(l)?l:G(o)?o:0,h=bg(i),f=as.parseLevelPlaylist(e.data,c,u,h,0,this.variableList);if(d===ce.MANIFEST){let m={attrs:new Re({}),bitrate:0,details:f,name:"",url:c};f.requestScheduled=t.loading.start+Zg(f,0),a.trigger(g.MANIFEST_LOADED,{levels:[m],audioTracks:[],url:c,stats:t,networkDetails:r,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null});}t.parsing.end=performance.now(),i.levelDetails=f,this.handlePlaylistLoaded(f,e,t,i,r,n);}handleManifestParsingError(e,t,i,r,n){this.hls.trigger(g.ERROR,{type:z.NETWORK_ERROR,details:x.MANIFEST_PARSING_ERROR,fatal:t.type===ce.MANIFEST,url:e.url,err:i,error:i,reason:i.message,response:e,context:t,networkDetails:r,stats:n});}handleNetworkError(e,t,i=false,r,n){let a=`A network ${i?"timeout":"error"+(r?" (status "+r.code+")":"")} occurred while loading ${e.type}`;e.type===ce.LEVEL?a+=`: ${e.level} id: ${e.id}`:(e.type===ce.AUDIO_TRACK||e.type===ce.SUBTITLE_TRACK)&&(a+=` id: ${e.id} group-id: "${e.groupId}"`);let o=new Error(a);this.hls.logger.warn(`[playlist-loader]: ${a}`);let l=x.UNKNOWN,d=false,c=this.getInternalLoader(e);switch(e.type){case ce.MANIFEST:l=i?x.MANIFEST_LOAD_TIMEOUT:x.MANIFEST_LOAD_ERROR,d=true;break;case ce.LEVEL:l=i?x.LEVEL_LOAD_TIMEOUT:x.LEVEL_LOAD_ERROR,d=false;break;case ce.AUDIO_TRACK:l=i?x.AUDIO_TRACK_LOAD_TIMEOUT:x.AUDIO_TRACK_LOAD_ERROR,d=false;break;case ce.SUBTITLE_TRACK:l=i?x.SUBTITLE_TRACK_LOAD_TIMEOUT:x.SUBTITLE_LOAD_ERROR,d=false;break}c&&this.resetInternalLoader(e.type);let u={type:z.NETWORK_ERROR,details:l,fatal:d,url:e.url,loader:c,context:e,error:o,networkDetails:t,stats:n};if(r){let h=t?.url||e.url;u.response=ve({url:h,data:void 0},r);}this.hls.trigger(g.ERROR,u);}handlePlaylistLoaded(e,t,i,r,n,a){let o=this.hls,{type:l,level:d,levelOrTrack:c,id:u,groupId:h,deliveryDirectives:f}=r,m=hc(t,r),p=bg(r),E=typeof r.level=="number"&&p===W.MAIN?d:void 0,v=e.playlistParsingError;if(v){if(this.hls.logger.warn(`${v} ${e.url}`),!o.config.ignorePlaylistParsingErrors){o.trigger(g.ERROR,{type:z.NETWORK_ERROR,details:x.LEVEL_PARSING_ERROR,fatal:false,url:m,error:v,reason:v.message,response:t,context:r,level:E,parent:p,networkDetails:n,stats:i});return}e.playlistParsingError=null;}if(!e.fragments.length){let T=e.playlistParsingError=new Error("No Segments found in Playlist");o.trigger(g.ERROR,{type:z.NETWORK_ERROR,details:x.LEVEL_EMPTY_ERROR,fatal:false,url:m,error:T,reason:T.message,response:t,context:r,level:E,parent:p,networkDetails:n,stats:i});return}switch(e.live&&a&&(a.getCacheAge&&(e.ageHeader=a.getCacheAge()||0),(!a.getCacheAge||isNaN(e.ageHeader))&&(e.ageHeader=0)),l){case ce.MANIFEST:case ce.LEVEL:if(E){if(!c)E=0;else if(c!==o.levels[E]){let T=o.levels.indexOf(c);T>-1&&(E=T);}}o.trigger(g.LEVEL_LOADED,{details:e,levelInfo:c||o.levels[0],level:E||0,id:u||0,stats:i,networkDetails:n,deliveryDirectives:f,withoutMultiVariant:l===ce.MANIFEST});break;case ce.AUDIO_TRACK:o.trigger(g.AUDIO_TRACK_LOADED,{details:e,track:c,id:u||0,groupId:h||"",stats:i,networkDetails:n,deliveryDirectives:f});break;case ce.SUBTITLE_TRACK:o.trigger(g.SUBTITLE_TRACK_LOADED,{details:e,track:c,id:u||0,groupId:h||"",stats:i,networkDetails:n,deliveryDirectives:f});break}}},ui=class s{static get version(){return Sn}static isMSESupported(){return Wp()}static isSupported(){return YA()}static getMediaSource(){return Fi()}static get Events(){return g}static get MetadataSchema(){return At}static get ErrorTypes(){return z}static get ErrorDetails(){return x}static get DefaultConfig(){return s.defaultConfig?s.defaultConfig:UA}static set DefaultConfig(e){s.defaultConfig=e;}constructor(e={}){this.config=void 0,this.userConfig=void 0,this.logger=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this._emitter=new Bu,this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.abrController=void 0,this.bufferController=void 0,this.capLevelController=void 0,this.latencyController=void 0,this.levelController=void 0,this.streamController=void 0,this.audioStreamController=void 0,this.subtititleStreamController=void 0,this.audioTrackController=void 0,this.subtitleTrackController=void 0,this.interstitialsController=void 0,this.gapController=void 0,this.emeController=void 0,this.cmcdController=void 0,this._media=null,this._url=null,this._sessionId=void 0,this.triggeringException=void 0,this.started=false;let t=this.logger=Xv(e.debug||false,"Hls instance",e.assetPlayerId),i=this.config=$A(s.DefaultConfig,e,t);this.userConfig=e,i.progressive&&GA(i,t);let{abrController:r,bufferController:n,capLevelController:a,errorController:o,fpsController:l}=i,d=new o(this),c=this.abrController=new r(this),u=new Ac(this),h=i.interstitialsController,f=h?this.interstitialsController=new h(this,s):null,m=this.bufferController=new n(this,u),p=this.capLevelController=new a(this),E=new l(this),v=new Cu(this),T=i.contentSteeringController,S=T?new T(this):null,A=this.levelController=new Ru(this,S),b=new Lu(this),D=new Du(this.config,this.logger),I=this.streamController=new ku(this,u,D),k=this.gapController=new _u(this,u);p.setStreamController(I),E.setStreamController(I);let R=[v,A,I];f&&R.splice(1,0,f),S&&R.splice(1,0,S),this.networkControllers=R;let L=[c,m,k,p,E,b,u];this.audioTrackController=this.createController(i.audioTrackController,R);let M=i.audioStreamController;M&&R.push(this.audioStreamController=new M(this,u,D)),this.subtitleTrackController=this.createController(i.subtitleTrackController,R);let B=i.subtitleStreamController;B&&R.push(this.subtititleStreamController=new B(this,u,D)),this.createController(i.timelineController,L),D.emeController=this.emeController=this.createController(i.emeController,L),this.cmcdController=this.createController(i.cmcdController,L),this.latencyController=this.createController(xu,L),this.coreComponents=L,R.push(d);let K=d.onErrorOut;typeof K=="function"&&this.on(g.ERROR,K,d),this.on(g.MANIFEST_LOADED,v.onManifestLoaded,v);}createController(e,t){if(e){let i=new e(this);return t&&t.push(i),i}return null}on(e,t,i=this){this._emitter.on(e,t,i);}once(e,t,i=this){this._emitter.once(e,t,i);}removeAllListeners(e){this._emitter.removeAllListeners(e);}off(e,t,i=this,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(this.logger.error("An internal error happened while handling event "+e+'. Error message: "'+i.message+'". Here is a stacktrace:',i),!this.triggeringException){this.triggeringException=true;let r=e===g.ERROR;this.trigger(g.ERROR,{type:z.OTHER_ERROR,details:x.INTERNAL_EXCEPTION,fatal:r,event:e,error:i}),this.triggeringException=false;}}return false}listenerCount(e){return this._emitter.listenerCount(e)}destroy(){this.logger.log("destroy"),this.trigger(g.DESTROYING,void 0),this.detachMedia(),this.removeAllListeners(),this._autoLevelCapping=-1,this._url=null,this.networkControllers.forEach(t=>t.destroy()),this.networkControllers.length=0,this.coreComponents.forEach(t=>t.destroy()),this.coreComponents.length=0;let e=this.config;e.xhrSetup=e.fetchSetup=void 0,this.userConfig=null;}attachMedia(e){if(!e||"media"in e&&!e.media){let n=new Error(`attachMedia failed: invalid argument (${e})`);this.trigger(g.ERROR,{type:z.OTHER_ERROR,details:x.ATTACH_MEDIA_ERROR,fatal:true,error:n});return}this.logger.log("attachMedia"),this._media&&(this.logger.warn("media must be detached before attaching"),this.detachMedia());let t="media"in e,i=t?e.media:e,r=t?e:{media:i};this._media=i,this.trigger(g.MEDIA_ATTACHING,r);}detachMedia(){this.logger.log("detachMedia"),this.trigger(g.MEDIA_DETACHING,{}),this._media=null;}transferMedia(){this._media=null;let e=this.bufferController.transferMedia();return this.trigger(g.MEDIA_DETACHING,{transferMedia:e}),e}loadSource(e){this.stopLoad();let t=this.media,i=this._url,r=this._url=Mu.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:true});this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.logger.log(`loadSource:${r}`),t&&i&&(i!==r||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(t)),this.trigger(g.MANIFEST_LOADING,{url:e});}get url(){return this._url}get hasEnoughToStart(){return this.streamController.hasEnoughToStart}get startPosition(){return this.streamController.startPositionValue}startLoad(e=-1,t){this.logger.log(`startLoad(${e+(t?", <skip seek to start>":"")})`),this.started=true,this.resumeBuffering();for(let i=0;i<this.networkControllers.length&&(this.networkControllers[i].startLoad(e,t),!(!this.started||!this.networkControllers));i++);}stopLoad(){this.logger.log("stopLoad"),this.started=false;for(let e=0;e<this.networkControllers.length&&(this.networkControllers[e].stopLoad(),!(this.started||!this.networkControllers));e++);}get loadingEnabled(){return this.started}get bufferingEnabled(){return this.streamController.bufferingEnabled}resumeBuffering(){this.bufferingEnabled||(this.logger.log("resume buffering"),this.networkControllers.forEach(e=>{e.resumeBuffering&&e.resumeBuffering();}));}pauseBuffering(){this.bufferingEnabled&&(this.logger.log("pause buffering"),this.networkControllers.forEach(e=>{e.pauseBuffering&&e.pauseBuffering();}));}get inFlightFragments(){let e={[W.MAIN]:this.streamController.inFlightFrag};return this.audioStreamController&&(e[W.AUDIO]=this.audioStreamController.inFlightFrag),this.subtititleStreamController&&(e[W.SUBTITLE]=this.subtititleStreamController.inFlightFrag),e}swapAudioCodec(){this.logger.log("swapAudioCodec"),this.streamController.swapAudioCodec();}recoverMediaError(){this.logger.log("recoverMediaError");let e=this._media,t=e?.currentTime;this.detachMedia(),e&&(this.attachMedia(e),t&&this.startLoad(t));}removeLevel(e){this.levelController.removeLevel(e);}get sessionId(){let e=this._sessionId;return e||(e=this._sessionId=aA()),e}get levels(){let e=this.levelController.levels;return e||[]}get latestLevelDetails(){return this.streamController.getLevelDetails()||null}get loadLevelObj(){return this.levelController.loadLevelObj}get currentLevel(){return this.streamController.currentLevel}set currentLevel(e){this.logger.log(`set currentLevel:${e}`),this.levelController.manualLevel=e,this.streamController.immediateLevelSwitch();}get nextLevel(){return this.streamController.nextLevel}set nextLevel(e){this.logger.log(`set nextLevel:${e}`),this.levelController.manualLevel=e,this.streamController.nextLevelSwitch();}get loadLevel(){return this.levelController.level}set loadLevel(e){this.logger.log(`set loadLevel:${e}`),this.levelController.manualLevel=e;}get nextLoadLevel(){return this.levelController.nextLoadLevel}set nextLoadLevel(e){this.levelController.nextLoadLevel=e;}get firstLevel(){return Math.max(this.levelController.firstLevel,this.minAutoLevel)}set firstLevel(e){this.logger.log(`set firstLevel:${e}`),this.levelController.firstLevel=e;}get startLevel(){let e=this.levelController.startLevel;return e===-1&&this.abrController.forcedAutoLevel>-1?this.abrController.forcedAutoLevel:e}set startLevel(e){this.logger.log(`set startLevel:${e}`),e!==-1&&(e=Math.max(e,this.minAutoLevel)),this.levelController.startLevel=e;}get capLevelToPlayerSize(){return this.config.capLevelToPlayerSize}set capLevelToPlayerSize(e){let t=!!e;t!==this.config.capLevelToPlayerSize&&(t?this.capLevelController.startCapping():(this.capLevelController.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=t);}get autoLevelCapping(){return this._autoLevelCapping}get bandwidthEstimate(){let{bwEstimator:e}=this.abrController;return e?e.getEstimate():NaN}set bandwidthEstimate(e){this.abrController.resetEstimator(e);}get abrEwmaDefaultEstimate(){let{bwEstimator:e}=this.abrController;return e?e.defaultEstimate:NaN}get ttfbEstimate(){let{bwEstimator:e}=this.abrController;return e?e.getEstimateTTFB():NaN}set autoLevelCapping(e){this._autoLevelCapping!==e&&(this.logger.log(`set autoLevelCapping:${e}`),this._autoLevelCapping=e,this.levelController.checkMaxAutoUpdated());}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(e){kT(e)&&this._maxHdcpLevel!==e&&(this._maxHdcpLevel=e,this.levelController.checkMaxAutoUpdated());}get autoLevelEnabled(){return this.levelController.manualLevel===-1}get manualLevel(){return this.levelController.manualLevel}get minAutoLevel(){let{levels:e,config:{minAutoBitrate:t}}=this;if(!e)return 0;let i=e.length;for(let r=0;r<i;r++)if(e[r].maxBitrate>=t)return r;return 0}get maxAutoLevel(){let{levels:e,autoLevelCapping:t,maxHdcpLevel:i}=this,r;if(t===-1&&e!=null&&e.length?r=e.length-1:r=t,i)for(let n=r;n--;){let 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()}get maxBufferLength(){return this.streamController.maxBufferLength}setAudioOption(e){var t;return ((t=this.audioTrackController)==null?void 0:t.setAudioOption(e))||null}setSubtitleOption(e){var t;return ((t=this.subtitleTrackController)==null?void 0:t.setSubtitleOption(e))||null}get allAudioTracks(){let e=this.audioTrackController;return e?e.allAudioTracks:[]}get audioTracks(){let e=this.audioTrackController;return e?e.audioTracks:[]}get audioTrack(){let e=this.audioTrackController;return e?e.audioTrack:-1}set audioTrack(e){let t=this.audioTrackController;t&&(t.audioTrack=e);}get allSubtitleTracks(){let e=this.subtitleTrackController;return e?e.allSubtitleTracks:[]}get subtitleTracks(){let e=this.subtitleTrackController;return e?e.subtitleTracks:[]}get subtitleTrack(){let e=this.subtitleTrackController;return e?e.subtitleTrack:-1}get media(){return this._media}set subtitleTrack(e){let t=this.subtitleTrackController;t&&(t.subtitleTrack=e);}get subtitleDisplay(){let e=this.subtitleTrackController;return e?e.subtitleDisplay:false}set subtitleDisplay(e){let t=this.subtitleTrackController;t&&(t.subtitleDisplay=e);}get lowLatencyMode(){return this.config.lowLatencyMode}set lowLatencyMode(e){this.config.lowLatencyMode=e;}get liveSyncPosition(){return this.latencyController.liveSyncPosition}get latency(){return this.latencyController.latency}get maxLatency(){return this.latencyController.maxLatency}get targetLatency(){return this.latencyController.targetLatency}set targetLatency(e){this.latencyController.targetLatency=e;}get drift(){return this.latencyController.drift}get forceStartLoad(){return this.streamController.forceStartLoad}get pathways(){return this.levelController.pathways}get pathwayPriority(){return this.levelController.pathwayPriority}set pathwayPriority(e){this.levelController.pathwayPriority=e;}get bufferedToEnd(){var e;return !!((e=this.bufferController)!=null&&e.bufferedToEnd)}get interstitialsManager(){var e;return ((e=this.interstitialsController)==null?void 0:e.interstitialsManager)||null}getMediaDecodingInfo(e,t=this.allAudioTracks){let i=Bg(t);return Ng(e,i,navigator.mediaCapabilities)}};ui.defaultConfig=void 0;var qp=Symbol.for(""),zA=s=>{if(s?.r===qp)return s?._$litStatic$},zu=s=>({_$litStatic$:s,r:qp});var Yp=new Map,jp=s=>(e,...t)=>{let i=t.length,r,n,a=[],o=[],l,d=0,c=false;for(;d<i;){for(l=e[d];d<i&&(n=t[d],(r=zA(n))!==void 0);)l+=r+e[++d],c=true;d!==i&&o.push(n),a.push(l),d++;}if(d===i&&a.push(e[i]),c){let u=a.join("$$lit$$");(e=Yp.get(u))===void 0&&(a.raw=a,Yp.set(u,e=a)),t=o;}return s(e,...t)},zp=jp(chunk5NSCV6C2_cjs.c);var H,Qp,Xp,Qu,gl,Zp,Jp,e0,t0,Xu,Zu,Ju,pl,i0,eh,th,s0,ih,El,sh,Rn,lr,rh,r0,n0,_e=class extends chunkEOHKHSQ3_cjs.a{constructor(){super(...arguments);chunkJHSFSCC2_cjs.e(this,H);this._controls=["play","time","seek","volume","audio-tracks","fullscreen","subtitles"];this.popped=false;this._startedPlaying=false;this._audioTrackCount=0;this._hlsAudioTracks=[];this._hlsAudioTrackIdMap=new Map;this._intersectionObserver=new chunkKVMGCTLR_cjs.a(this,{callback:chunkJHSFSCC2_cjs.g(this,H,e0).bind(this)});this.embedController=new chunkYT56YDUY_cjs.b(this);this._intersected=false;this._queue=[];}get embed(){return this._embedId}set embed(t){this._embedId!=t&&(this._embedId=t,this.embedController.embed=this.embed,this.updateStylePoster(),this.loadTheme());}get token(){return this._token}set token(t){this._token!=t&&(this._token=t,this.requestUpdate("token"),this.embedController.token=this._token);}set loop(t){this._loop=(t===""||t=="true"||t==true)??false;}get loop(){return this._loop}get controls(){return this._controls}set controls(t){typeof t=="string"?this._controls=t.split(" "):this._controls=t;}get cache(){return this._cache}set cache(t){this._cache!=t&&(typeof t=="string"?this._cache=t==="true"||t==="":this._cache=false,this.requestUpdate("caching"),this.embedController.caching=this._cache);}get quality(){return this._quality}set quality(t){this._quality!=t&&(this._quality=t);}get theme(){return this._theme||"default"}set theme(t){this._theme!=t&&(this._theme=t,this.requestUpdate("theme"),this.loadTheme());}get poster(){return !this.embed||!this._embedObj||!chunkJHSFSCC2_cjs.g(this,H,Qu).call(this,"thumbnail","jpg")?null:this._poster&&this._poster=="custom"?this.embedController.embedFile(chunkJHSFSCC2_cjs.g(this,H,gl).call(this,"custom_thumbnail")):this._poster&&(!Number.isNaN(parseFloat(this._poster))||!Number.isNaN(parseInt(this._poster)))?this._embedObj.poster&&this._embedObj.poster.renditions&&this._embedObj.poster.renditions.find(t=>t.type=="custom_thumbnail")?this.embedController.embedFile(chunkJHSFSCC2_cjs.g(this,H,gl).call(this,"custom_thumbnail")):`https://image.mave.io/${this.embedController.spaceId}${this.embedController.embedId}.jpg?time=${this._poster}`:this._poster?this._poster:this.embedController.embedFile(chunkJHSFSCC2_cjs.g(this,H,gl).call(this,"thumbnail"))}set poster(t){t&&(this._poster=t,this.requestUpdate("poster"));}pop(){this.popped=true;}close(){this.popped=false;}set muted(t){let i=(t===""||t=="true"||t==true)??false;this._videoElement?this._videoElement.muted=i:this._queue.push(()=>this._videoElement.muted=i);}get muted(){return this._videoElement?.muted||false}set currentTime(t){this._videoElement?this._videoElement.currentTime=t:this._queue.push(()=>this._videoElement.currentTime=t);}get currentTime(){return this._videoElement?this._videoElement?.currentTime:0}get duration(){return new Promise((t,i)=>{if(this._videoElement&&!isNaN(this._videoElement.duration))return t(this._videoElement.duration);let r=()=>{this._videoElement?.addEventListener("loadedmetadata",()=>{this._videoElement&&t(this._videoElement.duration);}),this._videoElement?.addEventListener("error",()=>{i(new Error("Failed to load video metadata."));});};this._videoElement?r():this.addEventListener("mave:video_element_ready",()=>{r();});})}get paused(){return this._videoElement?this._videoElement.paused:true}play(){this._videoElement&&!this.embedController.loading?chunkJHSFSCC2_cjs.g(this,H,pl).call(this):this._queue.push(()=>chunkJHSFSCC2_cjs.g(this,H,pl).call(this));}restart(){this._videoElement&&(this.pause(),this._videoElement.currentTime=0,this.play());}pause(){this._videoElement?this._videoElement.pause():this._queue.push(()=>this._videoElement?.pause());}updateStylePoster(){this.style.setProperty("background",`center / contain no-repeat url(${this.poster})`);}connectedCallback(){super.connectedCallback(),this.loadTheme(),this.addEventListener("mave:video_element_ready",chunkJHSFSCC2_cjs.g(this,H,Xp).bind(this));}disconnectedCallback(){super.disconnectedCallback(),this._metricsInstance?.demonitor(),this._cleanupHlsAudioTracks?.(),this._cleanupHlsAudioTracks=void 0,this._pendingAudioTrackSetup!=null&&(cancelAnimationFrame(this._pendingAudioTrackSetup),this._pendingAudioTrackSetup=void 0),this._hlsAudioTrackIdMap.clear(),this._hlsAudioTracks=[],this._currentAudioTrackMenu=void 0,this._themeMutationObserver?.disconnect(),this._themeMutationObserver=void 0,this._themeMutationObserverRoot=void 0;}loadTheme(){this.embed&&this._themeLoaded!=this.theme&&(this.theme&&this.theme.endsWith(".js")?chunkBVMU4ZXD_cjs.a.external(this.theme):chunkBVMU4ZXD_cjs.a.get(this.theme,`${this.embedController.cdnRoot}/themes/player`),this._themeLoaded=chunkBVMU4ZXD_cjs.a.getTheme());}updateEmbed(t){this._embedObj=t,this._audioTrackCount=t.audio_tracks?.length??0,this.updateStylePoster(),this.poster=this._embedObj.settings.poster,this.attributes.getNamedItem("color")||(this.color=this._embedObj.settings.color),this.attributes.getNamedItem("opacity")||(this.opacity=this._embedObj.settings.opacity?this._embedObj.settings.opacity:void 0),this.attributes.getNamedItem("aspect-ratio")||(this.aspect_ratio=this._embedObj.settings.aspect_ratio),this.attributes.getNamedItem("width")||(this.width=this._embedObj.settings.width),this.attributes.getNamedItem("height")||(this.height=this._embedObj.settings.height),this.attributes.getNamedItem("autoplay")||(this.autoplay=this._embedObj.settings.autoplay=="on_show"?"lazy":this._embedObj.settings.autoplay),this.attributes.getNamedItem("controls")||(this.controls=this._embedObj.settings.controls),this.attributes.getNamedItem("loop")||(this.loop=this._embedObj.settings.loop);}get styles(){let t={},i=!!this._embedObj?.subtitles?.length,r=this.subtitles==="none"||this.subtitles==="off"||!i,n=this.controls.includes("volume")||this.controls.includes("full");(this.color||this._embedObj?.settings.color)&&(t["--primary-color"]=`${this.color||this._embedObj?.settings.color}${this.opacity||this._embedObj?.settings.opacity?this._embedObj?.settings.opacity:""}`),this.aspect_ratio=="auto"||this._embedObj?.settings.aspect_ratio=="auto"&&!this.aspect_ratio?t["--aspect-ratio"]=this._embedObj?.video.aspect_ratio:t["--aspect-ratio"]=this.aspect_ratio||this._embedObj?.settings.aspect_ratio,(this.width||this._embedObj?.settings.width)&&(t["--width"]=this.width||this._embedObj?.settings.width),(this.height||this._embedObj?.settings.height)&&(t["--height"]=this.height||this._embedObj?.settings.height),!this.controls.includes("full")&&!this.controls.includes("big")&&!this.controls.includes("none")&&(t["--play-display"]=this.controls.includes("play")?"flex":"none",t["--time-display"]=this.controls.includes("time")?"flex":"none",t["--seek-bar-visibility"]=this.controls.includes("seek")?"visible":"hidden",t["--volume-display"]=this.controls.includes("volume")?"flex":"none",t["--fullscreen-display"]=this.controls.includes("fullscreen")?"flex":"none",t["--media-captions-menu-button-display"]=this.controls.includes("subtitles")?"flex":"none"),t["--playbackrate-display"]=this.controls.includes("rate")?"flex":"none",(r||this._embedObj?.created_at<1740674988&&!this.subtitles&&!this.active_subtitle)&&(t["--media-captions-menu-button-display"]="none"),this.controls.includes("full")||this._embedObj?.settings.controls=="full"&&!this.controls.includes("big")&&!this.controls.includes("none")?t["--media-control-bar-display"]="flex":t["--media-control-bar-display"]="none",this.controls.includes("big")||this._embedObj?.settings.controls=="big"&&!this.controls.includes("full")&&!this.controls.includes("none")?t["--big-button-display"]="flex":t["--big-button-display"]="none",this._embedObj?.video.audio===false?t["--media-mute-button-display"]="none":n?t["--media-mute-button-display"]="flex":t["--media-mute-button-display"]="none";let a=this._audioTrackCount??0,o=this.controls.includes("audio-tracks")||this.controls.includes("full");return t["--media-audio-track-menu-button-display"]=a>1&&o?"flex":"none",chunkQ22T22LT_cjs.a(t)}render(){if(!this.embed)return;let t=this.querySelector('[slot="start-screen"], [data-slot="start-screen"]');return chunk5NSCV6C2_cjs.c`
1389
1389
  <slot
1390
1390
  name="video"
1391
1391
  style=${chunkQ22T22LT_cjs.a({display:t&&!this._startedPlaying?"none":"block"})}
1392
1392
  >
1393
- ${this.embedController.render({complete:i=>{if(this._embed||(this._embedObj=i,this.updateEmbed(this._embedObj)),!!i)return jp`<theme-${zu(this._themeLoaded)} style=${this.styles}>
1393
+ ${this.embedController.render({complete:i=>{if(this._embed||(this._embedObj=i,this.updateEmbed(this._embedObj)),!!i)return zp`<theme-${zu(this._themeLoaded)} style=${this.styles}>
1394
1394
  <video
1395
- @click=${chunkJHSFSCC2_cjs.g(this,V,pl)}
1395
+ @click=${chunkJHSFSCC2_cjs.g(this,H,pl)}
1396
1396
  playsinline
1397
1397
  ?loop=${this.loop||this._embedObj.settings.loop}
1398
1398
  poster=${this.poster}
1399
- ${chunkKVMGCTLR_cjs.c(chunkJHSFSCC2_cjs.g(this,V,Zp))}
1399
+ ${chunkKVMGCTLR_cjs.c(chunkJHSFSCC2_cjs.g(this,H,Jp))}
1400
1400
  slot="media"
1401
1401
  crossorigin="anonymous"
1402
1402
  >
1403
- ${chunkJHSFSCC2_cjs.d(this,V,r0)}
1404
- ${chunkJHSFSCC2_cjs.d(this,V,s0)}
1403
+ ${chunkJHSFSCC2_cjs.d(this,H,n0)}
1404
+ ${chunkJHSFSCC2_cjs.d(this,H,r0)}
1405
1405
  </video>
1406
1406
  </theme-${zu(this._themeLoaded)}>`}})}
1407
1407
  </slot>
1408
1408
  <slot name="start-screen"></slot>
1409
1409
  <slot name="end-screen"></slot>
1410
1410
  <slot name="hover-screen"></slot>
1411
- `}};V=new WeakSet,zp=function(t,i){let r=new URL(i);if(this.token&&!r.searchParams.get("token")){let n=new URLSearchParams;n.append("token",this.token),r.search=n.toString();}t.open("GET",r.toString());},Qp=function(){this._videoElement?.addEventListener("webkitbeginfullscreen",()=>{this.style.setProperty("--subtitle-opacity","1");}),this._videoElement?.addEventListener("webkitendfullscreen",()=>{this.style.setProperty("--subtitle-opacity","0");});},gl=function(t){let r=(a=>this._embedObj.poster&&this._embedObj.poster.renditions&&this._embedObj.poster.renditions.find(o=>o.container===a&&o.type===t))("jpg"),n=t=="custom_thumbnail"?"thumbnail":t;return r?`${n}.jpg${r&&r.date?`?e=${r.date}`:""}`:`${n}.jpg`},Xp=function(){let t=[{name:"sd",width:640},{name:"hd",width:1280},{name:"fhd",width:1920},{name:"qhd",width:2560},{name:"uhd",width:3840}],i=t.find(r=>r.name==this.quality);return i?t.indexOf(i):2},Zp=function(t){if(t&&t.tagName=="VIDEO"&&(chunkJHSFSCC2_cjs.d(this,V,lr)||chunkJHSFSCC2_cjs.d(this,V,sh))){this._videoElement=t,this.dispatchEvent(new CustomEvent("mave:video_element_ready",{detail:this._videoElement,bubbles:true,composed:true})),this._intersectionObserver.observe(this._videoElement),chunkSDKTBB4N_cjs.a.forEach(n=>{this._videoElement?.addEventListener(n,a=>{if(n=="play"&&chunkJHSFSCC2_cjs.g(this,V,e0).call(this),n=="ended"&&chunkJHSFSCC2_cjs.g(this,V,Qu).call(this),n=="timeupdate"&&this._videoElement&&this._videoElement.duration-this._videoElement.currentTime<5){let o=this.querySelector('[slot="end-screen"], [data-slot="end-screen"]');if(o&&o.getAttribute("x-mave-end-shows")=="near_end"){chunkJHSFSCC2_cjs.g(this,V,Qu).call(this);let l=this.querySelector("[name='mave-time-remaining']");if(l){let c=Math.floor(this._videoElement.duration-this._videoElement.currentTime);l.innerHTML=c<=0?"0":c.toString();}if(this._videoElement?.duration-this._videoElement?.currentTime<=0&&o.getAttribute("x-mave-list-trigger-next")=="true"){let c=[...document.querySelectorAll("mave-list")].find(u=>u.containsEmbed(this.embed));if(c){let u=c.getNextForEmbed(this.embed);u&&this.emit(this.EVENT_TYPES.CLICK,{embedId:u.id});}}let d=this.querySelector("[name='mave-list-next-image']");if(d){let c=[...document.querySelectorAll("mave-list")].find(u=>u.containsEmbed(this.embed));if(c){let u=c.getNextForEmbed(this.embed);if(u){let h=document.createElement("mave-img");h.setAttribute("embed",u.id),h.addEventListener("click",()=>{this.emit(this.EVENT_TYPES.CLICK,{embedId:u.id}),d.innerHTML="";}),d.appendChild(h);}else d.innerHTML="";}}}}this.dispatchEvent(new CustomEvent(n,{detail:a,bubbles:true,composed:true}));});}),xn.Metrics.config={socketPath:chunk5STN56TL_cjs.a.metrics.socket,apiKey:this._embedObj.metrics_key};let i={component:"player",video_id:this._embedObj.video.id,space_id:this._embedObj.space_id},r=/iPhone|iPad/.test(navigator.userAgent);ui.isSupported()&&chunkJHSFSCC2_cjs.d(this,V,lr)&&!r?(this._cleanupHlsAudioTracks?.(),this._cleanupHlsAudioTracks=void 0,this._pendingAudioTrackSetup!=null&&(cancelAnimationFrame(this._pendingAudioTrackSetup),this._pendingAudioTrackSetup=void 0),this._hlsAudioTrackIdMap.clear(),this._hlsAudioTracks=[],this.hls=new ui({startLevel:chunkJHSFSCC2_cjs.g(this,V,Xp).call(this),capLevelToPlayerSize:true,xhrSetup:chunkJHSFSCC2_cjs.g(this,V,zp).bind(this),maxBufferLength:20,maxBufferSize:20,backBufferLength:60}),this.hls?.loadSource(chunkJHSFSCC2_cjs.d(this,V,lr)),this.hls?.attachMedia(this._videoElement),chunkJHSFSCC2_cjs.g(this,V,ih).call(this),chunk5STN56TL_cjs.a.metrics.enabled&&(this._metricsInstance=new xn.Metrics(this.hls,this.embed,i))):this._videoElement.canPlayType("application/vnd.apple.mpegurl")&&chunkJHSFSCC2_cjs.d(this,V,lr)?(this._cleanupHlsAudioTracks?.(),this._cleanupHlsAudioTracks=void 0,this._pendingAudioTrackSetup!=null&&(cancelAnimationFrame(this._pendingAudioTrackSetup),this._pendingAudioTrackSetup=void 0),this._hlsAudioTrackIdMap.clear(),this._hlsAudioTracks=[],this._videoElement.src=chunkJHSFSCC2_cjs.d(this,V,lr),chunk5STN56TL_cjs.a.metrics.enabled&&(this._metricsInstance=new xn.Metrics(this._videoElement,this.embed,i))):(this._cleanupHlsAudioTracks?.(),this._cleanupHlsAudioTracks=void 0,this._pendingAudioTrackSetup!=null&&(cancelAnimationFrame(this._pendingAudioTrackSetup),this._pendingAudioTrackSetup=void 0),this._hlsAudioTrackIdMap.clear(),this._hlsAudioTracks=[],this._videoElement.src=chunkJHSFSCC2_cjs.d(this,V,sh),chunk5STN56TL_cjs.a.metrics.enabled&&(this._metricsInstance=new xn.Metrics(this._videoElement,this.embed,i))),this._queue.length&&(this._queue.forEach(n=>n()),this._queue=[]),chunkJHSFSCC2_cjs.g(this,V,Zu).call(this),chunkJHSFSCC2_cjs.g(this,V,Xu).call(this);}},Jp=function(t){for(let{isIntersecting:i}of t)t.length&&(t[0].target.tagName=="VIDEO"||t[0].target.tagName=="MAVE-PLAYER")&&(this._intersected=i,chunkJHSFSCC2_cjs.g(this,V,Zu).call(this));},e0=function(){if(this.active_subtitle&&!this._startedPlaying){let i;if(this.active_subtitle=="original"||this.subtitles=="original"){let r=this._embedObj.video.language;i=this._videoElement?.querySelector(`track[srclang="${r}"]`);}else i=this._videoElement?.querySelector(`track[srclang="${this.active_subtitle}"]`);i&&(i.track.mode="showing");}this._startedPlaying=true,chunkJHSFSCC2_cjs.g(this,V,Xu).call(this),this._previousControls&&(this.controls=this._previousControls,this._previousControls=void 0);let t=this.querySelector('[slot="start-screen"], [data-slot="start-screen"]');t&&((this.shadowRoot?.querySelector("slot[name='video']")).removeAttribute("style"),this.startScreenElement.style.display="none",t.style.display="none");},Qu=function(){let t=this.querySelector('[slot="end-screen"], [data-slot="end-screen"]');if(t){if(t.tagName==="TEMPLATE"){let i=t,r=i.parentElement,n=document.createElement("div");for(let a of i.attributes)n.setAttribute(a.name,a.value);n.style.display="block",n.innerHTML=i.innerHTML,r?.replaceChild(n,i);}this.endScreenElement.style.display="block",t.style.display="block",this._previousControls||(this._previousControls=this.controls),this.controls="none";}},Xu=function(){let t=this.querySelector('[slot="end-screen"], [data-slot="end-screen"]');t&&(this.endScreenElement.style.display="none",t.style.display="none"),this._previousControls&&(this.controls=this._previousControls,this._previousControls=void 0);},Zu=function(){this._embedObj&&this.autoplay=="always"&&this._videoElement?.paused&&(this._metricsInstance?.monitor(),this._videoElement.muted=true,this._videoElement?.play()),this._embedObj&&(this.autoplay==="lazy"||this.autoplay==="true"||this._embedObj.settings.autoplay=="on_show")&&(this._intersected?this._videoElement?.paused&&(this._metricsInstance?.monitor(),this._videoElement.muted=true,this._videoElement?.play()):this._videoElement&&!this._videoElement.paused&&this._videoElement.readyState>2&&this._videoElement?.pause());},pl=function(){this._videoElement?.paused?(this._metricsInstance?.monitor(),this._videoElement?.play()):this._videoElement?.pause();},t0=function(t){let i=t.target.track,r=i.activeCues;if(i.mode=="showing"&&(this._currentTrackLanguage=i.language),!this._subtitlesText){let n=this.shadowRoot?.querySelector(`theme-${this._themeLoaded}`)?.shadowRoot?.querySelector("#subtitles_text");n&&(this._subtitlesText=n);}if(r.length){let n=r[0];this._subtitlesText.style.opacity="1",this._subtitlesText.style.transform="scale(1)",this._subtitlesText.innerHTML=n.text.replace(/\n/g,"<br>");}else this._subtitlesText.style.opacity="0",this._subtitlesText.style.transform="scale(0.99)";},Ju=function(t){let i=this._embedObj.video.renditions.filter(a=>a.container==t),r=["sd","hd","fhd","qhd","uhd"];return !i||!i.length?void 0:i.reduce((a,o)=>r.indexOf(o.size)>r.indexOf(a.size)?o:a)},eh=function(){return this._themeLoaded?this.shadowRoot?.querySelector(`theme-${this._themeLoaded}`)?.shadowRoot??null:null},i0=function(t){if(this._themeMutationObserverRoot===t)return;this._themeMutationObserver?.disconnect();let i=new MutationObserver(()=>{chunkJHSFSCC2_cjs.g(this,V,El).call(this);});i.observe(t,{childList:true,subtree:true}),this._themeMutationObserver=i,this._themeMutationObserverRoot=t;},th=function(){let t=chunkJHSFSCC2_cjs.d(this,V,eh);return t?{menu:t.querySelector("mave-audio-track-menu"),button:t.querySelector("mave-audio-track-menu-button")}:{menu:null,button:null}},El=function(){this._pendingAudioTrackSetup==null&&(this._pendingAudioTrackSetup=requestAnimationFrame(()=>{this._pendingAudioTrackSetup=void 0,chunkJHSFSCC2_cjs.g(this,V,ih).call(this);}));},ih=function(){if(!this.hls)return;let t=chunkJHSFSCC2_cjs.d(this,V,eh);t&&chunkJHSFSCC2_cjs.g(this,V,i0).call(this,t);let{menu:i,button:r}=chunkJHSFSCC2_cjs.g(this,V,th).call(this);if(!i||!r){chunkJHSFSCC2_cjs.g(this,V,El).call(this);return}if(i!==this._currentAudioTrackMenu||!this._cleanupHlsAudioTracks){this._cleanupHlsAudioTracks?.();let o=(c,u)=>{this._hlsAudioTracks=u?.audioTracks??[],chunkJHSFSCC2_cjs.g(this,V,Rn).call(this,this._hlsAudioTracks,this.hls?.audioTrack);},l=(c,u)=>{let h=u?.id??(typeof this.hls?.audioTrack=="number"?this.hls.audioTrack:void 0);chunkJHSFSCC2_cjs.g(this,V,Rn).call(this,this._hlsAudioTracks,h);},d=c=>{if(c.type!==chunkDITZCOYN_cjs.a.MEDIA_AUDIO_TRACK_REQUEST)return;let u=c.detail;if(u==null)return;let h=this._hlsAudioTrackIdMap.get(String(u));h==null||!this.hls||this.hls.audioTrack!==h&&(this.hls.audioTrack=h,chunkJHSFSCC2_cjs.g(this,V,Rn).call(this,this._hlsAudioTracks,h));};i.addEventListener(chunkDITZCOYN_cjs.a.MEDIA_AUDIO_TRACK_REQUEST,d),this.hls.on(ui.Events.AUDIO_TRACKS_UPDATED,o),this.hls.on(ui.Events.AUDIO_TRACK_SWITCHED,l),this._cleanupHlsAudioTracks=()=>{i.removeEventListener(chunkDITZCOYN_cjs.a.MEDIA_AUDIO_TRACK_REQUEST,d),this.hls?.off(ui.Events.AUDIO_TRACKS_UPDATED,o),this.hls?.off(ui.Events.AUDIO_TRACK_SWITCHED,l);},this._currentAudioTrackMenu=i,this.hls.audioTracks?.length&&(this._hlsAudioTracks=this.hls.audioTracks);}let n=(this._hlsAudioTracks&&this._hlsAudioTracks.length?this._hlsAudioTracks:this.hls.audioTracks)??[],a=typeof this.hls.audioTrack=="number"?this.hls.audioTrack:void 0;chunkJHSFSCC2_cjs.g(this,V,Rn).call(this,n,a);},Rn=function(t,i){let{menu:r,button:n}=chunkJHSFSCC2_cjs.g(this,V,th).call(this);if(!r||!n){chunkJHSFSCC2_cjs.g(this,V,El).call(this);return}if(this._hlsAudioTracks=t??[],this._hlsAudioTrackIdMap.clear(),!t?.length){"tracks"in r&&(r.tracks=[],r.selected=void 0),this._audioTrackCount=0,this.requestUpdate();return}let a=t.map((l,d)=>{let c=l?.id??d,u=String(c);this._hlsAudioTrackIdMap.set(u,c);let h=l?.lang??l?.attrs?.LANGUAGE,m=(l?.name??"").trim()||typeof h=="string"&&h.trim()||`Track ${d+1}`,p=i!=null?c===i:l?.default??d===0;return {id:u,language:h,label:m,enabled:p}});!a.some(l=>l.enabled)&&a.length&&(a[0].enabled=true);let o=a.find(l=>l.enabled)??a[0];"tracks"in r&&(r.tracks=a,r.selected=o?.id),this._audioTrackCount=a.length,this.requestUpdate();},lr=function(){let t=chunkJHSFSCC2_cjs.g(this,V,Ju).call(this,"hls");if(t){let i=new URLSearchParams;return i.append("quality",t.size),this.embedController.embedFile("playlist.m3u8",i)}},sh=function(){let t=chunkJHSFSCC2_cjs.g(this,V,Ju).call(this,"mp4");return t?this.embedController.embedFile(`h264_${t?.size}.mp4`):this._embedObj.video.original},s0=function(){if(this._embedObj.subtitles.length>0){let t=this.shadowRoot?.querySelector(`theme-${this._themeLoaded}`)?.shadowRoot?.querySelector("media-captions-menu");return t&&new MutationObserver(r=>{r.forEach(()=>{this._subtitlesText&&t.getAttribute("mediasubtitlesshowing")&&(this._subtitlesText.style.opacity="0");});}).observe(t,{attributes:true}),this._embedObj.subtitles.map(i=>{if(this.subtitles&&this.subtitles.includes(i.language)||this.active_subtitle&&this.active_subtitle==i.language||this.subtitles=="all"||(this.subtitles=="original"||this.active_subtitle=="original")&&this._embedObj.video.language==i.language||!this.subtitles)return chunk5NSCV6C2_cjs.c`
1412
- <track mode="hidden" @cuechange=${chunkJHSFSCC2_cjs.g(this,V,t0)} label=${i.label} kind="subtitles" srclang=${i.language} src=${i.path}></track>
1413
- `})}},r0=function(){return chunk5NSCV6C2_cjs.c`<track
1411
+ `}};H=new WeakSet,Qp=function(t,i){let r=new URL(i);if(this.token&&!r.searchParams.get("token")){let n=new URLSearchParams;n.append("token",this.token),r.search=n.toString();}t.open("GET",r.toString());},Xp=function(){this._videoElement?.addEventListener("webkitbeginfullscreen",()=>{this.style.setProperty("--subtitle-opacity","1");}),this._videoElement?.addEventListener("webkitendfullscreen",()=>{this.style.setProperty("--subtitle-opacity","0");});},Qu=function(t,i){return this._embedObj.poster&&this._embedObj.poster.renditions&&this._embedObj.poster.renditions.find(r=>r.container===i&&r.type===t)},gl=function(t){let i=t=="custom_thumbnail"?"thumbnail":t,r=chunkJHSFSCC2_cjs.g(this,H,Qu).call(this,i,"jpg");return r?`${i}.jpg${r&&r.date?`?e=${r.date}`:""}`:`${i}.jpg`},Zp=function(){let t=[{name:"sd",width:640},{name:"hd",width:1280},{name:"fhd",width:1920},{name:"qhd",width:2560},{name:"uhd",width:3840}],i=t.find(r=>r.name==this.quality);return i?t.indexOf(i):2},Jp=function(t){if(t&&t.tagName=="VIDEO"&&(chunkJHSFSCC2_cjs.d(this,H,lr)||chunkJHSFSCC2_cjs.d(this,H,rh))){this._videoElement=t,this.dispatchEvent(new CustomEvent("mave:video_element_ready",{detail:this._videoElement,bubbles:true,composed:true})),this._intersectionObserver.observe(this._videoElement),chunkSDKTBB4N_cjs.a.forEach(n=>{this._videoElement?.addEventListener(n,a=>{if(n=="play"&&chunkJHSFSCC2_cjs.g(this,H,t0).call(this),n=="ended"&&chunkJHSFSCC2_cjs.g(this,H,Xu).call(this),n=="timeupdate"&&this._videoElement&&this._videoElement.duration-this._videoElement.currentTime<5){let o=this.querySelector('[slot="end-screen"], [data-slot="end-screen"]');if(o&&o.getAttribute("x-mave-end-shows")=="near_end"){chunkJHSFSCC2_cjs.g(this,H,Xu).call(this);let l=this.querySelector("[name='mave-time-remaining']");if(l){let c=Math.floor(this._videoElement.duration-this._videoElement.currentTime);l.innerHTML=c<=0?"0":c.toString();}if(this._videoElement?.duration-this._videoElement?.currentTime<=0&&o.getAttribute("x-mave-list-trigger-next")=="true"){let c=[...document.querySelectorAll("mave-list")].find(u=>u.containsEmbed(this.embed));if(c){let u=c.getNextForEmbed(this.embed);u&&this.emit(this.EVENT_TYPES.CLICK,{embedId:u.id});}}let d=this.querySelector("[name='mave-list-next-image']");if(d){let c=[...document.querySelectorAll("mave-list")].find(u=>u.containsEmbed(this.embed));if(c){let u=c.getNextForEmbed(this.embed);if(u){let h=document.createElement("mave-img");h.setAttribute("embed",u.id),h.addEventListener("click",()=>{this.emit(this.EVENT_TYPES.CLICK,{embedId:u.id}),d.innerHTML="";}),d.appendChild(h);}else d.innerHTML="";}}}}this.dispatchEvent(new CustomEvent(n,{detail:a,bubbles:true,composed:true}));});}),xn.Metrics.config={socketPath:chunk5STN56TL_cjs.a.metrics.socket,apiKey:this._embedObj.metrics_key};let i={component:"player",video_id:this._embedObj.video.id,space_id:this._embedObj.space_id},r=/iPhone|iPad/.test(navigator.userAgent);ui.isSupported()&&chunkJHSFSCC2_cjs.d(this,H,lr)&&!r?(this._cleanupHlsAudioTracks?.(),this._cleanupHlsAudioTracks=void 0,this._pendingAudioTrackSetup!=null&&(cancelAnimationFrame(this._pendingAudioTrackSetup),this._pendingAudioTrackSetup=void 0),this._hlsAudioTrackIdMap.clear(),this._hlsAudioTracks=[],this.hls=new ui({startLevel:chunkJHSFSCC2_cjs.g(this,H,Zp).call(this),capLevelToPlayerSize:true,xhrSetup:chunkJHSFSCC2_cjs.g(this,H,Qp).bind(this),maxBufferLength:20,maxBufferSize:20,backBufferLength:60}),this.hls?.loadSource(chunkJHSFSCC2_cjs.d(this,H,lr)),this.hls?.attachMedia(this._videoElement),chunkJHSFSCC2_cjs.g(this,H,sh).call(this),chunk5STN56TL_cjs.a.metrics.enabled&&(this._metricsInstance=new xn.Metrics(this.hls,this.embed,i))):this._videoElement.canPlayType("application/vnd.apple.mpegurl")&&chunkJHSFSCC2_cjs.d(this,H,lr)?(this._cleanupHlsAudioTracks?.(),this._cleanupHlsAudioTracks=void 0,this._pendingAudioTrackSetup!=null&&(cancelAnimationFrame(this._pendingAudioTrackSetup),this._pendingAudioTrackSetup=void 0),this._hlsAudioTrackIdMap.clear(),this._hlsAudioTracks=[],this._videoElement.src=chunkJHSFSCC2_cjs.d(this,H,lr),chunk5STN56TL_cjs.a.metrics.enabled&&(this._metricsInstance=new xn.Metrics(this._videoElement,this.embed,i))):(this._cleanupHlsAudioTracks?.(),this._cleanupHlsAudioTracks=void 0,this._pendingAudioTrackSetup!=null&&(cancelAnimationFrame(this._pendingAudioTrackSetup),this._pendingAudioTrackSetup=void 0),this._hlsAudioTrackIdMap.clear(),this._hlsAudioTracks=[],this._videoElement.src=chunkJHSFSCC2_cjs.d(this,H,rh),chunk5STN56TL_cjs.a.metrics.enabled&&(this._metricsInstance=new xn.Metrics(this._videoElement,this.embed,i))),this._queue.length&&(this._queue.forEach(n=>n()),this._queue=[]),chunkJHSFSCC2_cjs.g(this,H,Ju).call(this),chunkJHSFSCC2_cjs.g(this,H,Zu).call(this);}},e0=function(t){for(let{isIntersecting:i}of t)t.length&&(t[0].target.tagName=="VIDEO"||t[0].target.tagName=="MAVE-PLAYER")&&(this._intersected=i,chunkJHSFSCC2_cjs.g(this,H,Ju).call(this));},t0=function(){if(this.active_subtitle&&!this._startedPlaying){let i;if(this.active_subtitle=="original"||this.subtitles=="original"){let r=this._embedObj.video.language;i=this._videoElement?.querySelector(`track[srclang="${r}"]`);}else i=this._videoElement?.querySelector(`track[srclang="${this.active_subtitle}"]`);i&&(i.track.mode="showing");}this._startedPlaying=true,chunkJHSFSCC2_cjs.g(this,H,Zu).call(this),this._previousControls&&(this.controls=this._previousControls,this._previousControls=void 0);let t=this.querySelector('[slot="start-screen"], [data-slot="start-screen"]');t&&((this.shadowRoot?.querySelector("slot[name='video']")).removeAttribute("style"),this.startScreenElement.style.display="none",t.style.display="none");},Xu=function(){let t=this.querySelector('[slot="end-screen"], [data-slot="end-screen"]');if(t){if(t.tagName==="TEMPLATE"){let i=t,r=i.parentElement,n=document.createElement("div");for(let a of i.attributes)n.setAttribute(a.name,a.value);n.style.display="block",n.innerHTML=i.innerHTML,r?.replaceChild(n,i);}this.endScreenElement.style.display="block",t.style.display="block",this._previousControls||(this._previousControls=this.controls),this.controls="none";}},Zu=function(){let t=this.querySelector('[slot="end-screen"], [data-slot="end-screen"]');t&&(this.endScreenElement.style.display="none",t.style.display="none"),this._previousControls&&(this.controls=this._previousControls,this._previousControls=void 0);},Ju=function(){this._embedObj&&this.autoplay=="always"&&this._videoElement?.paused&&(this._metricsInstance?.monitor(),this._videoElement.muted=true,this._videoElement?.play()),this._embedObj&&(this.autoplay==="lazy"||this.autoplay==="true"||this._embedObj.settings.autoplay=="on_show")&&(this._intersected?this._videoElement?.paused&&(this._metricsInstance?.monitor(),this._videoElement.muted=true,this._videoElement?.play()):this._videoElement&&!this._videoElement.paused&&this._videoElement.readyState>2&&this._videoElement?.pause());},pl=function(){this._videoElement?.paused?(this._metricsInstance?.monitor(),this._videoElement?.play()):this._videoElement?.pause();},i0=function(t){let i=t.target.track,r=i.activeCues;if(i.mode=="showing"&&(this._currentTrackLanguage=i.language),!this._subtitlesText){let n=this.shadowRoot?.querySelector(`theme-${this._themeLoaded}`)?.shadowRoot?.querySelector("#subtitles_text");n&&(this._subtitlesText=n);}if(r.length){let n=r[0];this._subtitlesText.style.opacity="1",this._subtitlesText.style.transform="scale(1)",this._subtitlesText.innerHTML=n.text.replace(/\n/g,"<br>");}else this._subtitlesText.style.opacity="0",this._subtitlesText.style.transform="scale(0.99)";},eh=function(t){let i=this._embedObj.video.renditions.filter(a=>a.container==t),r=["sd","hd","fhd","qhd","uhd"];return !i||!i.length?void 0:i.reduce((a,o)=>r.indexOf(o.size)>r.indexOf(a.size)?o:a)},th=function(){return this._themeLoaded?this.shadowRoot?.querySelector(`theme-${this._themeLoaded}`)?.shadowRoot??null:null},s0=function(t){if(this._themeMutationObserverRoot===t)return;this._themeMutationObserver?.disconnect();let i=new MutationObserver(()=>{chunkJHSFSCC2_cjs.g(this,H,El).call(this);});i.observe(t,{childList:true,subtree:true}),this._themeMutationObserver=i,this._themeMutationObserverRoot=t;},ih=function(){let t=chunkJHSFSCC2_cjs.d(this,H,th);return t?{menu:t.querySelector("mave-audio-track-menu"),button:t.querySelector("mave-audio-track-menu-button")}:{menu:null,button:null}},El=function(){this._pendingAudioTrackSetup==null&&(this._pendingAudioTrackSetup=requestAnimationFrame(()=>{this._pendingAudioTrackSetup=void 0,chunkJHSFSCC2_cjs.g(this,H,sh).call(this);}));},sh=function(){if(!this.hls)return;let t=chunkJHSFSCC2_cjs.d(this,H,th);t&&chunkJHSFSCC2_cjs.g(this,H,s0).call(this,t);let{menu:i,button:r}=chunkJHSFSCC2_cjs.g(this,H,ih).call(this);if(!i||!r){chunkJHSFSCC2_cjs.g(this,H,El).call(this);return}if(i!==this._currentAudioTrackMenu||!this._cleanupHlsAudioTracks){this._cleanupHlsAudioTracks?.();let o=(c,u)=>{this._hlsAudioTracks=u?.audioTracks??[],chunkJHSFSCC2_cjs.g(this,H,Rn).call(this,this._hlsAudioTracks,this.hls?.audioTrack);},l=(c,u)=>{let h=u?.id??(typeof this.hls?.audioTrack=="number"?this.hls.audioTrack:void 0);chunkJHSFSCC2_cjs.g(this,H,Rn).call(this,this._hlsAudioTracks,h);},d=c=>{if(c.type!==chunkDITZCOYN_cjs.a.MEDIA_AUDIO_TRACK_REQUEST)return;let u=c.detail;if(u==null)return;let h=this._hlsAudioTrackIdMap.get(String(u));h==null||!this.hls||this.hls.audioTrack!==h&&(this.hls.audioTrack=h,chunkJHSFSCC2_cjs.g(this,H,Rn).call(this,this._hlsAudioTracks,h));};i.addEventListener(chunkDITZCOYN_cjs.a.MEDIA_AUDIO_TRACK_REQUEST,d),this.hls.on(ui.Events.AUDIO_TRACKS_UPDATED,o),this.hls.on(ui.Events.AUDIO_TRACK_SWITCHED,l),this._cleanupHlsAudioTracks=()=>{i.removeEventListener(chunkDITZCOYN_cjs.a.MEDIA_AUDIO_TRACK_REQUEST,d),this.hls?.off(ui.Events.AUDIO_TRACKS_UPDATED,o),this.hls?.off(ui.Events.AUDIO_TRACK_SWITCHED,l);},this._currentAudioTrackMenu=i,this.hls.audioTracks?.length&&(this._hlsAudioTracks=this.hls.audioTracks);}let n=(this._hlsAudioTracks&&this._hlsAudioTracks.length?this._hlsAudioTracks:this.hls.audioTracks)??[],a=typeof this.hls.audioTrack=="number"?this.hls.audioTrack:void 0;chunkJHSFSCC2_cjs.g(this,H,Rn).call(this,n,a);},Rn=function(t,i){let{menu:r,button:n}=chunkJHSFSCC2_cjs.g(this,H,ih).call(this);if(!r||!n){chunkJHSFSCC2_cjs.g(this,H,El).call(this);return}if(this._hlsAudioTracks=t??[],this._hlsAudioTrackIdMap.clear(),!t?.length){"tracks"in r&&(r.tracks=[],r.selected=void 0),this._audioTrackCount=0,this.requestUpdate();return}let a=t.map((l,d)=>{let c=l?.id??d,u=String(c);this._hlsAudioTrackIdMap.set(u,c);let h=l?.lang??l?.attrs?.LANGUAGE,m=(l?.name??"").trim()||typeof h=="string"&&h.trim()||`Track ${d+1}`,p=i!=null?c===i:l?.default??d===0;return {id:u,language:h,label:m,enabled:p}});!a.some(l=>l.enabled)&&a.length&&(a[0].enabled=true);let o=a.find(l=>l.enabled)??a[0];"tracks"in r&&(r.tracks=a,r.selected=o?.id),this._audioTrackCount=a.length,this.requestUpdate();},lr=function(){let t=chunkJHSFSCC2_cjs.g(this,H,eh).call(this,"hls");if(t){let i=new URLSearchParams;return i.append("quality",t.size),this.embedController.embedFile("playlist.m3u8",i)}},rh=function(){let t=chunkJHSFSCC2_cjs.g(this,H,eh).call(this,"mp4");return t?this.embedController.embedFile(`h264_${t?.size}.mp4`):this._embedObj.video.original},r0=function(){if(this._embedObj.subtitles.length>0){let t=this.shadowRoot?.querySelector(`theme-${this._themeLoaded}`)?.shadowRoot?.querySelector("media-captions-menu");return t&&new MutationObserver(r=>{r.forEach(()=>{this._subtitlesText&&t.getAttribute("mediasubtitlesshowing")&&(this._subtitlesText.style.opacity="0");});}).observe(t,{attributes:true}),this._embedObj.subtitles.map(i=>{if(this.subtitles&&this.subtitles.includes(i.language)||this.active_subtitle&&this.active_subtitle==i.language||this.subtitles=="all"||(this.subtitles=="original"||this.active_subtitle=="original")&&this._embedObj.video.language==i.language||!this.subtitles)return chunk5NSCV6C2_cjs.c`
1412
+ <track mode="hidden" @cuechange=${chunkJHSFSCC2_cjs.g(this,H,i0)} label=${i.label} kind="subtitles" srclang=${i.language} src=${i.path}></track>
1413
+ `})}},n0=function(){return chunk5NSCV6C2_cjs.c`<track
1414
1414
  label="thumbnails"
1415
1415
  default
1416
1416
  kind="metadata"