@vouchfor/embeds 0.0.0-experiment.d900f80 → 0.0.0-experiment.dce2e9b

Sign up to get free protection for your applications and to get access to all the features.
@@ -1,89 +1,94 @@
1
- var embeds=function(ut){"use strict";var ky=Object.defineProperty;var Cy=(ut,be,le)=>be in ut?ky(ut,be,{enumerable:!0,configurable:!0,writable:!0,value:le}):ut[be]=le;var Jd=(ut,be,le)=>(Cy(ut,typeof be!="symbol"?be+"":be,le),le);function be(r,t){for(var e=0;e<t.length;e++){const i=t[e];if(typeof i!="string"&&!Array.isArray(i)){for(const s in i)if(s!=="default"&&!(s in r)){const n=Object.getOwnPropertyDescriptor(i,s);n&&Object.defineProperty(r,s,n.get?n:{enumerable:!0,get:()=>i[s]})}}}return Object.freeze(Object.defineProperty(r,Symbol.toStringTag,{value:"Module"}))}/**
1
+ var G0=Object.defineProperty;var V0=(At,De,be)=>De in At?G0(At,De,{enumerable:!0,configurable:!0,writable:!0,value:be}):At[De]=be;var Dc=(At,De,be)=>(V0(At,typeof De!="symbol"?De+"":De,be),be);var embeds=function(At){var Ic;"use strict";function De(r,t){for(var e=0;e<t.length;e++){const i=t[e];if(typeof i!="string"&&!Array.isArray(i)){for(const s in i)if(s!=="default"&&!(s in r)){const n=Object.getOwnPropertyDescriptor(i,s);n&&Object.defineProperty(r,s,n.get?n:{enumerable:!0,get:()=>i[s]})}}}return Object.freeze(Object.defineProperty(r,Symbol.toStringTag,{value:"Module"}))}/**
2
2
  * @license
3
3
  * Copyright 2019 Google LLC
4
4
  * SPDX-License-Identifier: BSD-3-Clause
5
- */const le=window,Or=le.ShadowRoot&&(le.ShadyCSS===void 0||le.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,Mr=Symbol(),Ka=new WeakMap;let ja=class{constructor(t,e,i){if(this._$cssResult$=!0,i!==Mr)throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");this.cssText=t,this.t=e}get styleSheet(){let t=this.o;const e=this.t;if(Or&&t===void 0){const i=e!==void 0&&e.length===1;i&&(t=Ka.get(e)),t===void 0&&((this.o=t=new CSSStyleSheet).replaceSync(this.cssText),i&&Ka.set(e,t))}return t}toString(){return this.cssText}};const Oi=r=>new ja(typeof r=="string"?r:r+"",void 0,Mr),Ft=(r,...t)=>{const e=r.length===1?r[0]:t.reduce((i,s,n)=>i+(a=>{if(a._$cssResult$===!0)return a.cssText;if(typeof a=="number")return a;throw Error("Value passed to 'css' function must be a 'css' function result: "+a+". Use 'unsafeCSS' to pass non-literal values, but take care to ensure page security.")})(s)+r[n+1],r[0]);return new ja(e,r,Mr)},sc=(r,t)=>{Or?r.adoptedStyleSheets=t.map(e=>e instanceof CSSStyleSheet?e:e.styleSheet):t.forEach(e=>{const i=document.createElement("style"),s=le.litNonce;s!==void 0&&i.setAttribute("nonce",s),i.textContent=e.cssText,r.appendChild(i)})},Wa=Or?r=>r:r=>r instanceof CSSStyleSheet?(t=>{let e="";for(const i of t.cssRules)e+=i.cssText;return Oi(e)})(r):r;/**
5
+ */const be=globalThis,Cr=be.ShadowRoot&&(be.ShadyCSS===void 0||be.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,Da=Symbol(),xa=new WeakMap;let $c=class{constructor(t,e,i){if(this._$cssResult$=!0,i!==Da)throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");this.cssText=t,this.t=e}get styleSheet(){let t=this.o;const e=this.t;if(Cr&&t===void 0){const i=e!==void 0&&e.length===1;i&&(t=xa.get(e)),t===void 0&&((this.o=t=new CSSStyleSheet).replaceSync(this.cssText),i&&xa.set(e,t))}return t}toString(){return this.cssText}};const Mc=r=>new $c(typeof r=="string"?r:r+"",void 0,Da),Fc=(r,t)=>{if(Cr)r.adoptedStyleSheets=t.map(e=>e instanceof CSSStyleSheet?e:e.styleSheet);else for(const e of t){const i=document.createElement("style"),s=be.litNonce;s!==void 0&&i.setAttribute("nonce",s),i.textContent=e.cssText,r.appendChild(i)}},Pa=Cr?r=>r:r=>r instanceof CSSStyleSheet?(t=>{let e="";for(const i of t.cssRules)e+=i.cssText;return Mc(e)})(r):r;/**
6
6
  * @license
7
7
  * Copyright 2017 Google LLC
8
8
  * SPDX-License-Identifier: BSD-3-Clause
9
- */var $r;const Ss=window,Ya=Ss.trustedTypes,rc=Ya?Ya.emptyScript:"",za=Ss.reactiveElementPolyfillSupport,Fr={toAttribute(r,t){switch(t){case Boolean:r=r?rc:null;break;case Object:case Array:r=r==null?r:JSON.stringify(r)}return r},fromAttribute(r,t){let e=r;switch(t){case Boolean:e=r!==null;break;case Number:e=r===null?null:Number(r);break;case Object:case Array:try{e=JSON.parse(r)}catch{e=null}}return e}},qa=(r,t)=>t!==r&&(t==t||r==r),Nr={attribute:!0,type:String,converter:Fr,reflect:!1,hasChanged:qa},Ur="finalized";let di=class extends HTMLElement{constructor(){super(),this._$Ei=new Map,this.isUpdatePending=!1,this.hasUpdated=!1,this._$El=null,this.u()}static addInitializer(t){var e;this.finalize(),((e=this.h)!==null&&e!==void 0?e:this.h=[]).push(t)}static get observedAttributes(){this.finalize();const t=[];return this.elementProperties.forEach((e,i)=>{const s=this._$Ep(i,e);s!==void 0&&(this._$Ev.set(s,i),t.push(s))}),t}static createProperty(t,e=Nr){if(e.state&&(e.attribute=!1),this.finalize(),this.elementProperties.set(t,e),!e.noAccessor&&!this.prototype.hasOwnProperty(t)){const i=typeof t=="symbol"?Symbol():"__"+t,s=this.getPropertyDescriptor(t,i,e);s!==void 0&&Object.defineProperty(this.prototype,t,s)}}static getPropertyDescriptor(t,e,i){return{get(){return this[e]},set(s){const n=this[t];this[e]=s,this.requestUpdate(t,n,i)},configurable:!0,enumerable:!0}}static getPropertyOptions(t){return this.elementProperties.get(t)||Nr}static finalize(){if(this.hasOwnProperty(Ur))return!1;this[Ur]=!0;const t=Object.getPrototypeOf(this);if(t.finalize(),t.h!==void 0&&(this.h=[...t.h]),this.elementProperties=new Map(t.elementProperties),this._$Ev=new Map,this.hasOwnProperty("properties")){const e=this.properties,i=[...Object.getOwnPropertyNames(e),...Object.getOwnPropertySymbols(e)];for(const s of i)this.createProperty(s,e[s])}return this.elementStyles=this.finalizeStyles(this.styles),!0}static finalizeStyles(t){const e=[];if(Array.isArray(t)){const i=new Set(t.flat(1/0).reverse());for(const s of i)e.unshift(Wa(s))}else t!==void 0&&e.push(Wa(t));return e}static _$Ep(t,e){const i=e.attribute;return i===!1?void 0:typeof i=="string"?i:typeof t=="string"?t.toLowerCase():void 0}u(){var t;this._$E_=new Promise(e=>this.enableUpdating=e),this._$AL=new Map,this._$Eg(),this.requestUpdate(),(t=this.constructor.h)===null||t===void 0||t.forEach(e=>e(this))}addController(t){var e,i;((e=this._$ES)!==null&&e!==void 0?e:this._$ES=[]).push(t),this.renderRoot!==void 0&&this.isConnected&&((i=t.hostConnected)===null||i===void 0||i.call(t))}removeController(t){var e;(e=this._$ES)===null||e===void 0||e.splice(this._$ES.indexOf(t)>>>0,1)}_$Eg(){this.constructor.elementProperties.forEach((t,e)=>{this.hasOwnProperty(e)&&(this._$Ei.set(e,this[e]),delete this[e])})}createRenderRoot(){var t;const e=(t=this.shadowRoot)!==null&&t!==void 0?t:this.attachShadow(this.constructor.shadowRootOptions);return sc(e,this.constructor.elementStyles),e}connectedCallback(){var t;this.renderRoot===void 0&&(this.renderRoot=this.createRenderRoot()),this.enableUpdating(!0),(t=this._$ES)===null||t===void 0||t.forEach(e=>{var i;return(i=e.hostConnected)===null||i===void 0?void 0:i.call(e)})}enableUpdating(t){}disconnectedCallback(){var t;(t=this._$ES)===null||t===void 0||t.forEach(e=>{var i;return(i=e.hostDisconnected)===null||i===void 0?void 0:i.call(e)})}attributeChangedCallback(t,e,i){this._$AK(t,i)}_$EO(t,e,i=Nr){var s;const n=this.constructor._$Ep(t,i);if(n!==void 0&&i.reflect===!0){const a=(((s=i.converter)===null||s===void 0?void 0:s.toAttribute)!==void 0?i.converter:Fr).toAttribute(e,i.type);this._$El=t,a==null?this.removeAttribute(n):this.setAttribute(n,a),this._$El=null}}_$AK(t,e){var i;const s=this.constructor,n=s._$Ev.get(t);if(n!==void 0&&this._$El!==n){const a=s.getPropertyOptions(n),o=typeof a.converter=="function"?{fromAttribute:a.converter}:((i=a.converter)===null||i===void 0?void 0:i.fromAttribute)!==void 0?a.converter:Fr;this._$El=n,this[n]=o.fromAttribute(e,a.type),this._$El=null}}requestUpdate(t,e,i){let s=!0;t!==void 0&&(((i=i||this.constructor.getPropertyOptions(t)).hasChanged||qa)(this[t],e)?(this._$AL.has(t)||this._$AL.set(t,e),i.reflect===!0&&this._$El!==t&&(this._$EC===void 0&&(this._$EC=new Map),this._$EC.set(t,i))):s=!1),!this.isUpdatePending&&s&&(this._$E_=this._$Ej())}async _$Ej(){this.isUpdatePending=!0;try{await this._$E_}catch(e){Promise.reject(e)}const t=this.scheduleUpdate();return t!=null&&await t,!this.isUpdatePending}scheduleUpdate(){return this.performUpdate()}performUpdate(){var t;if(!this.isUpdatePending)return;this.hasUpdated,this._$Ei&&(this._$Ei.forEach((s,n)=>this[n]=s),this._$Ei=void 0);let e=!1;const i=this._$AL;try{e=this.shouldUpdate(i),e?(this.willUpdate(i),(t=this._$ES)===null||t===void 0||t.forEach(s=>{var n;return(n=s.hostUpdate)===null||n===void 0?void 0:n.call(s)}),this.update(i)):this._$Ek()}catch(s){throw e=!1,this._$Ek(),s}e&&this._$AE(i)}willUpdate(t){}_$AE(t){var e;(e=this._$ES)===null||e===void 0||e.forEach(i=>{var s;return(s=i.hostUpdated)===null||s===void 0?void 0:s.call(i)}),this.hasUpdated||(this.hasUpdated=!0,this.firstUpdated(t)),this.updated(t)}_$Ek(){this._$AL=new Map,this.isUpdatePending=!1}get updateComplete(){return this.getUpdateComplete()}getUpdateComplete(){return this._$E_}shouldUpdate(t){return!0}update(t){this._$EC!==void 0&&(this._$EC.forEach((e,i)=>this._$EO(i,this[i],e)),this._$EC=void 0),this._$Ek()}updated(t){}firstUpdated(t){}};di[Ur]=!0,di.elementProperties=new Map,di.elementStyles=[],di.shadowRootOptions={mode:"open"},za==null||za({ReactiveElement:di}),(($r=Ss.reactiveElementVersions)!==null&&$r!==void 0?$r:Ss.reactiveElementVersions=[]).push("1.6.2");/**
9
+ */const{is:Nc,defineProperty:Uc,getOwnPropertyDescriptor:Bc,getOwnPropertyNames:Hc,getOwnPropertySymbols:Gc,getPrototypeOf:Vc}=Object,Ue=globalThis,Oa=Ue.trustedTypes,Kc=Oa?Oa.emptyScript:"",Dr=Ue.reactiveElementPolyfillSupport,Hi=(r,t)=>r,Ds={toAttribute(r,t){switch(t){case Boolean:r=r?Kc:null;break;case Object:case Array:r=r==null?r:JSON.stringify(r)}return r},fromAttribute(r,t){let e=r;switch(t){case Boolean:e=r!==null;break;case Number:e=r===null?null:Number(r);break;case Object:case Array:try{e=JSON.parse(r)}catch{e=null}}return e}},xr=(r,t)=>!Nc(r,t),$a={attribute:!0,type:String,converter:Ds,reflect:!1,hasChanged:xr};Symbol.metadata??(Symbol.metadata=Symbol("metadata")),Ue.litPropertyMetadata??(Ue.litPropertyMetadata=new WeakMap);let Gi=class extends HTMLElement{static addInitializer(t){this._$Ei(),(this.l??(this.l=[])).push(t)}static get observedAttributes(){return this.finalize(),this._$Eh&&[...this._$Eh.keys()]}static createProperty(t,e=$a){if(e.state&&(e.attribute=!1),this._$Ei(),this.elementProperties.set(t,e),!e.noAccessor){const i=Symbol(),s=this.getPropertyDescriptor(t,i,e);s!==void 0&&Uc(this.prototype,t,s)}}static getPropertyDescriptor(t,e,i){const{get:s,set:n}=Bc(this.prototype,t)??{get(){return this[e]},set(a){this[e]=a}};return{get(){return s==null?void 0:s.call(this)},set(a){const o=s==null?void 0:s.call(this);n.call(this,a),this.requestUpdate(t,o,i)},configurable:!0,enumerable:!0}}static getPropertyOptions(t){return this.elementProperties.get(t)??$a}static _$Ei(){if(this.hasOwnProperty(Hi("elementProperties")))return;const t=Vc(this);t.finalize(),t.l!==void 0&&(this.l=[...t.l]),this.elementProperties=new Map(t.elementProperties)}static finalize(){if(this.hasOwnProperty(Hi("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(Hi("properties"))){const e=this.properties,i=[...Hc(e),...Gc(e)];for(const s of i)this.createProperty(s,e[s])}const t=this[Symbol.metadata];if(t!==null){const e=litPropertyMetadata.get(t);if(e!==void 0)for(const[i,s]of e)this.elementProperties.set(i,s)}this._$Eh=new Map;for(const[e,i]of this.elementProperties){const s=this._$Eu(e,i);s!==void 0&&this._$Eh.set(s,e)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(t){const e=[];if(Array.isArray(t)){const i=new Set(t.flat(1/0).reverse());for(const s of i)e.unshift(Pa(s))}else t!==void 0&&e.push(Pa(t));return e}static _$Eu(t,e){const i=e.attribute;return i===!1?void 0:typeof i=="string"?i:typeof t=="string"?t.toLowerCase():void 0}constructor(){super(),this._$Ep=void 0,this.isUpdatePending=!1,this.hasUpdated=!1,this._$Em=null,this._$Ev()}_$Ev(){var t;this._$Eg=new Promise(e=>this.enableUpdating=e),this._$AL=new Map,this._$ES(),this.requestUpdate(),(t=this.constructor.l)==null||t.forEach(e=>e(this))}addController(t){var e;(this._$E_??(this._$E_=new Set)).add(t),this.renderRoot!==void 0&&this.isConnected&&((e=t.hostConnected)==null||e.call(t))}removeController(t){var e;(e=this._$E_)==null||e.delete(t)}_$ES(){const t=new Map,e=this.constructor.elementProperties;for(const i of e.keys())this.hasOwnProperty(i)&&(t.set(i,this[i]),delete this[i]);t.size>0&&(this._$Ep=t)}createRenderRoot(){const t=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return Fc(t,this.constructor.elementStyles),t}connectedCallback(){var t;this.renderRoot??(this.renderRoot=this.createRenderRoot()),this.enableUpdating(!0),(t=this._$E_)==null||t.forEach(e=>{var i;return(i=e.hostConnected)==null?void 0:i.call(e)})}enableUpdating(t){}disconnectedCallback(){var t;(t=this._$E_)==null||t.forEach(e=>{var i;return(i=e.hostDisconnected)==null?void 0:i.call(e)})}attributeChangedCallback(t,e,i){this._$AK(t,i)}_$EO(t,e){var n;const i=this.constructor.elementProperties.get(t),s=this.constructor._$Eu(t,i);if(s!==void 0&&i.reflect===!0){const a=(((n=i.converter)==null?void 0:n.toAttribute)!==void 0?i.converter:Ds).toAttribute(e,i.type);this._$Em=t,a==null?this.removeAttribute(s):this.setAttribute(s,a),this._$Em=null}}_$AK(t,e){var n;const i=this.constructor,s=i._$Eh.get(t);if(s!==void 0&&this._$Em!==s){const a=i.getPropertyOptions(s),o=typeof a.converter=="function"?{fromAttribute:a.converter}:((n=a.converter)==null?void 0:n.fromAttribute)!==void 0?a.converter:Ds;this._$Em=s,this[s]=o.fromAttribute(e,a.type),this._$Em=null}}requestUpdate(t,e,i,s=!1,n){if(t!==void 0){if(i??(i=this.constructor.getPropertyOptions(t)),!(i.hasChanged??xr)(s?n:this[t],e))return;this.C(t,e,i)}this.isUpdatePending===!1&&(this._$Eg=this._$EP())}C(t,e,i){this._$AL.has(t)||this._$AL.set(t,e),i.reflect===!0&&this._$Em!==t&&(this._$Ej??(this._$Ej=new Set)).add(t)}async _$EP(){this.isUpdatePending=!0;try{await this._$Eg}catch(e){Promise.reject(e)}const t=this.scheduleUpdate();return t!=null&&await t,!this.isUpdatePending}scheduleUpdate(){return this.performUpdate()}performUpdate(){var i;if(!this.isUpdatePending)return;if(!this.hasUpdated){if(this.renderRoot??(this.renderRoot=this.createRenderRoot()),this._$Ep){for(const[n,a]of this._$Ep)this[n]=a;this._$Ep=void 0}const s=this.constructor.elementProperties;if(s.size>0)for(const[n,a]of s)a.wrapped!==!0||this._$AL.has(n)||this[n]===void 0||this.C(n,this[n],a)}let t=!1;const e=this._$AL;try{t=this.shouldUpdate(e),t?(this.willUpdate(e),(i=this._$E_)==null||i.forEach(s=>{var n;return(n=s.hostUpdate)==null?void 0:n.call(s)}),this.update(e)):this._$ET()}catch(s){throw t=!1,this._$ET(),s}t&&this._$AE(e)}willUpdate(t){}_$AE(t){var e;(e=this._$E_)==null||e.forEach(i=>{var s;return(s=i.hostUpdated)==null?void 0:s.call(i)}),this.hasUpdated||(this.hasUpdated=!0,this.firstUpdated(t)),this.updated(t)}_$ET(){this._$AL=new Map,this.isUpdatePending=!1}get updateComplete(){return this.getUpdateComplete()}getUpdateComplete(){return this._$Eg}shouldUpdate(t){return!0}update(t){this._$Ej&&(this._$Ej=this._$Ej.forEach(e=>this._$EO(e,this[e]))),this._$ET()}updated(t){}firstUpdated(t){}};Gi.elementStyles=[],Gi.shadowRootOptions={mode:"open"},Gi[Hi("elementProperties")]=new Map,Gi[Hi("finalized")]=new Map,Dr==null||Dr({ReactiveElement:Gi}),(Ue.reactiveElementVersions??(Ue.reactiveElementVersions=[])).push("2.0.2");/**
10
10
  * @license
11
11
  * Copyright 2017 Google LLC
12
12
  * SPDX-License-Identifier: BSD-3-Clause
13
- */var Br;const Ls=window,ci=Ls.trustedTypes,Xa=ci?ci.createPolicy("lit-html",{createHTML:r=>r}):void 0,Hr="$lit$",ke=`lit$${(Math.random()+"").slice(9)}$`,Qa="?"+ke,nc=`<${Qa}>`,He=document,Rs=()=>He.createComment(""),Mi=r=>r===null||typeof r!="object"&&typeof r!="function",Za=Array.isArray,ac=r=>Za(r)||typeof(r==null?void 0:r[Symbol.iterator])=="function",Gr=`[
14
- \f\r]`,$i=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,Ja=/-->/g,to=/>/g,Ge=RegExp(`>|${Gr}(?:([^\\s"'>=/]+)(${Gr}*=${Gr}*(?:[^
15
- \f\r"'\`<>=]|("|')|))|$)`,"g"),eo=/'/g,io=/"/g,so=/^(?:script|style|textarea|title)$/i,Fi=Symbol.for("lit-noChange"),pt=Symbol.for("lit-nothing"),ro=new WeakMap,Ve=He.createTreeWalker(He,129,null,!1);function no(r,t){if(!Array.isArray(r)||!r.hasOwnProperty("raw"))throw Error("invalid template strings array");return Xa!==void 0?Xa.createHTML(t):t}const oc=(r,t)=>{const e=r.length-1,i=[];let s,n=t===2?"<svg>":"",a=$i;for(let o=0;o<e;o++){const l=r[o];let h,d,c=-1,u=0;for(;u<l.length&&(a.lastIndex=u,d=a.exec(l),d!==null);)u=a.lastIndex,a===$i?d[1]==="!--"?a=Ja:d[1]!==void 0?a=to:d[2]!==void 0?(so.test(d[2])&&(s=RegExp("</"+d[2],"g")),a=Ge):d[3]!==void 0&&(a=Ge):a===Ge?d[0]===">"?(a=s??$i,c=-1):d[1]===void 0?c=-2:(c=a.lastIndex-d[2].length,h=d[1],a=d[3]===void 0?Ge:d[3]==='"'?io:eo):a===io||a===eo?a=Ge:a===Ja||a===to?a=$i:(a=Ge,s=void 0);const f=a===Ge&&r[o+1].startsWith("/>")?" ":"";n+=a===$i?l+nc:c>=0?(i.push(h),l.slice(0,c)+Hr+l.slice(c)+ke+f):l+ke+(c===-2?(i.push(void 0),o):f)}return[no(r,n+(r[e]||"<?>")+(t===2?"</svg>":"")),i]};let Vr=class tc{constructor({strings:t,_$litType$:e},i){let s;this.parts=[];let n=0,a=0;const o=t.length-1,l=this.parts,[h,d]=oc(t,e);if(this.el=tc.createElement(h,i),Ve.currentNode=this.el.content,e===2){const c=this.el.content,u=c.firstChild;u.remove(),c.append(...u.childNodes)}for(;(s=Ve.nextNode())!==null&&l.length<o;){if(s.nodeType===1){if(s.hasAttributes()){const c=[];for(const u of s.getAttributeNames())if(u.endsWith(Hr)||u.startsWith(ke)){const f=d[a++];if(c.push(u),f!==void 0){const p=s.getAttribute(f.toLowerCase()+Hr).split(ke),g=/([.?@])?(.*)/.exec(f);l.push({type:1,index:n,name:g[2],strings:p,ctor:g[1]==="."?hc:g[1]==="?"?cc:g[1]==="@"?uc:_s})}else l.push({type:6,index:n})}for(const u of c)s.removeAttribute(u)}if(so.test(s.tagName)){const c=s.textContent.split(ke),u=c.length-1;if(u>0){s.textContent=ci?ci.emptyScript:"";for(let f=0;f<u;f++)s.append(c[f],Rs()),Ve.nextNode(),l.push({type:2,index:++n});s.append(c[u],Rs())}}}else if(s.nodeType===8)if(s.data===Qa)l.push({type:2,index:n});else{let c=-1;for(;(c=s.data.indexOf(ke,c+1))!==-1;)l.push({type:7,index:n}),c+=ke.length-1}n++}}static createElement(t,e){const i=He.createElement("template");return i.innerHTML=t,i}};function ui(r,t,e=r,i){var s,n,a,o;if(t===Fi)return t;let l=i!==void 0?(s=e._$Co)===null||s===void 0?void 0:s[i]:e._$Cl;const h=Mi(t)?void 0:t._$litDirective$;return(l==null?void 0:l.constructor)!==h&&((n=l==null?void 0:l._$AO)===null||n===void 0||n.call(l,!1),h===void 0?l=void 0:(l=new h(r),l._$AT(r,e,i)),i!==void 0?((a=(o=e)._$Co)!==null&&a!==void 0?a:o._$Co=[])[i]=l:e._$Cl=l),l!==void 0&&(t=ui(r,l._$AS(r,t.values),l,i)),t}let lc=class{constructor(t,e){this._$AV=[],this._$AN=void 0,this._$AD=t,this._$AM=e}get parentNode(){return this._$AM.parentNode}get _$AU(){return this._$AM._$AU}u(t){var e;const{el:{content:i},parts:s}=this._$AD,n=((e=t==null?void 0:t.creationScope)!==null&&e!==void 0?e:He).importNode(i,!0);Ve.currentNode=n;let a=Ve.nextNode(),o=0,l=0,h=s[0];for(;h!==void 0;){if(o===h.index){let d;h.type===2?d=new ao(a,a.nextSibling,this,t):h.type===1?d=new h.ctor(a,h.name,h.strings,this,t):h.type===6&&(d=new fc(a,this,t)),this._$AV.push(d),h=s[++l]}o!==(h==null?void 0:h.index)&&(a=Ve.nextNode(),o++)}return Ve.currentNode=He,n}v(t){let e=0;for(const i of this._$AV)i!==void 0&&(i.strings!==void 0?(i._$AI(t,i,e),e+=i.strings.length-2):i._$AI(t[e])),e++}},ao=class ec{constructor(t,e,i,s){var n;this.type=2,this._$AH=pt,this._$AN=void 0,this._$AA=t,this._$AB=e,this._$AM=i,this.options=s,this._$Cp=(n=s==null?void 0:s.isConnected)===null||n===void 0||n}get _$AU(){var t,e;return(e=(t=this._$AM)===null||t===void 0?void 0:t._$AU)!==null&&e!==void 0?e:this._$Cp}get parentNode(){let t=this._$AA.parentNode;const e=this._$AM;return e!==void 0&&(t==null?void 0:t.nodeType)===11&&(t=e.parentNode),t}get startNode(){return this._$AA}get endNode(){return this._$AB}_$AI(t,e=this){t=ui(this,t,e),Mi(t)?t===pt||t==null||t===""?(this._$AH!==pt&&this._$AR(),this._$AH=pt):t!==this._$AH&&t!==Fi&&this._(t):t._$litType$!==void 0?this.g(t):t.nodeType!==void 0?this.$(t):ac(t)?this.T(t):this._(t)}k(t){return this._$AA.parentNode.insertBefore(t,this._$AB)}$(t){this._$AH!==t&&(this._$AR(),this._$AH=this.k(t))}_(t){this._$AH!==pt&&Mi(this._$AH)?this._$AA.nextSibling.data=t:this.$(He.createTextNode(t)),this._$AH=t}g(t){var e;const{values:i,_$litType$:s}=t,n=typeof s=="number"?this._$AC(t):(s.el===void 0&&(s.el=Vr.createElement(no(s.h,s.h[0]),this.options)),s);if(((e=this._$AH)===null||e===void 0?void 0:e._$AD)===n)this._$AH.v(i);else{const a=new lc(n,this),o=a.u(this.options);a.v(i),this.$(o),this._$AH=a}}_$AC(t){let e=ro.get(t.strings);return e===void 0&&ro.set(t.strings,e=new Vr(t)),e}T(t){Za(this._$AH)||(this._$AH=[],this._$AR());const e=this._$AH;let i,s=0;for(const n of t)s===e.length?e.push(i=new ec(this.k(Rs()),this.k(Rs()),this,this.options)):i=e[s],i._$AI(n),s++;s<e.length&&(this._$AR(i&&i._$AB.nextSibling,s),e.length=s)}_$AR(t=this._$AA.nextSibling,e){var i;for((i=this._$AP)===null||i===void 0||i.call(this,!1,!0,e);t&&t!==this._$AB;){const s=t.nextSibling;t.remove(),t=s}}setConnected(t){var e;this._$AM===void 0&&(this._$Cp=t,(e=this._$AP)===null||e===void 0||e.call(this,t))}},_s=class{constructor(t,e,i,s,n){this.type=1,this._$AH=pt,this._$AN=void 0,this.element=t,this.name=e,this._$AM=s,this.options=n,i.length>2||i[0]!==""||i[1]!==""?(this._$AH=Array(i.length-1).fill(new String),this.strings=i):this._$AH=pt}get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}_$AI(t,e=this,i,s){const n=this.strings;let a=!1;if(n===void 0)t=ui(this,t,e,0),a=!Mi(t)||t!==this._$AH&&t!==Fi,a&&(this._$AH=t);else{const o=t;let l,h;for(t=n[0],l=0;l<n.length-1;l++)h=ui(this,o[i+l],e,l),h===Fi&&(h=this._$AH[l]),a||(a=!Mi(h)||h!==this._$AH[l]),h===pt?t=pt:t!==pt&&(t+=(h??"")+n[l+1]),this._$AH[l]=h}a&&!s&&this.j(t)}j(t){t===pt?this.element.removeAttribute(this.name):this.element.setAttribute(this.name,t??"")}},hc=class extends _s{constructor(){super(...arguments),this.type=3}j(t){this.element[this.name]=t===pt?void 0:t}};const dc=ci?ci.emptyScript:"";let cc=class extends _s{constructor(){super(...arguments),this.type=4}j(t){t&&t!==pt?this.element.setAttribute(this.name,dc):this.element.removeAttribute(this.name)}},uc=class extends _s{constructor(t,e,i,s,n){super(t,e,i,s,n),this.type=5}_$AI(t,e=this){var i;if((t=(i=ui(this,t,e,0))!==null&&i!==void 0?i:pt)===Fi)return;const s=this._$AH,n=t===pt&&s!==pt||t.capture!==s.capture||t.once!==s.once||t.passive!==s.passive,a=t!==pt&&(s===pt||n);n&&this.element.removeEventListener(this.name,this,s),a&&this.element.addEventListener(this.name,this,t),this._$AH=t}handleEvent(t){var e,i;typeof this._$AH=="function"?this._$AH.call((i=(e=this.options)===null||e===void 0?void 0:e.host)!==null&&i!==void 0?i:this.element,t):this._$AH.handleEvent(t)}},fc=class{constructor(t,e,i){this.element=t,this.type=6,this._$AN=void 0,this._$AM=e,this.options=i}get _$AU(){return this._$AM._$AU}_$AI(t){ui(this,t)}};const oo=Ls.litHtmlPolyfillSupport;oo==null||oo(Vr,ao),((Br=Ls.litHtmlVersions)!==null&&Br!==void 0?Br:Ls.litHtmlVersions=[]).push("2.8.0");/**
13
+ */const Vi=globalThis,xs=Vi.trustedTypes,Ma=xs?xs.createPolicy("lit-html",{createHTML:r=>r}):void 0,Pr="$lit$",xe=`lit$${(Math.random()+"").slice(9)}$`,Or="?"+xe,jc=`<${Or}>`,Xe=document,Ps=()=>Xe.createComment(""),Ki=r=>r===null||typeof r!="object"&&typeof r!="function",Fa=Array.isArray,Na=r=>Fa(r)||typeof(r==null?void 0:r[Symbol.iterator])=="function",$r=`[
14
+ \f\r]`,ji=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,Ua=/-->/g,Ba=/>/g,Qe=RegExp(`>|${$r}(?:([^\\s"'>=/]+)(${$r}*=${$r}*(?:[^
15
+ \f\r"'\`<>=]|("|')|))|$)`,"g"),Ha=/'/g,Ga=/"/g,Va=/^(?:script|style|textarea|title)$/i,Ze=Symbol.for("lit-noChange"),kt=Symbol.for("lit-nothing"),Ka=new WeakMap,Je=Xe.createTreeWalker(Xe,129);function ja(r,t){if(!Array.isArray(r)||!r.hasOwnProperty("raw"))throw Error("invalid template strings array");return Ma!==void 0?Ma.createHTML(t):t}const Wa=(r,t)=>{const e=r.length-1,i=[];let s,n=t===2?"<svg>":"",a=ji;for(let o=0;o<e;o++){const l=r[o];let h,c,d=-1,u=0;for(;u<l.length&&(a.lastIndex=u,c=a.exec(l),c!==null);)u=a.lastIndex,a===ji?c[1]==="!--"?a=Ua:c[1]!==void 0?a=Ba:c[2]!==void 0?(Va.test(c[2])&&(s=RegExp("</"+c[2],"g")),a=Qe):c[3]!==void 0&&(a=Qe):a===Qe?c[0]===">"?(a=s??ji,d=-1):c[1]===void 0?d=-2:(d=a.lastIndex-c[2].length,h=c[1],a=c[3]===void 0?Qe:c[3]==='"'?Ga:Ha):a===Ga||a===Ha?a=Qe:a===Ua||a===Ba?a=ji:(a=Qe,s=void 0);const f=a===Qe&&r[o+1].startsWith("/>")?" ":"";n+=a===ji?l+jc:d>=0?(i.push(h),l.slice(0,d)+Pr+l.slice(d)+xe+f):l+xe+(d===-2?o:f)}return[ja(r,n+(r[e]||"<?>")+(t===2?"</svg>":"")),i]};let Mr=class xc{constructor({strings:t,_$litType$:e},i){let s;this.parts=[];let n=0,a=0;const o=t.length-1,l=this.parts,[h,c]=Wa(t,e);if(this.el=xc.createElement(h,i),Je.currentNode=this.el.content,e===2){const d=this.el.content.firstChild;d.replaceWith(...d.childNodes)}for(;(s=Je.nextNode())!==null&&l.length<o;){if(s.nodeType===1){if(s.hasAttributes())for(const d of s.getAttributeNames())if(d.endsWith(Pr)){const u=c[a++],f=s.getAttribute(d).split(xe),p=/([.?@])?(.*)/.exec(u);l.push({type:1,index:n,name:p[2],strings:f,ctor:p[1]==="."?za:p[1]==="?"?qa:p[1]==="@"?Xa:Wi}),s.removeAttribute(d)}else d.startsWith(xe)&&(l.push({type:6,index:n}),s.removeAttribute(d));if(Va.test(s.tagName)){const d=s.textContent.split(xe),u=d.length-1;if(u>0){s.textContent=xs?xs.emptyScript:"";for(let f=0;f<u;f++)s.append(d[f],Ps()),Je.nextNode(),l.push({type:2,index:++n});s.append(d[u],Ps())}}}else if(s.nodeType===8)if(s.data===Or)l.push({type:2,index:n});else{let d=-1;for(;(d=s.data.indexOf(xe,d+1))!==-1;)l.push({type:7,index:n}),d+=xe.length-1}n++}}static createElement(t,e){const i=Xe.createElement("template");return i.innerHTML=t,i}};function ti(r,t,e=r,i){var a,o;if(t===Ze)return t;let s=i!==void 0?(a=e._$Co)==null?void 0:a[i]:e._$Cl;const n=Ki(t)?void 0:t._$litDirective$;return(s==null?void 0:s.constructor)!==n&&((o=s==null?void 0:s._$AO)==null||o.call(s,!1),n===void 0?s=void 0:(s=new n(r),s._$AT(r,e,i)),i!==void 0?(e._$Co??(e._$Co=[]))[i]=s:e._$Cl=s),s!==void 0&&(t=ti(r,s._$AS(r,t.values),s,i)),t}let Ya=class{constructor(t,e){this._$AV=[],this._$AN=void 0,this._$AD=t,this._$AM=e}get parentNode(){return this._$AM.parentNode}get _$AU(){return this._$AM._$AU}u(t){const{el:{content:e},parts:i}=this._$AD,s=((t==null?void 0:t.creationScope)??Xe).importNode(e,!0);Je.currentNode=s;let n=Je.nextNode(),a=0,o=0,l=i[0];for(;l!==void 0;){if(a===l.index){let h;l.type===2?h=new Fr(n,n.nextSibling,this,t):l.type===1?h=new l.ctor(n,l.name,l.strings,this,t):l.type===6&&(h=new Qa(n,this,t)),this._$AV.push(h),l=i[++o]}a!==(l==null?void 0:l.index)&&(n=Je.nextNode(),a++)}return Je.currentNode=Xe,s}p(t){let e=0;for(const i of this._$AV)i!==void 0&&(i.strings!==void 0?(i._$AI(t,i,e),e+=i.strings.length-2):i._$AI(t[e])),e++}},Fr=class Pc{get _$AU(){var t;return((t=this._$AM)==null?void 0:t._$AU)??this._$Cv}constructor(t,e,i,s){this.type=2,this._$AH=kt,this._$AN=void 0,this._$AA=t,this._$AB=e,this._$AM=i,this.options=s,this._$Cv=(s==null?void 0:s.isConnected)??!0}get parentNode(){let t=this._$AA.parentNode;const e=this._$AM;return e!==void 0&&(t==null?void 0:t.nodeType)===11&&(t=e.parentNode),t}get startNode(){return this._$AA}get endNode(){return this._$AB}_$AI(t,e=this){t=ti(this,t,e),Ki(t)?t===kt||t==null||t===""?(this._$AH!==kt&&this._$AR(),this._$AH=kt):t!==this._$AH&&t!==Ze&&this._(t):t._$litType$!==void 0?this.g(t):t.nodeType!==void 0?this.$(t):Na(t)?this.T(t):this._(t)}k(t){return this._$AA.parentNode.insertBefore(t,this._$AB)}$(t){this._$AH!==t&&(this._$AR(),this._$AH=this.k(t))}_(t){this._$AH!==kt&&Ki(this._$AH)?this._$AA.nextSibling.data=t:this.$(Xe.createTextNode(t)),this._$AH=t}g(t){var n;const{values:e,_$litType$:i}=t,s=typeof i=="number"?this._$AC(t):(i.el===void 0&&(i.el=Mr.createElement(ja(i.h,i.h[0]),this.options)),i);if(((n=this._$AH)==null?void 0:n._$AD)===s)this._$AH.p(e);else{const a=new Ya(s,this),o=a.u(this.options);a.p(e),this.$(o),this._$AH=a}}_$AC(t){let e=Ka.get(t.strings);return e===void 0&&Ka.set(t.strings,e=new Mr(t)),e}T(t){Fa(this._$AH)||(this._$AH=[],this._$AR());const e=this._$AH;let i,s=0;for(const n of t)s===e.length?e.push(i=new Pc(this.k(Ps()),this.k(Ps()),this,this.options)):i=e[s],i._$AI(n),s++;s<e.length&&(this._$AR(i&&i._$AB.nextSibling,s),e.length=s)}_$AR(t=this._$AA.nextSibling,e){var i;for((i=this._$AP)==null?void 0:i.call(this,!1,!0,e);t&&t!==this._$AB;){const s=t.nextSibling;t.remove(),t=s}}setConnected(t){var e;this._$AM===void 0&&(this._$Cv=t,(e=this._$AP)==null||e.call(this,t))}},Wi=class{get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}constructor(t,e,i,s,n){this.type=1,this._$AH=kt,this._$AN=void 0,this.element=t,this.name=e,this._$AM=s,this.options=n,i.length>2||i[0]!==""||i[1]!==""?(this._$AH=Array(i.length-1).fill(new String),this.strings=i):this._$AH=kt}_$AI(t,e=this,i,s){const n=this.strings;let a=!1;if(n===void 0)t=ti(this,t,e,0),a=!Ki(t)||t!==this._$AH&&t!==Ze,a&&(this._$AH=t);else{const o=t;let l,h;for(t=n[0],l=0;l<n.length-1;l++)h=ti(this,o[i+l],e,l),h===Ze&&(h=this._$AH[l]),a||(a=!Ki(h)||h!==this._$AH[l]),h===kt?t=kt:t!==kt&&(t+=(h??"")+n[l+1]),this._$AH[l]=h}a&&!s&&this.O(t)}O(t){t===kt?this.element.removeAttribute(this.name):this.element.setAttribute(this.name,t??"")}},za=class extends Wi{constructor(){super(...arguments),this.type=3}O(t){this.element[this.name]=t===kt?void 0:t}},qa=class extends Wi{constructor(){super(...arguments),this.type=4}O(t){this.element.toggleAttribute(this.name,!!t&&t!==kt)}},Xa=class extends Wi{constructor(t,e,i,s,n){super(t,e,i,s,n),this.type=5}_$AI(t,e=this){if((t=ti(this,t,e,0)??kt)===Ze)return;const i=this._$AH,s=t===kt&&i!==kt||t.capture!==i.capture||t.once!==i.once||t.passive!==i.passive,n=t!==kt&&(i===kt||s);s&&this.element.removeEventListener(this.name,this,i),n&&this.element.addEventListener(this.name,this,t),this._$AH=t}handleEvent(t){var e;typeof this._$AH=="function"?this._$AH.call(((e=this.options)==null?void 0:e.host)??this.element,t):this._$AH.handleEvent(t)}},Qa=class{constructor(t,e,i){this.element=t,this.type=6,this._$AN=void 0,this._$AM=e,this.options=i}get _$AU(){return this._$AM._$AU}_$AI(t){ti(this,t)}};const Wc={j:Pr,P:xe,A:Or,C:1,M:Wa,L:Ya,R:Na,V:ti,D:Fr,I:Wi,H:qa,N:Xa,U:za,B:Qa},Nr=Vi.litHtmlPolyfillSupport;Nr==null||Nr(Mr,Fr),(Vi.litHtmlVersions??(Vi.litHtmlVersions=[])).push("3.1.0");/**
16
+ * @license
17
+ * Copyright 2019 Google LLC
18
+ * SPDX-License-Identifier: BSD-3-Clause
19
+ */const Os=globalThis,Ur=Os.ShadowRoot&&(Os.ShadyCSS===void 0||Os.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,Br=Symbol(),Za=new WeakMap;let Ja=class{constructor(t,e,i){if(this._$cssResult$=!0,i!==Br)throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");this.cssText=t,this.t=e}get styleSheet(){let t=this.o;const e=this.t;if(Ur&&t===void 0){const i=e!==void 0&&e.length===1;i&&(t=Za.get(e)),t===void 0&&((this.o=t=new CSSStyleSheet).replaceSync(this.cssText),i&&Za.set(e,t))}return t}toString(){return this.cssText}};const Yi=r=>new Ja(typeof r=="string"?r:r+"",void 0,Br),jt=(r,...t)=>{const e=r.length===1?r[0]:t.reduce((i,s,n)=>i+(a=>{if(a._$cssResult$===!0)return a.cssText;if(typeof a=="number")return a;throw Error("Value passed to 'css' function must be a 'css' function result: "+a+". Use 'unsafeCSS' to pass non-literal values, but take care to ensure page security.")})(s)+r[n+1],r[0]);return new Ja(e,r,Br)},Yc=(r,t)=>{if(Ur)r.adoptedStyleSheets=t.map(e=>e instanceof CSSStyleSheet?e:e.styleSheet);else for(const e of t){const i=document.createElement("style"),s=Os.litNonce;s!==void 0&&i.setAttribute("nonce",s),i.textContent=e.cssText,r.appendChild(i)}},to=Ur?r=>r:r=>r instanceof CSSStyleSheet?(t=>{let e="";for(const i of t.cssRules)e+=i.cssText;return Yi(e)})(r):r;/**
16
20
  * @license
17
21
  * Copyright 2017 Google LLC
18
22
  * SPDX-License-Identifier: BSD-3-Clause
19
- */var Kr;const Is=window,fi=Is.trustedTypes,lo=fi?fi.createPolicy("lit-html",{createHTML:r=>r}):void 0,ks="$lit$",Ae=`lit$${(Math.random()+"").slice(9)}$`,jr="?"+Ae,pc=`<${jr}>`,Ke=document,Ni=()=>Ke.createComment(""),Ui=r=>r===null||typeof r!="object"&&typeof r!="function",ho=Array.isArray,co=r=>ho(r)||typeof(r==null?void 0:r[Symbol.iterator])=="function",Wr=`[
20
- \f\r]`,Bi=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,uo=/-->/g,fo=/>/g,je=RegExp(`>|${Wr}(?:([^\\s"'>=/]+)(${Wr}*=${Wr}*(?:[^
21
- \f\r"'\`<>=]|("|')|))|$)`,"g"),po=/'/g,go=/"/g,mo=/^(?:script|style|textarea|title)$/i,gc=r=>(t,...e)=>({_$litType$:r,strings:t,values:e}),J=gc(1),he=Symbol.for("lit-noChange"),gt=Symbol.for("lit-nothing"),vo=new WeakMap,We=Ke.createTreeWalker(Ke,129,null,!1),yo=(r,t)=>{const e=r.length-1,i=[];let s,n=t===2?"<svg>":"",a=Bi;for(let l=0;l<e;l++){const h=r[l];let d,c,u=-1,f=0;for(;f<h.length&&(a.lastIndex=f,c=a.exec(h),c!==null);)f=a.lastIndex,a===Bi?c[1]==="!--"?a=uo:c[1]!==void 0?a=fo:c[2]!==void 0?(mo.test(c[2])&&(s=RegExp("</"+c[2],"g")),a=je):c[3]!==void 0&&(a=je):a===je?c[0]===">"?(a=s??Bi,u=-1):c[1]===void 0?u=-2:(u=a.lastIndex-c[2].length,d=c[1],a=c[3]===void 0?je:c[3]==='"'?go:po):a===go||a===po?a=je:a===uo||a===fo?a=Bi:(a=je,s=void 0);const p=a===je&&r[l+1].startsWith("/>")?" ":"";n+=a===Bi?h+pc:u>=0?(i.push(d),h.slice(0,u)+ks+h.slice(u)+Ae+p):h+Ae+(u===-2?(i.push(void 0),l):p)}const o=n+(r[e]||"<?>")+(t===2?"</svg>":"");if(!Array.isArray(r)||!r.hasOwnProperty("raw"))throw Error("invalid template strings array");return[lo!==void 0?lo.createHTML(o):o,i]};class Hi{constructor({strings:t,_$litType$:e},i){let s;this.parts=[];let n=0,a=0;const o=t.length-1,l=this.parts,[h,d]=yo(t,e);if(this.el=Hi.createElement(h,i),We.currentNode=this.el.content,e===2){const c=this.el.content,u=c.firstChild;u.remove(),c.append(...u.childNodes)}for(;(s=We.nextNode())!==null&&l.length<o;){if(s.nodeType===1){if(s.hasAttributes()){const c=[];for(const u of s.getAttributeNames())if(u.endsWith(ks)||u.startsWith(Ae)){const f=d[a++];if(c.push(u),f!==void 0){const p=s.getAttribute(f.toLowerCase()+ks).split(Ae),g=/([.?@])?(.*)/.exec(f);l.push({type:1,index:n,name:g[2],strings:p,ctor:g[1]==="."?To:g[1]==="?"?bo:g[1]==="@"?Ao:Gi})}else l.push({type:6,index:n})}for(const u of c)s.removeAttribute(u)}if(mo.test(s.tagName)){const c=s.textContent.split(Ae),u=c.length-1;if(u>0){s.textContent=fi?fi.emptyScript:"";for(let f=0;f<u;f++)s.append(c[f],Ni()),We.nextNode(),l.push({type:2,index:++n});s.append(c[u],Ni())}}}else if(s.nodeType===8)if(s.data===jr)l.push({type:2,index:n});else{let c=-1;for(;(c=s.data.indexOf(Ae,c+1))!==-1;)l.push({type:7,index:n}),c+=Ae.length-1}n++}}static createElement(t,e){const i=Ke.createElement("template");return i.innerHTML=t,i}}function Ye(r,t,e=r,i){var s,n,a,o;if(t===he)return t;let l=i!==void 0?(s=e._$Co)===null||s===void 0?void 0:s[i]:e._$Cl;const h=Ui(t)?void 0:t._$litDirective$;return(l==null?void 0:l.constructor)!==h&&((n=l==null?void 0:l._$AO)===null||n===void 0||n.call(l,!1),h===void 0?l=void 0:(l=new h(r),l._$AT(r,e,i)),i!==void 0?((a=(o=e)._$Co)!==null&&a!==void 0?a:o._$Co=[])[i]=l:e._$Cl=l),l!==void 0&&(t=Ye(r,l._$AS(r,t.values),l,i)),t}let Eo=class{constructor(t,e){this._$AV=[],this._$AN=void 0,this._$AD=t,this._$AM=e}get parentNode(){return this._$AM.parentNode}get _$AU(){return this._$AM._$AU}u(t){var e;const{el:{content:i},parts:s}=this._$AD,n=((e=t==null?void 0:t.creationScope)!==null&&e!==void 0?e:Ke).importNode(i,!0);We.currentNode=n;let a=We.nextNode(),o=0,l=0,h=s[0];for(;h!==void 0;){if(o===h.index){let d;h.type===2?d=new Cs(a,a.nextSibling,this,t):h.type===1?d=new h.ctor(a,h.name,h.strings,this,t):h.type===6&&(d=new wo(a,this,t)),this._$AV.push(d),h=s[++l]}o!==(h==null?void 0:h.index)&&(a=We.nextNode(),o++)}return We.currentNode=Ke,n}v(t){let e=0;for(const i of this._$AV)i!==void 0&&(i.strings!==void 0?(i._$AI(t,i,e),e+=i.strings.length-2):i._$AI(t[e])),e++}},Cs=class ic{constructor(t,e,i,s){var n;this.type=2,this._$AH=gt,this._$AN=void 0,this._$AA=t,this._$AB=e,this._$AM=i,this.options=s,this._$Cp=(n=s==null?void 0:s.isConnected)===null||n===void 0||n}get _$AU(){var t,e;return(e=(t=this._$AM)===null||t===void 0?void 0:t._$AU)!==null&&e!==void 0?e:this._$Cp}get parentNode(){let t=this._$AA.parentNode;const e=this._$AM;return e!==void 0&&(t==null?void 0:t.nodeType)===11&&(t=e.parentNode),t}get startNode(){return this._$AA}get endNode(){return this._$AB}_$AI(t,e=this){t=Ye(this,t,e),Ui(t)?t===gt||t==null||t===""?(this._$AH!==gt&&this._$AR(),this._$AH=gt):t!==this._$AH&&t!==he&&this._(t):t._$litType$!==void 0?this.g(t):t.nodeType!==void 0?this.$(t):co(t)?this.T(t):this._(t)}k(t){return this._$AA.parentNode.insertBefore(t,this._$AB)}$(t){this._$AH!==t&&(this._$AR(),this._$AH=this.k(t))}_(t){this._$AH!==gt&&Ui(this._$AH)?this._$AA.nextSibling.data=t:this.$(Ke.createTextNode(t)),this._$AH=t}g(t){var e;const{values:i,_$litType$:s}=t,n=typeof s=="number"?this._$AC(t):(s.el===void 0&&(s.el=Hi.createElement(s.h,this.options)),s);if(((e=this._$AH)===null||e===void 0?void 0:e._$AD)===n)this._$AH.v(i);else{const a=new Eo(n,this),o=a.u(this.options);a.v(i),this.$(o),this._$AH=a}}_$AC(t){let e=vo.get(t.strings);return e===void 0&&vo.set(t.strings,e=new Hi(t)),e}T(t){ho(this._$AH)||(this._$AH=[],this._$AR());const e=this._$AH;let i,s=0;for(const n of t)s===e.length?e.push(i=new ic(this.k(Ni()),this.k(Ni()),this,this.options)):i=e[s],i._$AI(n),s++;s<e.length&&(this._$AR(i&&i._$AB.nextSibling,s),e.length=s)}_$AR(t=this._$AA.nextSibling,e){var i;for((i=this._$AP)===null||i===void 0||i.call(this,!1,!0,e);t&&t!==this._$AB;){const s=t.nextSibling;t.remove(),t=s}}setConnected(t){var e;this._$AM===void 0&&(this._$Cp=t,(e=this._$AP)===null||e===void 0||e.call(this,t))}};class Gi{constructor(t,e,i,s,n){this.type=1,this._$AH=gt,this._$AN=void 0,this.element=t,this.name=e,this._$AM=s,this.options=n,i.length>2||i[0]!==""||i[1]!==""?(this._$AH=Array(i.length-1).fill(new String),this.strings=i):this._$AH=gt}get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}_$AI(t,e=this,i,s){const n=this.strings;let a=!1;if(n===void 0)t=Ye(this,t,e,0),a=!Ui(t)||t!==this._$AH&&t!==he,a&&(this._$AH=t);else{const o=t;let l,h;for(t=n[0],l=0;l<n.length-1;l++)h=Ye(this,o[i+l],e,l),h===he&&(h=this._$AH[l]),a||(a=!Ui(h)||h!==this._$AH[l]),h===gt?t=gt:t!==gt&&(t+=(h??"")+n[l+1]),this._$AH[l]=h}a&&!s&&this.j(t)}j(t){t===gt?this.element.removeAttribute(this.name):this.element.setAttribute(this.name,t??"")}}class To extends Gi{constructor(){super(...arguments),this.type=3}j(t){this.element[this.name]=t===gt?void 0:t}}const mc=fi?fi.emptyScript:"";class bo extends Gi{constructor(){super(...arguments),this.type=4}j(t){t&&t!==gt?this.element.setAttribute(this.name,mc):this.element.removeAttribute(this.name)}}let Ao=class extends Gi{constructor(t,e,i,s,n){super(t,e,i,s,n),this.type=5}_$AI(t,e=this){var i;if((t=(i=Ye(this,t,e,0))!==null&&i!==void 0?i:gt)===he)return;const s=this._$AH,n=t===gt&&s!==gt||t.capture!==s.capture||t.once!==s.once||t.passive!==s.passive,a=t!==gt&&(s===gt||n);n&&this.element.removeEventListener(this.name,this,s),a&&this.element.addEventListener(this.name,this,t),this._$AH=t}handleEvent(t){var e,i;typeof this._$AH=="function"?this._$AH.call((i=(e=this.options)===null||e===void 0?void 0:e.host)!==null&&i!==void 0?i:this.element,t):this._$AH.handleEvent(t)}};class wo{constructor(t,e,i){this.element=t,this.type=6,this._$AN=void 0,this._$AM=e,this.options=i}get _$AU(){return this._$AM._$AU}_$AI(t){Ye(this,t)}}const vc={O:ks,P:Ae,A:jr,C:1,M:yo,L:Eo,D:co,R:Ye,I:Cs,V:Gi,H:bo,N:Ao,U:To,F:wo},So=Is.litHtmlPolyfillSupport;So==null||So(Hi,Cs),((Kr=Is.litHtmlVersions)!==null&&Kr!==void 0?Kr:Is.litHtmlVersions=[]).push("2.7.4");const yc=(r,t,e)=>{var i,s;const n=(i=e==null?void 0:e.renderBefore)!==null&&i!==void 0?i:t;let a=n._$litPart$;if(a===void 0){const o=(s=e==null?void 0:e.renderBefore)!==null&&s!==void 0?s:null;n._$litPart$=a=new Cs(t.insertBefore(Ni(),o),o,void 0,e??{})}return a._$AI(r),a};/**
23
+ */const{is:zc,defineProperty:qc,getOwnPropertyDescriptor:Xc,getOwnPropertyNames:Qc,getOwnPropertySymbols:Zc,getPrototypeOf:Jc}=Object,Be=globalThis,eo=Be.trustedTypes,td=eo?eo.emptyScript:"",Hr=Be.reactiveElementPolyfillSupport,zi=(r,t)=>r,Gr={toAttribute(r,t){switch(t){case Boolean:r=r?td:null;break;case Object:case Array:r=r==null?r:JSON.stringify(r)}return r},fromAttribute(r,t){let e=r;switch(t){case Boolean:e=r!==null;break;case Number:e=r===null?null:Number(r);break;case Object:case Array:try{e=JSON.parse(r)}catch{e=null}}return e}},io=(r,t)=>!zc(r,t),so={attribute:!0,type:String,converter:Gr,reflect:!1,hasChanged:io};Symbol.metadata??(Symbol.metadata=Symbol("metadata")),Be.litPropertyMetadata??(Be.litPropertyMetadata=new WeakMap);let Ei=class extends HTMLElement{static addInitializer(t){this._$Ei(),(this.l??(this.l=[])).push(t)}static get observedAttributes(){return this.finalize(),this._$Eh&&[...this._$Eh.keys()]}static createProperty(t,e=so){if(e.state&&(e.attribute=!1),this._$Ei(),this.elementProperties.set(t,e),!e.noAccessor){const i=Symbol(),s=this.getPropertyDescriptor(t,i,e);s!==void 0&&qc(this.prototype,t,s)}}static getPropertyDescriptor(t,e,i){const{get:s,set:n}=Xc(this.prototype,t)??{get(){return this[e]},set(a){this[e]=a}};return{get(){return s==null?void 0:s.call(this)},set(a){const o=s==null?void 0:s.call(this);n.call(this,a),this.requestUpdate(t,o,i)},configurable:!0,enumerable:!0}}static getPropertyOptions(t){return this.elementProperties.get(t)??so}static _$Ei(){if(this.hasOwnProperty(zi("elementProperties")))return;const t=Jc(this);t.finalize(),t.l!==void 0&&(this.l=[...t.l]),this.elementProperties=new Map(t.elementProperties)}static finalize(){if(this.hasOwnProperty(zi("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(zi("properties"))){const e=this.properties,i=[...Qc(e),...Zc(e)];for(const s of i)this.createProperty(s,e[s])}const t=this[Symbol.metadata];if(t!==null){const e=litPropertyMetadata.get(t);if(e!==void 0)for(const[i,s]of e)this.elementProperties.set(i,s)}this._$Eh=new Map;for(const[e,i]of this.elementProperties){const s=this._$Eu(e,i);s!==void 0&&this._$Eh.set(s,e)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(t){const e=[];if(Array.isArray(t)){const i=new Set(t.flat(1/0).reverse());for(const s of i)e.unshift(to(s))}else t!==void 0&&e.push(to(t));return e}static _$Eu(t,e){const i=e.attribute;return i===!1?void 0:typeof i=="string"?i:typeof t=="string"?t.toLowerCase():void 0}constructor(){super(),this._$Ep=void 0,this.isUpdatePending=!1,this.hasUpdated=!1,this._$Em=null,this._$Ev()}_$Ev(){var t;this._$Eg=new Promise(e=>this.enableUpdating=e),this._$AL=new Map,this._$ES(),this.requestUpdate(),(t=this.constructor.l)==null||t.forEach(e=>e(this))}addController(t){var e;(this._$E_??(this._$E_=new Set)).add(t),this.renderRoot!==void 0&&this.isConnected&&((e=t.hostConnected)==null||e.call(t))}removeController(t){var e;(e=this._$E_)==null||e.delete(t)}_$ES(){const t=new Map,e=this.constructor.elementProperties;for(const i of e.keys())this.hasOwnProperty(i)&&(t.set(i,this[i]),delete this[i]);t.size>0&&(this._$Ep=t)}createRenderRoot(){const t=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return Yc(t,this.constructor.elementStyles),t}connectedCallback(){var t;this.renderRoot??(this.renderRoot=this.createRenderRoot()),this.enableUpdating(!0),(t=this._$E_)==null||t.forEach(e=>{var i;return(i=e.hostConnected)==null?void 0:i.call(e)})}enableUpdating(t){}disconnectedCallback(){var t;(t=this._$E_)==null||t.forEach(e=>{var i;return(i=e.hostDisconnected)==null?void 0:i.call(e)})}attributeChangedCallback(t,e,i){this._$AK(t,i)}_$EO(t,e){var n;const i=this.constructor.elementProperties.get(t),s=this.constructor._$Eu(t,i);if(s!==void 0&&i.reflect===!0){const a=(((n=i.converter)==null?void 0:n.toAttribute)!==void 0?i.converter:Gr).toAttribute(e,i.type);this._$Em=t,a==null?this.removeAttribute(s):this.setAttribute(s,a),this._$Em=null}}_$AK(t,e){var n;const i=this.constructor,s=i._$Eh.get(t);if(s!==void 0&&this._$Em!==s){const a=i.getPropertyOptions(s),o=typeof a.converter=="function"?{fromAttribute:a.converter}:((n=a.converter)==null?void 0:n.fromAttribute)!==void 0?a.converter:Gr;this._$Em=s,this[s]=o.fromAttribute(e,a.type),this._$Em=null}}requestUpdate(t,e,i,s=!1,n){if(t!==void 0){if(i??(i=this.constructor.getPropertyOptions(t)),!(i.hasChanged??io)(s?n:this[t],e))return;this.C(t,e,i)}this.isUpdatePending===!1&&(this._$Eg=this._$EP())}C(t,e,i){this._$AL.has(t)||this._$AL.set(t,e),i.reflect===!0&&this._$Em!==t&&(this._$Ej??(this._$Ej=new Set)).add(t)}async _$EP(){this.isUpdatePending=!0;try{await this._$Eg}catch(e){Promise.reject(e)}const t=this.scheduleUpdate();return t!=null&&await t,!this.isUpdatePending}scheduleUpdate(){return this.performUpdate()}performUpdate(){var i;if(!this.isUpdatePending)return;if(!this.hasUpdated){if(this.renderRoot??(this.renderRoot=this.createRenderRoot()),this._$Ep){for(const[n,a]of this._$Ep)this[n]=a;this._$Ep=void 0}const s=this.constructor.elementProperties;if(s.size>0)for(const[n,a]of s)a.wrapped!==!0||this._$AL.has(n)||this[n]===void 0||this.C(n,this[n],a)}let t=!1;const e=this._$AL;try{t=this.shouldUpdate(e),t?(this.willUpdate(e),(i=this._$E_)==null||i.forEach(s=>{var n;return(n=s.hostUpdate)==null?void 0:n.call(s)}),this.update(e)):this._$ET()}catch(s){throw t=!1,this._$ET(),s}t&&this._$AE(e)}willUpdate(t){}_$AE(t){var e;(e=this._$E_)==null||e.forEach(i=>{var s;return(s=i.hostUpdated)==null?void 0:s.call(i)}),this.hasUpdated||(this.hasUpdated=!0,this.firstUpdated(t)),this.updated(t)}_$ET(){this._$AL=new Map,this.isUpdatePending=!1}get updateComplete(){return this.getUpdateComplete()}getUpdateComplete(){return this._$Eg}shouldUpdate(t){return!0}update(t){this._$Ej&&(this._$Ej=this._$Ej.forEach(e=>this._$EO(e,this[e]))),this._$ET()}updated(t){}firstUpdated(t){}};Ei.elementStyles=[],Ei.shadowRootOptions={mode:"open"},Ei[zi("elementProperties")]=new Map,Ei[zi("finalized")]=new Map,Hr==null||Hr({ReactiveElement:Ei}),(Be.reactiveElementVersions??(Be.reactiveElementVersions=[])).push("2.0.2");/**
22
24
  * @license
23
25
  * Copyright 2017 Google LLC
24
26
  * SPDX-License-Identifier: BSD-3-Clause
25
- */var Yr,zr;let pi=class extends di{constructor(){super(...arguments),this.renderOptions={host:this},this._$Do=void 0}createRenderRoot(){var t,e;const i=super.createRenderRoot();return(t=(e=this.renderOptions).renderBefore)!==null&&t!==void 0||(e.renderBefore=i.firstChild),i}update(t){const e=this.render();this.hasUpdated||(this.renderOptions.isConnected=this.isConnected),super.update(t),this._$Do=yc(e,this.renderRoot,this.renderOptions)}connectedCallback(){var t;super.connectedCallback(),(t=this._$Do)===null||t===void 0||t.setConnected(!0)}disconnectedCallback(){var t;super.disconnectedCallback(),(t=this._$Do)===null||t===void 0||t.setConnected(!1)}render(){return he}};pi.finalized=!0,pi._$litElement$=!0,(Yr=globalThis.litElementHydrateSupport)===null||Yr===void 0||Yr.call(globalThis,{LitElement:pi});const Lo=globalThis.litElementPolyfillSupport;Lo==null||Lo({LitElement:pi}),((zr=globalThis.litElementVersions)!==null&&zr!==void 0?zr:globalThis.litElementVersions=[]).push("3.3.2");/**
27
+ */const qi=globalThis,$s=qi.trustedTypes,ro=$s?$s.createPolicy("lit-html",{createHTML:r=>r}):void 0,no="$lit$",He=`lit$${(Math.random()+"").slice(9)}$`,ao="?"+He,ed=`<${ao}>`,ei=document,Xi=()=>ei.createComment(""),Qi=r=>r===null||typeof r!="object"&&typeof r!="function",oo=Array.isArray,id=r=>oo(r)||typeof(r==null?void 0:r[Symbol.iterator])=="function",Vr=`[
28
+ \f\r]`,Zi=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,lo=/-->/g,ho=/>/g,ii=RegExp(`>|${Vr}(?:([^\\s"'>=/]+)(${Vr}*=${Vr}*(?:[^
29
+ \f\r"'\`<>=]|("|')|))|$)`,"g"),co=/'/g,uo=/"/g,fo=/^(?:script|style|textarea|title)$/i,sd=r=>(t,...e)=>({_$litType$:r,strings:t,values:e}),st=sd(1),Ge=Symbol.for("lit-noChange"),Ot=Symbol.for("lit-nothing"),po=new WeakMap,si=ei.createTreeWalker(ei,129);function go(r,t){if(!Array.isArray(r)||!r.hasOwnProperty("raw"))throw Error("invalid template strings array");return ro!==void 0?ro.createHTML(t):t}const rd=(r,t)=>{const e=r.length-1,i=[];let s,n=t===2?"<svg>":"",a=Zi;for(let o=0;o<e;o++){const l=r[o];let h,c,d=-1,u=0;for(;u<l.length&&(a.lastIndex=u,c=a.exec(l),c!==null);)u=a.lastIndex,a===Zi?c[1]==="!--"?a=lo:c[1]!==void 0?a=ho:c[2]!==void 0?(fo.test(c[2])&&(s=RegExp("</"+c[2],"g")),a=ii):c[3]!==void 0&&(a=ii):a===ii?c[0]===">"?(a=s??Zi,d=-1):c[1]===void 0?d=-2:(d=a.lastIndex-c[2].length,h=c[1],a=c[3]===void 0?ii:c[3]==='"'?uo:co):a===uo||a===co?a=ii:a===lo||a===ho?a=Zi:(a=ii,s=void 0);const f=a===ii&&r[o+1].startsWith("/>")?" ":"";n+=a===Zi?l+ed:d>=0?(i.push(h),l.slice(0,d)+no+l.slice(d)+He+f):l+He+(d===-2?o:f)}return[go(r,n+(r[e]||"<?>")+(t===2?"</svg>":"")),i]};class Ji{constructor({strings:t,_$litType$:e},i){let s;this.parts=[];let n=0,a=0;const o=t.length-1,l=this.parts,[h,c]=rd(t,e);if(this.el=Ji.createElement(h,i),si.currentNode=this.el.content,e===2){const d=this.el.content.firstChild;d.replaceWith(...d.childNodes)}for(;(s=si.nextNode())!==null&&l.length<o;){if(s.nodeType===1){if(s.hasAttributes())for(const d of s.getAttributeNames())if(d.endsWith(no)){const u=c[a++],f=s.getAttribute(d).split(He),p=/([.?@])?(.*)/.exec(u);l.push({type:1,index:n,name:p[2],strings:f,ctor:p[1]==="."?ad:p[1]==="?"?od:p[1]==="@"?ld:Ms}),s.removeAttribute(d)}else d.startsWith(He)&&(l.push({type:6,index:n}),s.removeAttribute(d));if(fo.test(s.tagName)){const d=s.textContent.split(He),u=d.length-1;if(u>0){s.textContent=$s?$s.emptyScript:"";for(let f=0;f<u;f++)s.append(d[f],Xi()),si.nextNode(),l.push({type:2,index:++n});s.append(d[u],Xi())}}}else if(s.nodeType===8)if(s.data===ao)l.push({type:2,index:n});else{let d=-1;for(;(d=s.data.indexOf(He,d+1))!==-1;)l.push({type:7,index:n}),d+=He.length-1}n++}}static createElement(t,e){const i=ei.createElement("template");return i.innerHTML=t,i}}function bi(r,t,e=r,i){var a,o;if(t===Ge)return t;let s=i!==void 0?(a=e._$Co)==null?void 0:a[i]:e._$Cl;const n=Qi(t)?void 0:t._$litDirective$;return(s==null?void 0:s.constructor)!==n&&((o=s==null?void 0:s._$AO)==null||o.call(s,!1),n===void 0?s=void 0:(s=new n(r),s._$AT(r,e,i)),i!==void 0?(e._$Co??(e._$Co=[]))[i]=s:e._$Cl=s),s!==void 0&&(t=bi(r,s._$AS(r,t.values),s,i)),t}let nd=class{constructor(t,e){this._$AV=[],this._$AN=void 0,this._$AD=t,this._$AM=e}get parentNode(){return this._$AM.parentNode}get _$AU(){return this._$AM._$AU}u(t){const{el:{content:e},parts:i}=this._$AD,s=((t==null?void 0:t.creationScope)??ei).importNode(e,!0);si.currentNode=s;let n=si.nextNode(),a=0,o=0,l=i[0];for(;l!==void 0;){if(a===l.index){let h;l.type===2?h=new Kr(n,n.nextSibling,this,t):l.type===1?h=new l.ctor(n,l.name,l.strings,this,t):l.type===6&&(h=new hd(n,this,t)),this._$AV.push(h),l=i[++o]}a!==(l==null?void 0:l.index)&&(n=si.nextNode(),a++)}return si.currentNode=ei,s}p(t){let e=0;for(const i of this._$AV)i!==void 0&&(i.strings!==void 0?(i._$AI(t,i,e),e+=i.strings.length-2):i._$AI(t[e])),e++}},Kr=class Oc{get _$AU(){var t;return((t=this._$AM)==null?void 0:t._$AU)??this._$Cv}constructor(t,e,i,s){this.type=2,this._$AH=Ot,this._$AN=void 0,this._$AA=t,this._$AB=e,this._$AM=i,this.options=s,this._$Cv=(s==null?void 0:s.isConnected)??!0}get parentNode(){let t=this._$AA.parentNode;const e=this._$AM;return e!==void 0&&(t==null?void 0:t.nodeType)===11&&(t=e.parentNode),t}get startNode(){return this._$AA}get endNode(){return this._$AB}_$AI(t,e=this){t=bi(this,t,e),Qi(t)?t===Ot||t==null||t===""?(this._$AH!==Ot&&this._$AR(),this._$AH=Ot):t!==this._$AH&&t!==Ge&&this._(t):t._$litType$!==void 0?this.g(t):t.nodeType!==void 0?this.$(t):id(t)?this.T(t):this._(t)}k(t){return this._$AA.parentNode.insertBefore(t,this._$AB)}$(t){this._$AH!==t&&(this._$AR(),this._$AH=this.k(t))}_(t){this._$AH!==Ot&&Qi(this._$AH)?this._$AA.nextSibling.data=t:this.$(ei.createTextNode(t)),this._$AH=t}g(t){var n;const{values:e,_$litType$:i}=t,s=typeof i=="number"?this._$AC(t):(i.el===void 0&&(i.el=Ji.createElement(go(i.h,i.h[0]),this.options)),i);if(((n=this._$AH)==null?void 0:n._$AD)===s)this._$AH.p(e);else{const a=new nd(s,this),o=a.u(this.options);a.p(e),this.$(o),this._$AH=a}}_$AC(t){let e=po.get(t.strings);return e===void 0&&po.set(t.strings,e=new Ji(t)),e}T(t){oo(this._$AH)||(this._$AH=[],this._$AR());const e=this._$AH;let i,s=0;for(const n of t)s===e.length?e.push(i=new Oc(this.k(Xi()),this.k(Xi()),this,this.options)):i=e[s],i._$AI(n),s++;s<e.length&&(this._$AR(i&&i._$AB.nextSibling,s),e.length=s)}_$AR(t=this._$AA.nextSibling,e){var i;for((i=this._$AP)==null?void 0:i.call(this,!1,!0,e);t&&t!==this._$AB;){const s=t.nextSibling;t.remove(),t=s}}setConnected(t){var e;this._$AM===void 0&&(this._$Cv=t,(e=this._$AP)==null||e.call(this,t))}};class Ms{get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}constructor(t,e,i,s,n){this.type=1,this._$AH=Ot,this._$AN=void 0,this.element=t,this.name=e,this._$AM=s,this.options=n,i.length>2||i[0]!==""||i[1]!==""?(this._$AH=Array(i.length-1).fill(new String),this.strings=i):this._$AH=Ot}_$AI(t,e=this,i,s){const n=this.strings;let a=!1;if(n===void 0)t=bi(this,t,e,0),a=!Qi(t)||t!==this._$AH&&t!==Ge,a&&(this._$AH=t);else{const o=t;let l,h;for(t=n[0],l=0;l<n.length-1;l++)h=bi(this,o[i+l],e,l),h===Ge&&(h=this._$AH[l]),a||(a=!Qi(h)||h!==this._$AH[l]),h===Ot?t=Ot:t!==Ot&&(t+=(h??"")+n[l+1]),this._$AH[l]=h}a&&!s&&this.O(t)}O(t){t===Ot?this.element.removeAttribute(this.name):this.element.setAttribute(this.name,t??"")}}class ad extends Ms{constructor(){super(...arguments),this.type=3}O(t){this.element[this.name]=t===Ot?void 0:t}}let od=class extends Ms{constructor(){super(...arguments),this.type=4}O(t){this.element.toggleAttribute(this.name,!!t&&t!==Ot)}};class ld extends Ms{constructor(t,e,i,s,n){super(t,e,i,s,n),this.type=5}_$AI(t,e=this){if((t=bi(this,t,e,0)??Ot)===Ge)return;const i=this._$AH,s=t===Ot&&i!==Ot||t.capture!==i.capture||t.once!==i.once||t.passive!==i.passive,n=t!==Ot&&(i===Ot||s);s&&this.element.removeEventListener(this.name,this,i),n&&this.element.addEventListener(this.name,this,t),this._$AH=t}handleEvent(t){var e;typeof this._$AH=="function"?this._$AH.call(((e=this.options)==null?void 0:e.host)??this.element,t):this._$AH.handleEvent(t)}}let hd=class{constructor(t,e,i){this.element=t,this.type=6,this._$AN=void 0,this._$AM=e,this.options=i}get _$AU(){return this._$AM._$AU}_$AI(t){bi(this,t)}};const jr=qi.litHtmlPolyfillSupport;jr==null||jr(Ji,Kr),(qi.litHtmlVersions??(qi.litHtmlVersions=[])).push("3.1.0");const cd=(r,t,e)=>{const i=(e==null?void 0:e.renderBefore)??t;let s=i._$litPart$;if(s===void 0){const n=(e==null?void 0:e.renderBefore)??null;i._$litPart$=s=new Kr(t.insertBefore(Xi(),n),n,void 0,e??{})}return s._$AI(r),s};/**
26
30
  * @license
27
31
  * Copyright 2017 Google LLC
28
32
  * SPDX-License-Identifier: BSD-3-Clause
29
- */const Ec=r=>t=>typeof t=="function"?((e,i)=>(customElements.define(e,i),i))(r,t):((e,i)=>{const{kind:s,elements:n}=i;return{kind:s,elements:n,finisher(a){customElements.define(e,a)}}})(r,t);/**
33
+ */let Ti=class extends Ei{constructor(){super(...arguments),this.renderOptions={host:this},this._$Do=void 0}createRenderRoot(){var e;const t=super.createRenderRoot();return(e=this.renderOptions).renderBefore??(e.renderBefore=t.firstChild),t}update(t){const e=this.render();this.hasUpdated||(this.renderOptions.isConnected=this.isConnected),super.update(t),this._$Do=cd(e,this.renderRoot,this.renderOptions)}connectedCallback(){var t;super.connectedCallback(),(t=this._$Do)==null||t.setConnected(!0)}disconnectedCallback(){var t;super.disconnectedCallback(),(t=this._$Do)==null||t.setConnected(!1)}render(){return Ge}};Ti._$litElement$=!0,Ti.finalized=!0,(Ic=globalThis.litElementHydrateSupport)==null||Ic.call(globalThis,{LitElement:Ti});const Wr=globalThis.litElementPolyfillSupport;Wr==null||Wr({LitElement:Ti}),(globalThis.litElementVersions??(globalThis.litElementVersions=[])).push("4.0.2");/**
30
34
  * @license
31
35
  * Copyright 2017 Google LLC
32
36
  * SPDX-License-Identifier: BSD-3-Clause
33
- */const Tc=(r,t)=>t.kind==="method"&&t.descriptor&&!("value"in t.descriptor)?{...t,finisher(e){e.createProperty(t.key,r)}}:{kind:"field",key:Symbol(),placement:"own",descriptor:{},originalKey:t.key,initializer(){typeof t.initializer=="function"&&(this[t.key]=t.initializer.call(this))},finisher(e){e.createProperty(t.key,r)}},bc=(r,t,e)=>{t.constructor.createProperty(e,r)};function G(r){return(t,e)=>e!==void 0?bc(r,t,e):Tc(r,t)}/**
37
+ */const dd=r=>(t,e)=>{e!==void 0?e.addInitializer(()=>{customElements.define(r,t)}):customElements.define(r,t)};/**
34
38
  * @license
35
39
  * Copyright 2017 Google LLC
36
40
  * SPDX-License-Identifier: BSD-3-Clause
37
- */function Nt(r){return G({...r,state:!0})}/**
41
+ */const ud={attribute:!0,type:String,converter:Ds,reflect:!1,hasChanged:xr},fd=(r=ud,t,e)=>{const{kind:i,metadata:s}=e;let n=globalThis.litPropertyMetadata.get(s);if(n===void 0&&globalThis.litPropertyMetadata.set(s,n=new Map),n.set(e.name,r),i==="accessor"){const{name:a}=e;return{set(o){const l=t.get.call(this);t.set.call(this,o),this.requestUpdate(a,l,r)},init(o){return o!==void 0&&this.C(a,void 0,r),o}}}if(i==="setter"){const{name:a}=e;return function(o){const l=this[a];t.call(this,o),this.requestUpdate(a,l,r)}}throw Error("Unsupported decorator location: "+i)};function j(r){return(t,e)=>typeof e=="object"?fd(r,t,e):((i,s,n)=>{const a=s.hasOwnProperty(n);return s.constructor.createProperty(n,a?{...i,wrapped:!0}:i),a?Object.getOwnPropertyDescriptor(s,n):void 0})(r,t,e)}/**
38
42
  * @license
39
- * Copyright 2021 Google LLC
43
+ * Copyright 2017 Google LLC
40
44
  * SPDX-License-Identifier: BSD-3-Clause
41
- */var qr;((qr=window.HTMLSlotElement)===null||qr===void 0?void 0:qr.prototype.assignedElements)!=null;/**
45
+ */function Wt(r){return j({...r,state:!0,attribute:!1})}/**
42
46
  * @license
43
47
  * Copyright 2018 Google LLC
44
48
  * SPDX-License-Identifier: BSD-3-Clause
45
- */const Ro=r=>r??pt;/**
49
+ */const ri=r=>r??kt;/**
46
50
  * @license
47
51
  * Copyright 2020 Google LLC
48
52
  * SPDX-License-Identifier: BSD-3-Clause
49
- */const Ac=r=>r.strings===void 0;/**
53
+ */const{D:pd}=Wc,gd=r=>r.strings===void 0,mo=()=>document.createComment(""),ts=(r,t,e)=>{var n;const i=r._$AA.parentNode,s=t===void 0?r._$AB:t._$AA;if(e===void 0){const a=i.insertBefore(mo(),s),o=i.insertBefore(mo(),s);e=new pd(a,o,r,r.options)}else{const a=e._$AB.nextSibling,o=e._$AM,l=o!==r;if(l){let h;(n=e._$AQ)==null||n.call(e,r),e._$AM=r,e._$AP!==void 0&&(h=r._$AU)!==o._$AU&&e._$AP(h)}if(a!==s||l){let h=e._$AA;for(;h!==a;){const c=h.nextSibling;i.insertBefore(h,s),h=c}}}return e},ni=(r,t,e=r)=>(r._$AI(t,e),r),md={},vd=(r,t=md)=>r._$AH=t,yd=r=>r._$AH,Yr=r=>{var i;(i=r._$AP)==null||i.call(r,!1,!0);let t=r._$AA;const e=r._$AB.nextSibling;for(;t!==e;){const s=t.nextSibling;t.remove(),t=s}};/**
50
54
  * @license
51
55
  * Copyright 2017 Google LLC
52
56
  * SPDX-License-Identifier: BSD-3-Clause
53
- */const wc={ATTRIBUTE:1,CHILD:2,PROPERTY:3,BOOLEAN_ATTRIBUTE:4,EVENT:5,ELEMENT:6},Sc=r=>(...t)=>({_$litDirective$:r,values:t});let Lc=class{constructor(t){}get _$AU(){return this._$AM._$AU}_$AT(t,e,i){this._$Ct=t,this._$AM=e,this._$Ci=i}_$AS(t,e){return this.update(t,e)}update(t,e){return this.render(...e)}};/**
57
+ */const es={ATTRIBUTE:1,CHILD:2,PROPERTY:3,BOOLEAN_ATTRIBUTE:4,EVENT:5,ELEMENT:6},is=r=>(...t)=>({_$litDirective$:r,values:t});let Fs=class{constructor(t){}get _$AU(){return this._$AM._$AU}_$AT(t,e,i){this._$Ct=t,this._$AM=e,this._$Ci=i}_$AS(t,e){return this.update(t,e)}update(t,e){return this.render(...e)}};/**
54
58
  * @license
55
59
  * Copyright 2017 Google LLC
56
60
  * SPDX-License-Identifier: BSD-3-Clause
57
- */const Vi=(r,t)=>{var e,i;const s=r._$AN;if(s===void 0)return!1;for(const n of s)(i=(e=n)._$AO)===null||i===void 0||i.call(e,t,!1),Vi(n,t);return!0},Ds=r=>{let t,e;do{if((t=r._$AM)===void 0)break;e=t._$AN,e.delete(r),r=t}while((e==null?void 0:e.size)===0)},_o=r=>{for(let t;t=r._$AM;r=t){let e=t._$AN;if(e===void 0)t._$AN=e=new Set;else if(e.has(r))break;e.add(r),Ic(t)}};function Rc(r){this._$AN!==void 0?(Ds(this),this._$AM=r,_o(this)):this._$AM=r}function _c(r,t=!1,e=0){const i=this._$AH,s=this._$AN;if(s!==void 0&&s.size!==0)if(t)if(Array.isArray(i))for(let n=e;n<i.length;n++)Vi(i[n],!1),Ds(i[n]);else i!=null&&(Vi(i,!1),Ds(i));else Vi(this,r)}const Ic=r=>{var t,e,i,s;r.type==wc.CHILD&&((t=(i=r)._$AP)!==null&&t!==void 0||(i._$AP=_c),(e=(s=r)._$AQ)!==null&&e!==void 0||(s._$AQ=Rc))};let kc=class extends Lc{constructor(){super(...arguments),this._$AN=void 0}_$AT(t,e,i){super._$AT(t,e,i),_o(this),this.isConnected=t._$AU}_$AO(t,e=!0){var i,s;t!==this.isConnected&&(this.isConnected=t,t?(i=this.reconnected)===null||i===void 0||i.call(this):(s=this.disconnected)===null||s===void 0||s.call(this)),e&&(Vi(this,t),Ds(this))}setValue(t){if(Ac(this._$Ct))this._$Ct._$AI(t,this);else{const e=[...this._$Ct._$AH];e[this._$Ci]=t,this._$Ct._$AI(e,this,0)}}disconnected(){}reconnected(){}};/**
61
+ */const ss=(r,t)=>{var i;const e=r._$AN;if(e===void 0)return!1;for(const s of e)(i=s._$AO)==null||i.call(s,t,!1),ss(s,t);return!0},Ns=r=>{let t,e;do{if((t=r._$AM)===void 0)break;e=t._$AN,e.delete(r),r=t}while((e==null?void 0:e.size)===0)},vo=r=>{for(let t;t=r._$AM;r=t){let e=t._$AN;if(e===void 0)t._$AN=e=new Set;else if(e.has(r))break;e.add(r),Td(t)}};function Ed(r){this._$AN!==void 0?(Ns(this),this._$AM=r,vo(this)):this._$AM=r}function bd(r,t=!1,e=0){const i=this._$AH,s=this._$AN;if(s!==void 0&&s.size!==0)if(t)if(Array.isArray(i))for(let n=e;n<i.length;n++)ss(i[n],!1),Ns(i[n]);else i!=null&&(ss(i,!1),Ns(i));else ss(this,r)}const Td=r=>{r.type==es.CHILD&&(r._$AP??(r._$AP=bd),r._$AQ??(r._$AQ=Ed))};let yo=class extends Fs{constructor(){super(...arguments),this._$AN=void 0}_$AT(t,e,i){super._$AT(t,e,i),vo(this),this.isConnected=t._$AU}_$AO(t,e=!0){var i,s;t!==this.isConnected&&(this.isConnected=t,t?(i=this.reconnected)==null||i.call(this):(s=this.disconnected)==null||s.call(this)),e&&(ss(this,t),Ns(this))}setValue(t){if(gd(this._$Ct))this._$Ct._$AI(t,this);else{const e=[...this._$Ct._$AH];e[this._$Ci]=t,this._$Ct._$AI(e,this,0)}}disconnected(){}reconnected(){}};/**
58
62
  * @license
59
63
  * Copyright 2020 Google LLC
60
64
  * SPDX-License-Identifier: BSD-3-Clause
61
- */const Io=()=>new Cc;let Cc=class{};const Xr=new WeakMap,ko=Sc(class extends kc{render(r){return pt}update(r,[t]){var e;const i=t!==this.G;return i&&this.G!==void 0&&this.ot(void 0),(i||this.rt!==this.lt)&&(this.G=t,this.dt=(e=r.options)===null||e===void 0?void 0:e.host,this.ot(this.lt=r.element)),pt}ot(r){var t;if(typeof this.G=="function"){const e=(t=this.dt)!==null&&t!==void 0?t:globalThis;let i=Xr.get(e);i===void 0&&(i=new WeakMap,Xr.set(e,i)),i.get(this.G)!==void 0&&this.G.call(this.dt,void 0),i.set(this.G,r),r!==void 0&&this.G.call(this.dt,r)}else this.G.value=r}get rt(){var r,t,e;return typeof this.G=="function"?(t=Xr.get((r=this.dt)!==null&&r!==void 0?r:globalThis))===null||t===void 0?void 0:t.get(this.G):(e=this.G)===null||e===void 0?void 0:e.value}disconnected(){this.rt===this.lt&&this.ot(void 0)}reconnected(){this.ot(this.lt)}});function Dc(r,t,e){function i(s){e.dispatchEvent(new CustomEvent(s.type,s))}return t.addEventListener(r,i),()=>{t.removeEventListener(r,i)}}class xc{constructor(t,e){this._events=[],this._cleanup=[],this._forwardElementRef=Io(),this.host=t,this._events=e,t.addController(this)}register(){return ko(this._forwardElementRef)}hostConnected(){requestAnimationFrame(()=>{this._events.forEach(t=>{this._forwardElementRef.value&&this._cleanup.push(Dc(t,this._forwardElementRef.value,this.host))})})}hostDisconnected(){this._cleanup.forEach(t=>{t()}),this._cleanup=[]}}/**
65
+ */const ae=()=>new Ad;let Ad=class{};const zr=new WeakMap,oe=is(class extends yo{render(r){return kt}update(r,[t]){var i;const e=t!==this.G;return e&&this.G!==void 0&&this.ot(void 0),(e||this.rt!==this.lt)&&(this.G=t,this.ct=(i=r.options)==null?void 0:i.host,this.ot(this.lt=r.element)),kt}ot(r){if(typeof this.G=="function"){const t=this.ct??globalThis;let e=zr.get(t);e===void 0&&(e=new WeakMap,zr.set(t,e)),e.get(this.G)!==void 0&&this.G.call(this.ct,void 0),e.set(this.G,r),r!==void 0&&this.G.call(this.ct,r)}else this.G.value=r}get rt(){var r,t;return typeof this.G=="function"?(r=zr.get(this.ct??globalThis))==null?void 0:r.get(this.G):(t=this.G)==null?void 0:t.value}disconnected(){this.rt===this.lt&&this.ot(void 0)}reconnected(){this.ot(this.lt)}});function wd(r,t,e){function i(s){e.dispatchEvent(new CustomEvent(s.type,s))}return t.addEventListener(r,i),()=>{t.removeEventListener(r,i)}}class Sd{constructor(t,e){this._events=[],this._cleanup=[],this._forwardElementRef=ae(),this.host=t,this._events=e,t.addController(this)}register(){return oe(this._forwardElementRef)}hostConnected(){requestAnimationFrame(()=>{this._events.forEach(t=>{this._forwardElementRef.value&&this._cleanup.push(wd(t,this._forwardElementRef.value,this.host))})})}hostDisconnected(){this._cleanup.forEach(t=>{t()}),this._cleanup=[]}}/**
62
66
  * @license
63
67
  * Copyright 2019 Google LLC
64
68
  * SPDX-License-Identifier: BSD-3-Clause
65
- */const xs=globalThis,Qr=xs.ShadowRoot&&(xs.ShadyCSS===void 0||xs.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,Co=Symbol(),Do=new WeakMap;let Pc=class{constructor(t,e,i){if(this._$cssResult$=!0,i!==Co)throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");this.cssText=t,this.t=e}get styleSheet(){let t=this.o;const e=this.t;if(Qr&&t===void 0){const i=e!==void 0&&e.length===1;i&&(t=Do.get(e)),t===void 0&&((this.o=t=new CSSStyleSheet).replaceSync(this.cssText),i&&Do.set(e,t))}return t}toString(){return this.cssText}};const Oc=r=>new Pc(typeof r=="string"?r:r+"",void 0,Co),Mc=(r,t)=>{if(Qr)r.adoptedStyleSheets=t.map(e=>e instanceof CSSStyleSheet?e:e.styleSheet);else for(const e of t){const i=document.createElement("style"),s=xs.litNonce;s!==void 0&&i.setAttribute("nonce",s),i.textContent=e.cssText,r.appendChild(i)}},xo=Qr?r=>r:r=>r instanceof CSSStyleSheet?(t=>{let e="";for(const i of t.cssRules)e+=i.cssText;return Oc(e)})(r):r;/**
69
+ */const Us=globalThis,qr=Us.ShadowRoot&&(Us.ShadyCSS===void 0||Us.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,Eo=Symbol(),bo=new WeakMap;let Ld=class{constructor(t,e,i){if(this._$cssResult$=!0,i!==Eo)throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");this.cssText=t,this.t=e}get styleSheet(){let t=this.o;const e=this.t;if(qr&&t===void 0){const i=e!==void 0&&e.length===1;i&&(t=bo.get(e)),t===void 0&&((this.o=t=new CSSStyleSheet).replaceSync(this.cssText),i&&bo.set(e,t))}return t}toString(){return this.cssText}};const Rd=r=>new Ld(typeof r=="string"?r:r+"",void 0,Eo),_d=(r,t)=>{if(qr)r.adoptedStyleSheets=t.map(e=>e instanceof CSSStyleSheet?e:e.styleSheet);else for(const e of t){const i=document.createElement("style"),s=Us.litNonce;s!==void 0&&i.setAttribute("nonce",s),i.textContent=e.cssText,r.appendChild(i)}},To=qr?r=>r:r=>r instanceof CSSStyleSheet?(t=>{let e="";for(const i of t.cssRules)e+=i.cssText;return Rd(e)})(r):r;/**
66
70
  * @license
67
71
  * Copyright 2017 Google LLC
68
72
  * SPDX-License-Identifier: BSD-3-Clause
69
- */const{is:$c,defineProperty:Fc,getOwnPropertyDescriptor:Nc,getOwnPropertyNames:Uc,getOwnPropertySymbols:Bc,getPrototypeOf:Hc}=Object,Ce=globalThis,Po=Ce.trustedTypes,Gc=Po?Po.emptyScript:"",Zr=Ce.reactiveElementPolyfillSupport,Ki=(r,t)=>r,Jr={toAttribute(r,t){switch(t){case Boolean:r=r?Gc:null;break;case Object:case Array:r=r==null?r:JSON.stringify(r)}return r},fromAttribute(r,t){let e=r;switch(t){case Boolean:e=r!==null;break;case Number:e=r===null?null:Number(r);break;case Object:case Array:try{e=JSON.parse(r)}catch{e=null}}return e}},tn=(r,t)=>!$c(r,t),Oo={attribute:!0,type:String,converter:Jr,reflect:!1,hasChanged:tn};Symbol.metadata??(Symbol.metadata=Symbol("metadata")),Ce.litPropertyMetadata??(Ce.litPropertyMetadata=new WeakMap);class ji extends HTMLElement{static addInitializer(t){this._$Ei(),(this.l??(this.l=[])).push(t)}static get observedAttributes(){return this.finalize(),this._$Eh&&[...this._$Eh.keys()]}static createProperty(t,e=Oo){if(e.state&&(e.attribute=!1),this._$Ei(),this.elementProperties.set(t,e),!e.noAccessor){const i=Symbol(),s=this.getPropertyDescriptor(t,i,e);s!==void 0&&Fc(this.prototype,t,s)}}static getPropertyDescriptor(t,e,i){const{get:s,set:n}=Nc(this.prototype,t)??{get(){return this[e]},set(a){this[e]=a}};return{get(){return s==null?void 0:s.call(this)},set(a){const o=s==null?void 0:s.call(this);n.call(this,a),this.requestUpdate(t,o,i)},configurable:!0,enumerable:!0}}static getPropertyOptions(t){return this.elementProperties.get(t)??Oo}static _$Ei(){if(this.hasOwnProperty(Ki("elementProperties")))return;const t=Hc(this);t.finalize(),t.l!==void 0&&(this.l=[...t.l]),this.elementProperties=new Map(t.elementProperties)}static finalize(){if(this.hasOwnProperty(Ki("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(Ki("properties"))){const e=this.properties,i=[...Uc(e),...Bc(e)];for(const s of i)this.createProperty(s,e[s])}const t=this[Symbol.metadata];if(t!==null){const e=litPropertyMetadata.get(t);if(e!==void 0)for(const[i,s]of e)this.elementProperties.set(i,s)}this._$Eh=new Map;for(const[e,i]of this.elementProperties){const s=this._$Eu(e,i);s!==void 0&&this._$Eh.set(s,e)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(t){const e=[];if(Array.isArray(t)){const i=new Set(t.flat(1/0).reverse());for(const s of i)e.unshift(xo(s))}else t!==void 0&&e.push(xo(t));return e}static _$Eu(t,e){const i=e.attribute;return i===!1?void 0:typeof i=="string"?i:typeof t=="string"?t.toLowerCase():void 0}constructor(){super(),this._$Ep=void 0,this.isUpdatePending=!1,this.hasUpdated=!1,this._$Em=null,this._$Ev()}_$Ev(){var t;this._$Eg=new Promise(e=>this.enableUpdating=e),this._$AL=new Map,this._$E_(),this.requestUpdate(),(t=this.constructor.l)==null||t.forEach(e=>e(this))}addController(t){var e;(this._$ES??(this._$ES=[])).push(t),this.renderRoot!==void 0&&this.isConnected&&((e=t.hostConnected)==null||e.call(t))}removeController(t){var e;(e=this._$ES)==null||e.splice(this._$ES.indexOf(t)>>>0,1)}_$E_(){const t=new Map,e=this.constructor.elementProperties;for(const i of e.keys())this.hasOwnProperty(i)&&(t.set(i,this[i]),delete this[i]);t.size>0&&(this._$Ep=t)}createRenderRoot(){const t=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return Mc(t,this.constructor.elementStyles),t}connectedCallback(){var t;this.renderRoot??(this.renderRoot=this.createRenderRoot()),this.enableUpdating(!0),(t=this._$ES)==null||t.forEach(e=>{var i;return(i=e.hostConnected)==null?void 0:i.call(e)})}enableUpdating(t){}disconnectedCallback(){var t;(t=this._$ES)==null||t.forEach(e=>{var i;return(i=e.hostDisconnected)==null?void 0:i.call(e)})}attributeChangedCallback(t,e,i){this._$AK(t,i)}_$EO(t,e){var n;const i=this.constructor.elementProperties.get(t),s=this.constructor._$Eu(t,i);if(s!==void 0&&i.reflect===!0){const a=(((n=i.converter)==null?void 0:n.toAttribute)!==void 0?i.converter:Jr).toAttribute(e,i.type);this._$Em=t,a==null?this.removeAttribute(s):this.setAttribute(s,a),this._$Em=null}}_$AK(t,e){var n;const i=this.constructor,s=i._$Eh.get(t);if(s!==void 0&&this._$Em!==s){const a=i.getPropertyOptions(s),o=typeof a.converter=="function"?{fromAttribute:a.converter}:((n=a.converter)==null?void 0:n.fromAttribute)!==void 0?a.converter:Jr;this._$Em=s,this[s]=o.fromAttribute(e,a.type),this._$Em=null}}requestUpdate(t,e,i,s=!1,n){if(t!==void 0){if(i??(i=this.constructor.getPropertyOptions(t)),!(i.hasChanged??tn)(s?n:this[t],e))return;this.C(t,e,i)}this.isUpdatePending===!1&&(this._$Eg=this._$EP())}C(t,e,i){this._$AL.has(t)||this._$AL.set(t,e),i.reflect===!0&&this._$Em!==t&&(this._$Ej??(this._$Ej=new Set)).add(t)}async _$EP(){this.isUpdatePending=!0;try{await this._$Eg}catch(e){Promise.reject(e)}const t=this.scheduleUpdate();return t!=null&&await t,!this.isUpdatePending}scheduleUpdate(){return this.performUpdate()}performUpdate(){var i;if(!this.isUpdatePending)return;if(!this.hasUpdated){if(this._$Ep){for(const[n,a]of this._$Ep)this[n]=a;this._$Ep=void 0}const s=this.constructor.elementProperties;if(s.size>0)for(const[n,a]of s)a.wrapped!==!0||this._$AL.has(n)||this[n]===void 0||this.C(n,this[n],a)}let t=!1;const e=this._$AL;try{t=this.shouldUpdate(e),t?(this.willUpdate(e),(i=this._$ES)==null||i.forEach(s=>{var n;return(n=s.hostUpdate)==null?void 0:n.call(s)}),this.update(e)):this._$ET()}catch(s){throw t=!1,this._$ET(),s}t&&this._$AE(e)}willUpdate(t){}_$AE(t){var e;(e=this._$ES)==null||e.forEach(i=>{var s;return(s=i.hostUpdated)==null?void 0:s.call(i)}),this.hasUpdated||(this.hasUpdated=!0,this.firstUpdated(t)),this.updated(t)}_$ET(){this._$AL=new Map,this.isUpdatePending=!1}get updateComplete(){return this.getUpdateComplete()}getUpdateComplete(){return this._$Eg}shouldUpdate(t){return!0}update(t){this._$Ej&&(this._$Ej=this._$Ej.forEach(e=>this._$EO(e,this[e]))),this._$ET()}updated(t){}firstUpdated(t){}}ji.elementStyles=[],ji.shadowRootOptions={mode:"open"},ji[Ki("elementProperties")]=new Map,ji[Ki("finalized")]=new Map,Zr==null||Zr({ReactiveElement:ji}),(Ce.reactiveElementVersions??(Ce.reactiveElementVersions=[])).push("2.0.0");/**
73
+ */const{is:kd,defineProperty:Id,getOwnPropertyDescriptor:Cd,getOwnPropertyNames:Dd,getOwnPropertySymbols:xd,getPrototypeOf:Pd}=Object,Ve=globalThis,Ao=Ve.trustedTypes,Od=Ao?Ao.emptyScript:"",Xr=Ve.reactiveElementPolyfillSupport,rs=(r,t)=>r,Qr={toAttribute(r,t){switch(t){case Boolean:r=r?Od:null;break;case Object:case Array:r=r==null?r:JSON.stringify(r)}return r},fromAttribute(r,t){let e=r;switch(t){case Boolean:e=r!==null;break;case Number:e=r===null?null:Number(r);break;case Object:case Array:try{e=JSON.parse(r)}catch{e=null}}return e}},Zr=(r,t)=>!kd(r,t),wo={attribute:!0,type:String,converter:Qr,reflect:!1,hasChanged:Zr};Symbol.metadata??(Symbol.metadata=Symbol("metadata")),Ve.litPropertyMetadata??(Ve.litPropertyMetadata=new WeakMap);class ns extends HTMLElement{static addInitializer(t){this._$Ei(),(this.l??(this.l=[])).push(t)}static get observedAttributes(){return this.finalize(),this._$Eh&&[...this._$Eh.keys()]}static createProperty(t,e=wo){if(e.state&&(e.attribute=!1),this._$Ei(),this.elementProperties.set(t,e),!e.noAccessor){const i=Symbol(),s=this.getPropertyDescriptor(t,i,e);s!==void 0&&Id(this.prototype,t,s)}}static getPropertyDescriptor(t,e,i){const{get:s,set:n}=Cd(this.prototype,t)??{get(){return this[e]},set(a){this[e]=a}};return{get(){return s==null?void 0:s.call(this)},set(a){const o=s==null?void 0:s.call(this);n.call(this,a),this.requestUpdate(t,o,i)},configurable:!0,enumerable:!0}}static getPropertyOptions(t){return this.elementProperties.get(t)??wo}static _$Ei(){if(this.hasOwnProperty(rs("elementProperties")))return;const t=Pd(this);t.finalize(),t.l!==void 0&&(this.l=[...t.l]),this.elementProperties=new Map(t.elementProperties)}static finalize(){if(this.hasOwnProperty(rs("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(rs("properties"))){const e=this.properties,i=[...Dd(e),...xd(e)];for(const s of i)this.createProperty(s,e[s])}const t=this[Symbol.metadata];if(t!==null){const e=litPropertyMetadata.get(t);if(e!==void 0)for(const[i,s]of e)this.elementProperties.set(i,s)}this._$Eh=new Map;for(const[e,i]of this.elementProperties){const s=this._$Eu(e,i);s!==void 0&&this._$Eh.set(s,e)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(t){const e=[];if(Array.isArray(t)){const i=new Set(t.flat(1/0).reverse());for(const s of i)e.unshift(To(s))}else t!==void 0&&e.push(To(t));return e}static _$Eu(t,e){const i=e.attribute;return i===!1?void 0:typeof i=="string"?i:typeof t=="string"?t.toLowerCase():void 0}constructor(){super(),this._$Ep=void 0,this.isUpdatePending=!1,this.hasUpdated=!1,this._$Em=null,this._$Ev()}_$Ev(){var t;this._$Eg=new Promise(e=>this.enableUpdating=e),this._$AL=new Map,this._$E_(),this.requestUpdate(),(t=this.constructor.l)==null||t.forEach(e=>e(this))}addController(t){var e;(this._$ES??(this._$ES=[])).push(t),this.renderRoot!==void 0&&this.isConnected&&((e=t.hostConnected)==null||e.call(t))}removeController(t){var e;(e=this._$ES)==null||e.splice(this._$ES.indexOf(t)>>>0,1)}_$E_(){const t=new Map,e=this.constructor.elementProperties;for(const i of e.keys())this.hasOwnProperty(i)&&(t.set(i,this[i]),delete this[i]);t.size>0&&(this._$Ep=t)}createRenderRoot(){const t=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return _d(t,this.constructor.elementStyles),t}connectedCallback(){var t;this.renderRoot??(this.renderRoot=this.createRenderRoot()),this.enableUpdating(!0),(t=this._$ES)==null||t.forEach(e=>{var i;return(i=e.hostConnected)==null?void 0:i.call(e)})}enableUpdating(t){}disconnectedCallback(){var t;(t=this._$ES)==null||t.forEach(e=>{var i;return(i=e.hostDisconnected)==null?void 0:i.call(e)})}attributeChangedCallback(t,e,i){this._$AK(t,i)}_$EO(t,e){var n;const i=this.constructor.elementProperties.get(t),s=this.constructor._$Eu(t,i);if(s!==void 0&&i.reflect===!0){const a=(((n=i.converter)==null?void 0:n.toAttribute)!==void 0?i.converter:Qr).toAttribute(e,i.type);this._$Em=t,a==null?this.removeAttribute(s):this.setAttribute(s,a),this._$Em=null}}_$AK(t,e){var n;const i=this.constructor,s=i._$Eh.get(t);if(s!==void 0&&this._$Em!==s){const a=i.getPropertyOptions(s),o=typeof a.converter=="function"?{fromAttribute:a.converter}:((n=a.converter)==null?void 0:n.fromAttribute)!==void 0?a.converter:Qr;this._$Em=s,this[s]=o.fromAttribute(e,a.type),this._$Em=null}}requestUpdate(t,e,i,s=!1,n){if(t!==void 0){if(i??(i=this.constructor.getPropertyOptions(t)),!(i.hasChanged??Zr)(s?n:this[t],e))return;this.C(t,e,i)}this.isUpdatePending===!1&&(this._$Eg=this._$EP())}C(t,e,i){this._$AL.has(t)||this._$AL.set(t,e),i.reflect===!0&&this._$Em!==t&&(this._$Ej??(this._$Ej=new Set)).add(t)}async _$EP(){this.isUpdatePending=!0;try{await this._$Eg}catch(e){Promise.reject(e)}const t=this.scheduleUpdate();return t!=null&&await t,!this.isUpdatePending}scheduleUpdate(){return this.performUpdate()}performUpdate(){var i;if(!this.isUpdatePending)return;if(!this.hasUpdated){if(this._$Ep){for(const[n,a]of this._$Ep)this[n]=a;this._$Ep=void 0}const s=this.constructor.elementProperties;if(s.size>0)for(const[n,a]of s)a.wrapped!==!0||this._$AL.has(n)||this[n]===void 0||this.C(n,this[n],a)}let t=!1;const e=this._$AL;try{t=this.shouldUpdate(e),t?(this.willUpdate(e),(i=this._$ES)==null||i.forEach(s=>{var n;return(n=s.hostUpdate)==null?void 0:n.call(s)}),this.update(e)):this._$ET()}catch(s){throw t=!1,this._$ET(),s}t&&this._$AE(e)}willUpdate(t){}_$AE(t){var e;(e=this._$ES)==null||e.forEach(i=>{var s;return(s=i.hostUpdated)==null?void 0:s.call(i)}),this.hasUpdated||(this.hasUpdated=!0,this.firstUpdated(t)),this.updated(t)}_$ET(){this._$AL=new Map,this.isUpdatePending=!1}get updateComplete(){return this.getUpdateComplete()}getUpdateComplete(){return this._$Eg}shouldUpdate(t){return!0}update(t){this._$Ej&&(this._$Ej=this._$Ej.forEach(e=>this._$EO(e,this[e]))),this._$ET()}updated(t){}firstUpdated(t){}}ns.elementStyles=[],ns.shadowRootOptions={mode:"open"},ns[rs("elementProperties")]=new Map,ns[rs("finalized")]=new Map,Xr==null||Xr({ReactiveElement:ns}),(Ve.reactiveElementVersions??(Ve.reactiveElementVersions=[])).push("2.0.0");/**
70
74
  * @license
71
75
  * Copyright 2017 Google LLC
72
76
  * SPDX-License-Identifier: BSD-3-Clause
73
- */const Vc=Symbol();let Mo=class{get taskComplete(){return this.t||(this.status===1?this.t=new Promise((t,e)=>{this.i=t,this.o=e}):this.status===3?this.t=Promise.reject(this.h):this.t=Promise.resolve(this.l)),this.t}constructor(t,e,i){var n;this.u=0,this.status=0,(this.p=t).addController(this);const s=typeof e=="object"?e:{task:e,args:i};this._=s.task,this.v=s.args,this.j=s.argsEqual??Kc,this.m=s.onComplete,this.g=s.onError,this.autoRun=s.autoRun??!0,"initialValue"in s&&(this.l=s.initialValue,this.status=2,this.k=(n=this.A)==null?void 0:n.call(this))}hostUpdate(){this.autoRun===!0&&this.O()}hostUpdated(){this.autoRun==="afterUpdate"&&this.O()}A(){if(this.v===void 0)return;const t=this.v();if(!Array.isArray(t))throw Error("The args function must return an array");return t}async O(){const t=this.A(),e=this.k;this.k=t,t===e||t===void 0||e!==void 0&&this.j(e,t)||await this.run(t)}async run(t){var a,o,l,h,d;let e,i;t??(t=this.A()),this.k=t,this.status===1?(a=this.T)==null||a.abort():(this.t=void 0,this.i=void 0,this.o=void 0),this.status=1,this.autoRun==="afterUpdate"?queueMicrotask(()=>this.p.requestUpdate()):this.p.requestUpdate();const s=++this.u;this.T=new AbortController;let n=!1;try{e=await this._(t,{signal:this.T.signal})}catch(c){n=!0,i=c}if(this.u===s){if(e===Vc)this.status=0;else{if(n===!1){try{(o=this.m)==null||o.call(this,e)}catch{}this.status=2,(l=this.i)==null||l.call(this,e)}else{try{(h=this.g)==null||h.call(this,i)}catch{}this.status=3,(d=this.o)==null||d.call(this,i)}this.l=e,this.h=i}this.p.requestUpdate()}}abort(t){var e;this.status===1&&((e=this.T)==null||e.abort(t))}get value(){return this.l}get error(){return this.h}render(t){var e,i,s,n;switch(this.status){case 0:return(e=t.initial)==null?void 0:e.call(t);case 1:return(i=t.pending)==null?void 0:i.call(t);case 2:return(s=t.complete)==null?void 0:s.call(t,this.value);case 3:return(n=t.error)==null?void 0:n.call(t,this.error);default:throw Error("Unexpected status: "+this.status)}}};const Kc=(r,t)=>r===t||r.length===t.length&&r.every((e,i)=>!tn(e,t[i])),en="https://vouchfor.com",jc="https://d2rxhdlm2q91uk.cloudfront.net",Wc="https://d1ix11aj5kfygl.cloudfront.net",Yc="https://d157jlwnudd93d.cloudfront.net",zc="https://bshyfw4h5a.execute-api.ap-southeast-2.amazonaws.com/dev",qc="https://gyzw7rpbq3.execute-api.ap-southeast-2.amazonaws.com/staging",Xc="https://vfcjuim1l3.execute-api.ap-southeast-2.amazonaws.com/prod",Qc="http://localhost:6060/v1",Zc="https://embed-staging.vouchfor.com/v1",Jc="https://embed.vouchfor.com/v1",tu="https://dev.vouchfor.com",eu="https://staging.vouchfor.com",iu="https://app.vouchfor.com";function Ps(r){if(!["dev","staging","prod"].includes(r))throw new Error(`Unknown environment: ${r}`);if(r==="dev")return{marketingUrl:en,videoUrl:jc,publicApiUrl:zc,embedApiUrl:Qc,publicRecorderUrl:tu};if(r==="staging")return{marketingUrl:en,videoUrl:Wc,publicApiUrl:qc,embedApiUrl:Zc,publicRecorderUrl:eu};if(r==="prod")return{marketingUrl:en,videoUrl:Yc,publicApiUrl:Xc,embedApiUrl:Jc,publicRecorderUrl:iu}}class su{constructor(t){this._fetching=!1,this.host=t,new Mo(this.host,async([e,i,s,n,a])=>{var o,l,h,d;try{if(t.vouch=void 0,t.template=void 0,s){let c;a&&(this.fetching=!0,c=await this.getTemplate(e,i,a)),t.vouch=s,t.template=c??((l=(o=s==null?void 0:s.settings)==null?void 0:o.template)==null?void 0:l.instance)}else if(n){this.fetching=!0;const[c,u]=await Promise.all([this.getVouch(e,i,n),a?this.getTemplate(e,i,a):null]);t.vouch=c,t.template=u??((d=(h=c==null?void 0:c.settings)==null?void 0:h.template)==null?void 0:d.instance)}}finally{this.fetching=!1}},()=>[t.env,t.apiKey,t.data,t.vouchId,t.templateId])}set fetching(t){this._fetching!==t&&(this._fetching=t,this.host.requestUpdate())}get fetching(){return this._fetching}async getVouch(t,e,i){const{embedApiUrl:s}=Ps(t);return fetch(`${s}/vouches/${i}`,{method:"GET",headers:[["X-Api-Key",e]]}).then(n=>n.json())}async getTemplate(t,e,i){const{embedApiUrl:s}=Ps(t);return fetch(`${s}/templates/${i}`,{method:"GET",headers:[["X-Api-Key",e]]}).then(n=>n.json())}}let Os;const ru=new Uint8Array(16);function nu(){if(!Os&&(Os=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!Os))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return Os(ru)}const It=[];for(let r=0;r<256;++r)It.push((r+256).toString(16).slice(1));function au(r,t=0){return It[r[t+0]]+It[r[t+1]]+It[r[t+2]]+It[r[t+3]]+"-"+It[r[t+4]]+It[r[t+5]]+"-"+It[r[t+6]]+It[r[t+7]]+"-"+It[r[t+8]]+It[r[t+9]]+"-"+It[r[t+10]]+It[r[t+11]]+It[r[t+12]]+It[r[t+13]]+It[r[t+14]]+It[r[t+15]]}const $o={randomUUID:typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function Wi(r,t,e){if($o.randomUUID&&!t&&!r)return $o.randomUUID();r=r||{};const i=r.random||(r.rng||nu)();if(i[6]=i[6]&15|64,i[8]=i[8]&63|128,t){e=e||0;for(let s=0;s<16;++s)t[e+s]=i[s];return t}return au(i)}const ou=2e3;class lu{constructor(t){this._tabId=void 0,this._clientId=void 0,this._visitorId=void 0,this._hasPlayed=!1,this._hasLoaded={},this._answersViewed={},this._streamedTime={},this._streamedPrevTimestamp={},this._createVisitor=e=>{var s,n;const{publicApiUrl:i}=Ps(this.host.env);return(n=(s=window.localStorage)==null?void 0:s.setItem)==null||n.call(s,"vouch-uid-visitor",e),navigator.sendBeacon(`${i}/api/visitor`,JSON.stringify({visitorId:e})),e},this._getReportingMetadata=()=>{var n,a;const[e,i]=((a=(n=Intl.DateTimeFormat().resolvedOptions().timeZone)==null?void 0:n.split)==null?void 0:a.call(n,"/"))??[],s={};return[...new URLSearchParams(location.search).entries()].forEach(([o,l])=>{if(/utm/.test(o)){const h=o.toLowerCase().replace(/[-_][a-z0-9]/g,d=>d.slice(-1).toUpperCase());s[h]=l}}),{source:"media_player",time:new Date,region:i,country:e,screenHeight:window.screen.height,screenWidth:window.screen.width,referrer:document.referrer,currentUrl:location.href,...s}},this._sendTrackingEvent=(e,i)=>{const{publicApiUrl:s}=Ps(this.host.env),{client:n,tab:a,request:o,visitor:l}=this._getUids();navigator.sendBeacon(`${s}/api/events`,JSON.stringify({event:e,payload:i,context:{"x-uid-client":n,"x-uid-tab":a,"x-uid-request":o,"x-uid-visitor":l,"x-reporting-metadata":this._getReportingMetadata()}}))},this._handleVouchLoaded=({detail:e})=>{e&&(this._hasLoaded[e]||(this._sendTrackingEvent("VOUCH_LOADED",{vouchId:e}),this._hasLoaded[e]=!0))},this._handlePlay=()=>{const e=this._findVouchId();e&&(this._hasPlayed||(this._sendTrackingEvent("VIDEO_PLAYED",{vouchId:e,streamStart:this.host.currentTime}),this._hasPlayed=!0))},this._handleVideoPlay=({detail:{id:e,node:i}})=>{const s=this._findVouchId();s&&(this._answersViewed[e]||(this._sendTrackingEvent("VOUCH_RESPONSE_VIEWED",{vouchId:s,answerId:e}),this._answersViewed[e]=!0),this._streamedTime[e]=i.currentTime,this._streamedPrevTimestamp[e]=Date.now())},this._handleVideoTimeUpdate=({detail:{id:e,node:i}})=>{var a,o;const s=this._findVouchId();if(!s)return;const n=Date.now();!this.host.paused&&e===((o=(a=this.host.scene)==null?void 0:a.video)==null?void 0:o.id)&&n-this._streamedPrevTimestamp[e]>ou&&(this._sendTrackingEvent("VIDEO_STREAMED",{vouchId:s,answerId:e,streamStart:this._streamedTime[e],streamEnd:i.currentTime}),this._streamedTime[e]=i.currentTime,this._streamedPrevTimestamp[e]=n)},this._handleVideoPause=({detail:{id:e,node:i}})=>{const s=this._findVouchId();s&&(this._sendTrackingEvent("VIDEO_STREAMED",{vouchId:s,answerId:e,streamStart:this._streamedTime[e],streamEnd:i.currentTime}),delete this._streamedTime[e],delete this._streamedPrevTimestamp[e])},this.host=t,t.addController(this)}_findVouchId(){if(this.host.data)return"uuid"in this.host.data?this.host.data.uuid:this.host.data.id}_getUids(){var n,a,o,l,h,d,c,u,f,p,g,v;if(typeof window>"u")return{client:null,tab:null,request:Wi()};const t=this._visitorId||((a=(n=window.localStorage)==null?void 0:n.getItem)==null?void 0:a.call(n,"vouch-uid-visitor"))||this._createVisitor(Wi()),e=this._clientId||((l=(o=window.localStorage)==null?void 0:o.getItem)==null?void 0:l.call(o,"vouch-uid-client"))||Wi(),i=this._tabId||((d=(h=window.sessionStorage)==null?void 0:h.getItem)==null?void 0:d.call(h,"vouch-uid-tab"))||Wi(),s=Wi();return t!==this._visitorId&&(this._visitorId=t,(u=(c=window.localStorage)==null?void 0:c.setItem)==null||u.call(c,"vouch-uid-visitor",t)),e!==this._clientId&&(this._clientId=e,(p=(f=window.localStorage)==null?void 0:f.setItem)==null||p.call(f,"vouch-uid-client",e)),i!==this._tabId&&(this._tabId=i,(v=(g=window.sessionStorage)==null?void 0:g.setItem)==null||v.call(g,"vouch-uid-tab",i)),{client:e,tab:i,request:s,visitor:t}}hostConnected(){requestAnimationFrame(()=>{var t,e,i,s;this.host.addEventListener("vouch:loaded",this._handleVouchLoaded),(t=this.host.mediaPlayer)==null||t.addEventListener("play",this._handlePlay),(e=this.host.mediaPlayer)==null||e.addEventListener("video:play",this._handleVideoPlay),(i=this.host.mediaPlayer)==null||i.addEventListener("video:pause",this._handleVideoPause),(s=this.host.mediaPlayer)==null||s.addEventListener("video:timeupdate",this._handleVideoTimeUpdate)})}hostDisconnected(){var t,e,i,s;this.host.removeEventListener("vouch:loaded",this._handleVouchLoaded),(t=this.host.mediaPlayer)==null||t.removeEventListener("play",this._handlePlay),(e=this.host.mediaPlayer)==null||e.removeEventListener("video:play",this._handleVideoPlay),(i=this.host.mediaPlayer)==null||i.removeEventListener("video:pause",this._handleVideoPause),(s=this.host.mediaPlayer)==null||s.removeEventListener("video:timeupdate",this._handleVideoTimeUpdate)}}var Fo=new Function("return this")().Promise,sn=!1;try{sn=new Function("return (async function(){}).constructor")()}catch(r){if(!(r instanceof SyntaxError))throw r}function No(r,t){return Object.prototype.hasOwnProperty.call(r,t)}function Yi(r,t,e){for(var i in t)No(t,i)&&(t[i]!=null&&typeof t[i]=="object"&&(i==="storage"||i==="prefixes")&&!e?r[i]=Yi({},t[i]):r[i]=t[i]);return r}function hu(r,t,e,i){var s,n;return typeof t.autoTrim=="string"?s=n=t.autoTrim:Array.isArray(t.autoTrim)&&(s=t.autoTrim[1],n=t.autoTrim[0]),(e||e===!1)&&(s=e),(i||i===!1)&&(n=i),s==="slurp"&&n==="slurp"?r.trim():(s==="_"||s==="slurp"?String.prototype.trimLeft?r=r.trimLeft():r=r.replace(/^[\s\uFEFF\xA0]+/,""):(s==="-"||s==="nl")&&(r=r.replace(/^(?:\n|\r|\r\n)/,"")),n==="_"||n==="slurp"?String.prototype.trimRight?r=r.trimRight():r=r.replace(/[\s\uFEFF\xA0]+$/,""):(n==="-"||n==="nl")&&(r=r.replace(/(?:\n|\r|\r\n)$/,"")),r)}var Ms=function(){function r(t){this.cache=t}return r.prototype.define=function(t,e){this.cache[t]=e},r.prototype.get=function(t){return this.cache[t]},r.prototype.remove=function(t){delete this.cache[t]},r.prototype.reset=function(){this.cache={}},r.prototype.load=function(t){Yi(this.cache,t,!0)},r}();function du(r,t){Object.setPrototypeOf?Object.setPrototypeOf(r,t):r.__proto__=t}function kt(r){var t=new Error(r);return du(t,kt.prototype),t}kt.prototype=Object.create(Error.prototype,{name:{value:"Squirrelly Error",enumerable:!1}});function De(r,t,e){var i=t.slice(0,e).split(/\n/),s=i.length,n=i[s-1].length+1;throw r+=" at line "+s+" col "+n+`:
74
-
75
- `+t.split(/\n/)[s-1]+`
76
- `+Array(n).join(" ")+"^",kt(r)}var xe=/^async +/,$s=/`(?:\\[\s\S]|\${(?:[^{}]|{(?:[^{}]|{[^}]*})*})*}|(?!\${)[^\\`])*`/g,Fs=/'(?:\\[\s\w"'\\`]|[^\n\r'\\])*?'/g,Ns=/"(?:\\[\s\w"'\\`]|[^\n\r"\\])*?"/g,Uo=/[.*+\-?^${}()|[\]\\]/g;function Us(r){return Uo.test(r)?r.replace(Uo,"\\$&"):r}function cu(r,t){t.rmWhitespace&&(r=r.replace(/[\r\n]+/g,`
77
- `).replace(/^\s+|\s+$/gm,"")),$s.lastIndex=0,Fs.lastIndex=0,Ns.lastIndex=0;var e=t.prefixes,i=[e.h,e.b,e.i,e.r,e.c,e.e].reduce(function(f,p){return f&&p?f+"|"+Us(p):p?Us(p):f},""),s=new RegExp("([|()]|=>)|('|\"|`|\\/\\*)|\\s*((\\/)?(-|_)?"+Us(t.tags[1])+")","g"),n=new RegExp("([^]*?)"+Us(t.tags[0])+"(-|_)?\\s*("+i+")?\\s*","g"),a=0,o=!1;function l(f,p){var g={f:[]},v=0,E="c";p==="h"||p==="b"||p==="c"?E="n":p==="r"&&(g.raw=!0,p="i");function T(K){var w=r.slice(a,K),C=w.trim();if(E==="f")C==="safe"?g.raw=!0:t.async&&xe.test(C)?(C=C.replace(xe,""),g.f.push([C,"",!0])):g.f.push([C,""]);else if(E==="fp")g.f[g.f.length-1][1]+=C;else if(E==="err"){if(C){var U=w.search(/\S/);De("invalid syntax",r,a+U)}}else g[E]=C;a=K+1}s.lastIndex=a;for(var A;(A=s.exec(r))!==null;){var y=A[1],b=A[2],S=A[3],R=A[4],D=A[5],_=A.index;if(y)y==="("?(v===0&&(E==="n"?(T(_),E="p"):E==="f"&&(T(_),E="fp")),v++):y===")"?(v--,v===0&&E!=="c"&&(T(_),E="err")):v===0&&y==="|"?(T(_),E="f"):y==="=>"&&(T(_),a+=1,E="res");else if(b){if(b==="/*"){var I=r.indexOf("*/",s.lastIndex);I===-1&&De("unclosed comment",r,A.index),s.lastIndex=I+2}else if(b==="'"){Fs.lastIndex=A.index;var N=Fs.exec(r);N?s.lastIndex=Fs.lastIndex:De("unclosed string",r,A.index)}else if(b==='"'){Ns.lastIndex=A.index;var P=Ns.exec(r);P?s.lastIndex=Ns.lastIndex:De("unclosed string",r,A.index)}else if(b==="`"){$s.lastIndex=A.index;var F=$s.exec(r);F?s.lastIndex=$s.lastIndex:De("unclosed string",r,A.index)}}else if(S)return T(_),a=_+A[0].length,n.lastIndex=a,o=D,R&&p==="h"&&(p="s"),g.t=p,g}return De("unclosed tag",r,f),g}function h(f,p){f.b=[],f.d=[];var g=!1,v=[];function E(F,K){F&&(F=hu(F,t,o,K),F&&(F=F.replace(/\\|'/g,"\\$&").replace(/\r\n|\n|\r/g,"\\n"),v.push(F)))}for(var T;(T=n.exec(r))!==null;){var A=T[1],y=T[2],b=T[3]||"",S;for(var R in e)if(e[R]===b){S=R;break}E(A,y),a=T.index+T[0].length,S||De("unrecognized tag type: "+b,r,a);var D=l(T.index,S),_=D.t;if(_==="h"){var I=D.n||"";t.async&&xe.test(I)&&(D.a=!0,D.n=I.replace(xe,"")),D=h(D),v.push(D)}else if(_==="c"){if(f.n===D.n)return g?(g.d=v,f.b.push(g)):f.d=v,f;De("Helper start and end don't match",r,T.index+T[0].length)}else if(_==="b"){g?(g.d=v,f.b.push(g)):f.d=v;var N=D.n||"";t.async&&xe.test(N)&&(D.a=!0,D.n=N.replace(xe,"")),g=D,v=[]}else if(_==="s"){var P=D.n||"";t.async&&xe.test(P)&&(D.a=!0,D.n=P.replace(xe,"")),v.push(D)}else v.push(D)}if(p)E(r.slice(a,r.length),!1),f.d=v;else throw kt('unclosed helper "'+f.n+'"');return f}var d=h({f:[]},!0);if(t.plugins)for(var c=0;c<t.plugins.length;c++){var u=t.plugins[c];u.processAST&&(d.d=u.processAST(d.d,t))}return d.d}function Bo(r,t){var e=cu(r,t),i="var tR='';"+(t.useWith?"with("+t.varName+"||{}){":"")+ze(e,t)+"if(cb){cb(null,tR)} return tR"+(t.useWith?"}":"");if(t.plugins)for(var s=0;s<t.plugins.length;s++){var n=t.plugins[s];n.processFnString&&(i=n.processFnString(i,t))}return i}function rn(r,t){for(var e=0;e<t.length;e++){var i=t[e][0],s=t[e][1],n=t[e][2];r=(n?"await ":"")+"c.l('F','"+i+"')("+r,s&&(r+=","+s),r+=")"}return r}function Ho(r,t,e,i,s,n){var a="{exec:"+(s?"async ":"")+Go(e,t,r)+",params:["+i+"]";return n&&(a+=",name:'"+n+"'"),s&&(a+=",async:true"),a+="}",a}function uu(r,t){for(var e="[",i=0;i<r.length;i++){var s=r[i];e+=Ho(t,s.res||"",s.d,s.p||"",s.a,s.n),i<r.length&&(e+=",")}return e+="]",e}function Go(r,t,e){return"function("+t+"){var tR='';"+ze(r,e)+"return tR}"}function ze(r,t){var e=0,i=r.length,s="";for(e;e<i;e++){var n=r[e];if(typeof n=="string"){var a=n;s+="tR+='"+a+"';"}else{var o=n.t,l=n.c||"",h=n.f,d=n.n||"",c=n.p||"",u=n.res||"",f=n.b,p=!!n.a;if(o==="i"){t.defaultFilter&&(l="c.l('F','"+t.defaultFilter+"')("+l+")");var g=rn(l,h);!n.raw&&t.autoEscape&&(g="c.l('F','e')("+g+")"),s+="tR+="+g+";"}else if(o==="h")if(t.storage.nativeHelpers.get(d))s+=t.storage.nativeHelpers.get(d)(n,t);else{var v=(p?"await ":"")+"c.l('H','"+d+"')("+Ho(t,u,n.d,c,p);f?v+=","+uu(f,t):v+=",[]",v+=",c)",s+="tR+="+rn(v,h)+";"}else o==="s"?s+="tR+="+rn((p?"await ":"")+"c.l('H','"+d+"')({params:["+c+"]},[],c)",h)+";":o==="e"&&(s+=l+`
78
- `)}}return s}function qe(r,t,e,i){if(t&&t.length>0)throw kt((i?"Native":"")+"Helper '"+r+"' doesn't accept blocks");if(e&&e.length>0)throw kt((i?"Native":"")+"Helper '"+r+"' doesn't accept filters")}function Vo(r,t,e,i,s){e(r[t],t).then(function(n){i+=n,t===r.length-1?s(i):Vo(r,t+1,e,i,s)})}function Ko(r,t,e,i,s,n){i(t[e],r[t[e]]).then(function(a){s+=a,e===t.length-1?n(s):Ko(r,t,e+1,i,s,n)})}var fu={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"};function pu(r){return fu[r]}function gu(r){var t=String(r);return/[&<>"']/.test(t)?t.replace(/[&<>"']/g,pu):t}var mu=new Ms({}),zi=new Ms({each:function(r,t){var e="",i=r.params[0];if(qe("each",t,!1),r.async)return new Promise(function(n){Vo(i,0,r.exec,e,n)});for(var s=0;s<i.length;s++)e+=r.exec(i[s],s);return e},foreach:function(r,t){var e=r.params[0];if(qe("foreach",t,!1),r.async)return new Promise(function(n){Ko(e,Object.keys(e),0,r.exec,"",n)});var i="";for(var s in e)No(e,s)&&(i+=r.exec(s,e[s]));return i},include:function(r,t,e){qe("include",t,!1);var i=e.storage.templates.get(r.params[0]);if(!i)throw kt('Could not fetch template "'+r.params[0]+'"');return i(r.params[1],e)},extends:function(r,t,e){var i=r.params[1]||{};i.content=r.exec();for(var s=0;s<t.length;s++){var n=t[s];i[n.name]=n.exec()}var a=e.storage.templates.get(r.params[0]);if(!a)throw kt('Could not fetch template "'+r.params[0]+'"');return a(i,e)},useScope:function(r,t){return qe("useScope",t,!1),r.exec(r.params[0])}}),vu=new Ms({if:function(r,t){qe("if",!1,r.f,!0);var e="if("+r.p+"){"+ze(r.d,t)+"}";if(r.b)for(var i=0;i<r.b.length;i++){var s=r.b[i];s.n==="else"?e+="else{"+ze(s.d,t)+"}":s.n==="elif"&&(e+="else if("+s.p+"){"+ze(s.d,t)+"}")}return e},try:function(r,t){if(qe("try",!1,r.f,!0),!r.b||r.b.length!==1||r.b[0].n!=="catch")throw kt("native helper 'try' only accepts 1 block, 'catch'");var e="try{"+ze(r.d,t)+"}",i=r.b[0];return e+="catch"+(i.res?"("+i.res+")":"")+"{"+ze(i.d,t)+"}",e},block:function(r,t){qe("block",r.b,r.f,!0);var e="if(!"+t.varName+"["+r.p+"]){tR+=("+Go(r.d,"",t)+")()}else{tR+="+t.varName+"["+r.p+"]}";return e}}),Bs=new Ms({e:gu}),nn={varName:"it",autoTrim:[!1,"nl"],autoEscape:!0,defaultFilter:!1,tags:["{{","}}"],l:function(r,t){if(r==="H"){var e=this.storage.helpers.get(t);if(e)return e;throw kt("Can't find helper '"+t+"'")}else if(r==="F"){var i=this.storage.filters.get(t);if(i)return i;throw kt("Can't find filter '"+t+"'")}},async:!1,storage:{helpers:zi,nativeHelpers:vu,filters:Bs,templates:mu},prefixes:{h:"@",b:"#",i:"",r:"*",c:"/",e:"!"},cache:!1,plugins:[],useWith:!1};nn.l.bind(nn);function qi(r,t){var e={};return Yi(e,nn),t&&Yi(e,t),r&&Yi(e,r),e.l.bind(e),e}function an(r,t){var e=qi(t||{}),i=Function;if(e.async)if(sn)i=sn;else throw kt("This environment doesn't support async/await");try{return new i(e.varName,"c","cb",Bo(r,e))}catch(s){throw s instanceof SyntaxError?kt(`Bad template syntax
79
-
80
- `+s.message+`
81
- `+Array(s.message.length+1).join("=")+`
82
- `+Bo(r,e)):s}}var on=require("fs"),ln=require("path"),yu=/^\uFEFF/;function hn(r,t,e){var i=ln.resolve(e?t:ln.dirname(t),r),s=ln.extname(r);return s||(i+=".sqrl"),i}function Eu(r,t){var e,i,s=t.views,n=/^[A-Za-z]+:\\|^\//.exec(r);if(n&&n.length)e=hn(r.replace(/^\/*/,""),t.root||"/",!0);else if(t.filename&&(i=hn(r,t.filename),on.existsSync(i)&&(e=i)),e||Array.isArray(s)&&s.some(function(a){return i=hn(r,a,!0),on.existsSync(i)})&&(e=i),!e)throw kt('Could not find the include file "'+r+'"');return e}function jo(r){return on.readFileSync(r).toString().replace(yu,"")}function Tu(r,t){var e=qi(t),i=jo(r);try{var s=an(i,e);return e.storage.templates.define(e.filename,s),s}catch{throw kt("Loading file: "+r+" failed")}}function bu(r){var t=r.filename;if(r.cache){var e=r.storage.templates.get(t);return e||Tu(t,r)}return an(jo(t),r)}function Wo(r,t){var e=qi({filename:Eu(r,t)},t);return bu(e)}function Au(r,t,e){if(t&&t.length>0)throw kt("Helper 'includeFile' doesn't accept blocks");return Wo(r.params[0],e)(r.params[1],e)}function wu(r,t,e){var i=r.params[1]||{};i.content=r.exec();for(var s=0;s<t.length;s++){var n=t[s];i[n.name]=n.exec()}return Wo(r.params[0],e)(i,e)}function dn(r,t){var e;return t.cache&&t.name&&t.storage.templates.get(t.name)?t.storage.templates.get(t.name):(typeof r=="function"?e=r:e=an(r,t),t.cache&&t.name&&t.storage.templates.define(t.name,e),e)}function Su(r,t,e,i){var s=qi(e||{});if(s.async){var n;if(i)try{dn(r,s)(t,s,i)}catch(a){return i(a)}else{if(typeof Fo=="function")return new Fo(function(a,o){try{n=dn(r,s)(t,s),a(n)}catch(l){o(l)}});throw kt("Please provide a callback function, this env doesn't support Promises")}}else return dn(r,s)(t,s)}zi.define("includeFile",Au),zi.define("extendsFile",wu);var cn=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function un(r){return r&&r.__esModule&&Object.prototype.hasOwnProperty.call(r,"default")?r.default:r}var fn={exports:{}};(function(r,t){var e=typeof globalThis<"u"&&globalThis||typeof self<"u"&&self||typeof cn<"u"&&cn,i=function(){function n(){this.fetch=!1,this.DOMException=e.DOMException}return n.prototype=e,new n}();(function(n){(function(a){var o=typeof n<"u"&&n||typeof self<"u"&&self||typeof o<"u"&&o,l={searchParams:"URLSearchParams"in o,iterable:"Symbol"in o&&"iterator"in Symbol,blob:"FileReader"in o&&"Blob"in o&&function(){try{return new Blob,!0}catch{return!1}}(),formData:"FormData"in o,arrayBuffer:"ArrayBuffer"in o};function h(w){return w&&DataView.prototype.isPrototypeOf(w)}if(l.arrayBuffer)var d=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],c=ArrayBuffer.isView||function(w){return w&&d.indexOf(Object.prototype.toString.call(w))>-1};function u(w){if(typeof w!="string"&&(w=String(w)),/[^a-z0-9\-#$%&'*+.^_`|~!]/i.test(w)||w==="")throw new TypeError('Invalid character in header field name: "'+w+'"');return w.toLowerCase()}function f(w){return typeof w!="string"&&(w=String(w)),w}function p(w){var C={next:function(){var U=w.shift();return{done:U===void 0,value:U}}};return l.iterable&&(C[Symbol.iterator]=function(){return C}),C}function g(w){this.map={},w instanceof g?w.forEach(function(C,U){this.append(U,C)},this):Array.isArray(w)?w.forEach(function(C){this.append(C[0],C[1])},this):w&&Object.getOwnPropertyNames(w).forEach(function(C){this.append(C,w[C])},this)}g.prototype.append=function(w,C){w=u(w),C=f(C);var U=this.map[w];this.map[w]=U?U+", "+C:C},g.prototype.delete=function(w){delete this.map[u(w)]},g.prototype.get=function(w){return w=u(w),this.has(w)?this.map[w]:null},g.prototype.has=function(w){return this.map.hasOwnProperty(u(w))},g.prototype.set=function(w,C){this.map[u(w)]=f(C)},g.prototype.forEach=function(w,C){for(var U in this.map)this.map.hasOwnProperty(U)&&w.call(C,this.map[U],U,this)},g.prototype.keys=function(){var w=[];return this.forEach(function(C,U){w.push(U)}),p(w)},g.prototype.values=function(){var w=[];return this.forEach(function(C){w.push(C)}),p(w)},g.prototype.entries=function(){var w=[];return this.forEach(function(C,U){w.push([U,C])}),p(w)},l.iterable&&(g.prototype[Symbol.iterator]=g.prototype.entries);function v(w){if(w.bodyUsed)return Promise.reject(new TypeError("Already read"));w.bodyUsed=!0}function E(w){return new Promise(function(C,U){w.onload=function(){C(w.result)},w.onerror=function(){U(w.error)}})}function T(w){var C=new FileReader,U=E(C);return C.readAsArrayBuffer(w),U}function A(w){var C=new FileReader,U=E(C);return C.readAsText(w),U}function y(w){for(var C=new Uint8Array(w),U=new Array(C.length),M=0;M<C.length;M++)U[M]=String.fromCharCode(C[M]);return U.join("")}function b(w){if(w.slice)return w.slice(0);var C=new Uint8Array(w.byteLength);return C.set(new Uint8Array(w)),C.buffer}function S(){return this.bodyUsed=!1,this._initBody=function(w){this.bodyUsed=this.bodyUsed,this._bodyInit=w,w?typeof w=="string"?this._bodyText=w:l.blob&&Blob.prototype.isPrototypeOf(w)?this._bodyBlob=w:l.formData&&FormData.prototype.isPrototypeOf(w)?this._bodyFormData=w:l.searchParams&&URLSearchParams.prototype.isPrototypeOf(w)?this._bodyText=w.toString():l.arrayBuffer&&l.blob&&h(w)?(this._bodyArrayBuffer=b(w.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):l.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(w)||c(w))?this._bodyArrayBuffer=b(w):this._bodyText=w=Object.prototype.toString.call(w):this._bodyText="",this.headers.get("content-type")||(typeof w=="string"?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):l.searchParams&&URLSearchParams.prototype.isPrototypeOf(w)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},l.blob&&(this.blob=function(){var w=v(this);if(w)return w;if(this._bodyBlob)return Promise.resolve(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(new Blob([this._bodyArrayBuffer]));if(this._bodyFormData)throw new Error("could not read FormData body as blob");return Promise.resolve(new Blob([this._bodyText]))},this.arrayBuffer=function(){if(this._bodyArrayBuffer){var w=v(this);return w||(ArrayBuffer.isView(this._bodyArrayBuffer)?Promise.resolve(this._bodyArrayBuffer.buffer.slice(this._bodyArrayBuffer.byteOffset,this._bodyArrayBuffer.byteOffset+this._bodyArrayBuffer.byteLength)):Promise.resolve(this._bodyArrayBuffer))}else return this.blob().then(T)}),this.text=function(){var w=v(this);if(w)return w;if(this._bodyBlob)return A(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(y(this._bodyArrayBuffer));if(this._bodyFormData)throw new Error("could not read FormData body as text");return Promise.resolve(this._bodyText)},l.formData&&(this.formData=function(){return this.text().then(I)}),this.json=function(){return this.text().then(JSON.parse)},this}var R=["DELETE","GET","HEAD","OPTIONS","POST","PUT"];function D(w){var C=w.toUpperCase();return R.indexOf(C)>-1?C:w}function _(w,C){if(!(this instanceof _))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');C=C||{};var U=C.body;if(w instanceof _){if(w.bodyUsed)throw new TypeError("Already read");this.url=w.url,this.credentials=w.credentials,C.headers||(this.headers=new g(w.headers)),this.method=w.method,this.mode=w.mode,this.signal=w.signal,!U&&w._bodyInit!=null&&(U=w._bodyInit,w.bodyUsed=!0)}else this.url=String(w);if(this.credentials=C.credentials||this.credentials||"same-origin",(C.headers||!this.headers)&&(this.headers=new g(C.headers)),this.method=D(C.method||this.method||"GET"),this.mode=C.mode||this.mode||null,this.signal=C.signal||this.signal,this.referrer=null,(this.method==="GET"||this.method==="HEAD")&&U)throw new TypeError("Body not allowed for GET or HEAD requests");if(this._initBody(U),(this.method==="GET"||this.method==="HEAD")&&(C.cache==="no-store"||C.cache==="no-cache")){var M=/([?&])_=[^&]*/;if(M.test(this.url))this.url=this.url.replace(M,"$1_="+new Date().getTime());else{var B=/\?/;this.url+=(B.test(this.url)?"&":"?")+"_="+new Date().getTime()}}}_.prototype.clone=function(){return new _(this,{body:this._bodyInit})};function I(w){var C=new FormData;return w.trim().split("&").forEach(function(U){if(U){var M=U.split("="),B=M.shift().replace(/\+/g," "),H=M.join("=").replace(/\+/g," ");C.append(decodeURIComponent(B),decodeURIComponent(H))}}),C}function N(w){var C=new g,U=w.replace(/\r?\n[\t ]+/g," ");return U.split("\r").map(function(M){return M.indexOf(`
83
- `)===0?M.substr(1,M.length):M}).forEach(function(M){var B=M.split(":"),H=B.shift().trim();if(H){var z=B.join(":").trim();C.append(H,z)}}),C}S.call(_.prototype);function P(w,C){if(!(this instanceof P))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');C||(C={}),this.type="default",this.status=C.status===void 0?200:C.status,this.ok=this.status>=200&&this.status<300,this.statusText=C.statusText===void 0?"":""+C.statusText,this.headers=new g(C.headers),this.url=C.url||"",this._initBody(w)}S.call(P.prototype),P.prototype.clone=function(){return new P(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new g(this.headers),url:this.url})},P.error=function(){var w=new P(null,{status:0,statusText:""});return w.type="error",w};var F=[301,302,303,307,308];P.redirect=function(w,C){if(F.indexOf(C)===-1)throw new RangeError("Invalid status code");return new P(null,{status:C,headers:{location:w}})},a.DOMException=o.DOMException;try{new a.DOMException}catch{a.DOMException=function(C,U){this.message=C,this.name=U;var M=Error(C);this.stack=M.stack},a.DOMException.prototype=Object.create(Error.prototype),a.DOMException.prototype.constructor=a.DOMException}function K(w,C){return new Promise(function(U,M){var B=new _(w,C);if(B.signal&&B.signal.aborted)return M(new a.DOMException("Aborted","AbortError"));var H=new XMLHttpRequest;function z(){H.abort()}H.onload=function(){var Q={status:H.status,statusText:H.statusText,headers:N(H.getAllResponseHeaders()||"")};Q.url="responseURL"in H?H.responseURL:Q.headers.get("X-Request-URL");var it="response"in H?H.response:H.responseText;setTimeout(function(){U(new P(it,Q))},0)},H.onerror=function(){setTimeout(function(){M(new TypeError("Network request failed"))},0)},H.ontimeout=function(){setTimeout(function(){M(new TypeError("Network request failed"))},0)},H.onabort=function(){setTimeout(function(){M(new a.DOMException("Aborted","AbortError"))},0)};function Z(Q){try{return Q===""&&o.location.href?o.location.href:Q}catch{return Q}}H.open(B.method,Z(B.url),!0),B.credentials==="include"?H.withCredentials=!0:B.credentials==="omit"&&(H.withCredentials=!1),"responseType"in H&&(l.blob?H.responseType="blob":l.arrayBuffer&&B.headers.get("Content-Type")&&B.headers.get("Content-Type").indexOf("application/octet-stream")!==-1&&(H.responseType="arraybuffer")),C&&typeof C.headers=="object"&&!(C.headers instanceof g)?Object.getOwnPropertyNames(C.headers).forEach(function(Q){H.setRequestHeader(Q,f(C.headers[Q]))}):B.headers.forEach(function(Q,it){H.setRequestHeader(it,Q)}),B.signal&&(B.signal.addEventListener("abort",z),H.onreadystatechange=function(){H.readyState===4&&B.signal.removeEventListener("abort",z)}),H.send(typeof B._bodyInit>"u"?null:B._bodyInit)})}return K.polyfill=!0,o.fetch||(o.fetch=K,o.Headers=g,o.Request=_,o.Response=P),a.Headers=g,a.Request=_,a.Response=P,a.fetch=K,a})({})})(i),i.fetch.ponyfill=!0,delete i.fetch.polyfill;var s=e.fetch?e:i;t=s.fetch,t.default=s.fetch,t.fetch=s.fetch,t.Headers=s.Headers,t.Request=s.Request,t.Response=s.Response,r.exports=t})(fn,fn.exports);var Lu=fn.exports;const Ru=un(Lu);function _u({canvas:r,scenes:t,currentTime:e}){if(t&&r){const i=t.scenes.filter(({start:n,duration:a})=>e>=n&&e<=n+a);if(i.length<=0)return;const s=r.getContext("2d");if(s){const n=t.transitionDuration,a=Math.max(...t.scenes.map(({start:o,duration:l})=>o+l));s.globalCompositeOperation="lighter",s.clearRect(0,0,r.width,r.height),i.forEach(({start:o,duration:l,draw:h,transitionCanvas:d})=>{s.globalAlpha=1,d.width=d.height=0,d.width=r.width,d.height=r.height;const c=d.getContext("2d");if(c){const u=o+l,f=o===0,p=u===a;h({currentTime:e,canvas:d,context:c}),!f&&e>=o&&e<=o+n/2?s.globalAlpha=Math.max(0,Math.min(1,(e-o)/(n/2))):!p&&e>=u-n/2&&e<=u&&(s.globalAlpha=Math.max(0,Math.min(1,(u-e)/(n/2)))),s.drawImage(d,0,0,r.width,r.height)}})}}}function Iu(r){if(typeof r=="string"){const[t,e]=r.split(":");return Math.min(parseFloat(t),parseFloat(e))}return r}function ku(r){if(typeof r=="string"){const[t,e]=r.split(":"),i=parseFloat(t),s=parseFloat(e);return i/s}return r}function gi({resolution:r,aspectRatio:t}){const e=Iu(r),i=ku(t),s=i>=1,n=Math.min(s?e*i:e/i,e),a=Math.max(s?e*i:e/i,e);return{resolution:e,aspectRatio:i,height:s?n:a,width:s?a:n}}function Cu({format:r,resolution:t,aspectRatio:e,videoResolution:i,videoAspectRatio:s}){const{height:n,width:a}=gi({resolution:t,aspectRatio:e}),{height:o,width:l}=gi({resolution:i,aspectRatio:s}),h=e>s;let d=1;if(r==="letterbox"||r==="letterbox-video")d=h?n/o:a/l;else if(r==="squarebox"){const g=Math.min(n,a);d=l>=o?g/o:g/l}else(r==="crop"||r==="crop-top")&&(d=h?a/l:n/o);const c=a/d,u=n/d,f=(l-c)/2;let p=(o-u)/2;return r==="crop-top"&&(p=Math.min(0,p)),{sx:f,sy:p,sWidth:c,sHeight:u,scale:d}}function Hs({source:r,sx:t,sy:e,sw:i,sh:s,dx:n,dy:a,dw:o,dh:l}){const h=(r==null?void 0:r.naturalWidth)??(r==null?void 0:r.videoWidth)??(r==null?void 0:r.width),d=(r==null?void 0:r.naturalHeight)??(r==null?void 0:r.videoHeight)??(r==null?void 0:r.height);t=t??0,e=e??0,i=i??h,s=s??d,i<0&&(t+=i,i=Math.abs(i)),s<0&&(e+=s,s=Math.abs(s)),o<0&&(n+=o,o=Math.abs(o)),l<0&&(a+=l,l=Math.abs(l));const c=Math.max(t,0),u=Math.min(t+i,h),f=Math.max(e,0),p=Math.min(e+s,d),g=o/i,v=l/s;return[r,c,f,u-c,p-f,t<0?n-t*g:n,e<0?a-e*v:a,(u-c)*g,(p-f)*v]}function Yo({context:r,source:t,format:e="letterbox",videoResolution:i,videoAspectRatio:s,posX:n,posY:a,width:o,height:l,offscreenCanvas:h}){const{sx:d,sy:c,sWidth:u,sHeight:f,scale:p}=Cu({resolution:Math.min(o,l),aspectRatio:o/l,format:e,videoResolution:i,videoAspectRatio:s}),g=h&&typeof r.filter<"u";if(e==="letterbox"||e==="squarebox"||e==="letterbox-video"&&!g){if(d<0){const y=Math.abs(d)*p;r.fillStyle="black",r.beginPath(),r.rect(n,a,y,l),r.rect(n+o-y,a,y,l),r.fill(),r.closePath()}if(c<0){const y=Math.abs(c)*p;r.fillStyle="black",r.beginPath(),r.rect(n,a,o,y),r.rect(n,a+l-y,o,y),r.fill(),r.closePath()}}if(e==="letterbox-video"&&g){const{width:y,height:b}=gi({resolution:i,aspectRatio:s});h.width=y,h.height=b;const S=h.getContext("2d",{alpha:!1});if(S==null||S.drawImage(t,0,0,y,b),S){r.save(),r.globalCompositeOperation="destination-out",r.fillRect(n,a,o,l);const R=Hs({source:h,sx:d,sy:c,sw:u,sh:f,dx:n,dy:a,dw:o,dh:l});r.globalCompositeOperation="source-over",r.drawImage(...R),S.save();const D=1.3,_=-(y*D-y)/2,I=-(b*D-b)/2;if(S.filter="blur(40px) brightness(20%)",S.translate(_,I),S.scale(D,D),S.drawImage(h,0,0,y,b),S.restore(),r.globalCompositeOperation="destination-over",d<0){const N=o/s,P=l/N,F=Hs({source:h,sy:(1-P)*b/2,sh:P*b,dx:n,dy:a,dw:o,dh:l});r.drawImage(...F)}if(c<0){const N=l*s,P=o/N,F=Hs({source:h,sx:(1-P)*y/2,sw:P*y,dx:n,dy:a,dw:o,dh:l});r.drawImage(...F)}r.restore()}}else{const y=Hs({source:t,sx:d,sy:c,sw:u,sh:f,dx:n,dy:a,dw:o,dh:l});r.drawImage(...y)}const v=d*-1*p,E=c*-1*p,T=o-v*2,A=l-E*2;return{dx:v,dy:E,dw:T,dh:A}}const Du=/\d{0,2}:?\d{2}:\d{2}\.\d{3}\s-->\s\d{0,2}:?\d{2}:\d{2}\.\d{3}\s{1,2}.*/g,xu=/\d{0,2}:?\d{2}:\d{2}\.\d{3}/g;function zo(r){if(!r)return[];const t=r.match(Du);return t?t==null?void 0:t.map(e=>{const[i,s]=e.replace(`\r
77
+ */const $d=Symbol();class So{get taskComplete(){return this.t||(this.status===1?this.t=new Promise((t,e)=>{this.i=t,this.o=e}):this.status===3?this.t=Promise.reject(this.h):this.t=Promise.resolve(this.l)),this.t}constructor(t,e,i){var n;this.u=0,this.status=0,(this.p=t).addController(this);const s=typeof e=="object"?e:{task:e,args:i};this._=s.task,this.v=s.args,this.j=s.argsEqual??Md,this.m=s.onComplete,this.g=s.onError,this.autoRun=s.autoRun??!0,"initialValue"in s&&(this.l=s.initialValue,this.status=2,this.k=(n=this.A)==null?void 0:n.call(this))}hostUpdate(){this.autoRun===!0&&this.O()}hostUpdated(){this.autoRun==="afterUpdate"&&this.O()}A(){if(this.v===void 0)return;const t=this.v();if(!Array.isArray(t))throw Error("The args function must return an array");return t}async O(){const t=this.A(),e=this.k;this.k=t,t===e||t===void 0||e!==void 0&&this.j(e,t)||await this.run(t)}async run(t){var a,o,l,h,c;let e,i;t??(t=this.A()),this.k=t,this.status===1?(a=this.T)==null||a.abort():(this.t=void 0,this.i=void 0,this.o=void 0),this.status=1,this.autoRun==="afterUpdate"?queueMicrotask(()=>this.p.requestUpdate()):this.p.requestUpdate();const s=++this.u;this.T=new AbortController;let n=!1;try{e=await this._(t,{signal:this.T.signal})}catch(d){n=!0,i=d}if(this.u===s){if(e===$d)this.status=0;else{if(n===!1){try{(o=this.m)==null||o.call(this,e)}catch{}this.status=2,(l=this.i)==null||l.call(this,e)}else{try{(h=this.g)==null||h.call(this,i)}catch{}this.status=3,(c=this.o)==null||c.call(this,i)}this.l=e,this.h=i}this.p.requestUpdate()}}abort(t){var e;this.status===1&&((e=this.T)==null||e.abort(t))}get value(){return this.l}get error(){return this.h}render(t){var e,i,s,n;switch(this.status){case 0:return(e=t.initial)==null?void 0:e.call(t);case 1:return(i=t.pending)==null?void 0:i.call(t);case 2:return(s=t.complete)==null?void 0:s.call(t,this.value);case 3:return(n=t.error)==null?void 0:n.call(t,this.error);default:throw Error("Unexpected status: "+this.status)}}}const Md=(r,t)=>r===t||r.length===t.length&&r.every((e,i)=>!Zr(e,t[i])),Lo="https://d2rxhdlm2q91uk.cloudfront.net",Fd="https://d1ix11aj5kfygl.cloudfront.net",Nd="https://d157jlwnudd93d.cloudfront.net",Ro="https://bshyfw4h5a.execute-api.ap-southeast-2.amazonaws.com/dev",Ud="https://gyzw7rpbq3.execute-api.ap-southeast-2.amazonaws.com/staging",Bd="https://vfcjuim1l3.execute-api.ap-southeast-2.amazonaws.com/prod",Hd="http://localhost:6060/v2",Gd="https://embed-dev.vouchfor.com/v2",Vd="https://embed-staging.vouchfor.com/v2",Kd="https://embed.vouchfor.com/v2";function Bs(r){if(!["local","dev","staging","prod"].includes(r))throw new Error(`Unknown environment: ${r}`);if(r==="local")return{videoUrl:Lo,publicApiUrl:Ro,embedApiUrl:Hd};if(r==="dev")return{videoUrl:Lo,publicApiUrl:Ro,embedApiUrl:Gd};if(r==="staging")return{videoUrl:Fd,publicApiUrl:Ud,embedApiUrl:Vd};if(r==="prod")return{videoUrl:Nd,publicApiUrl:Bd,embedApiUrl:Kd}}class jd{constructor(t){this._fetching=!1,this.getVouch=async(e,i,s)=>{const{embedApiUrl:n}=Bs(e),a=await fetch(`${n}/vouches/${s}`,{method:"GET",headers:[["X-Api-Key",i]]}).then(o=>(this.host.dispatchEvent(new CustomEvent("vouch:loaded",{detail:s})),o.json()));return fetch(`${n}/vouches/${s}`,{method:"GET",headers:[["X-Api-Key",i],["Cache-Control","max-age=0"]]}),a},this.getTemplate=async(e,i,s)=>{const{embedApiUrl:n}=Bs(e),a=await fetch(`${n}/templates/${s}`,{method:"GET",headers:[["X-Api-Key",i]]}).then(o=>o.json());return fetch(`${n}/templates/${s}`,{method:"GET",headers:[["X-Api-Key",i],["Cache-Control","max-age=0"]]}),a},this.host=t,new So(this.host,async([e,i,s,n,a])=>{var o,l,h,c;try{if(t.vouch=void 0,t.template=void 0,s){let d;a&&(this.fetching=!0,d=await this.getTemplate(e,i,a)),t.vouch=s,t.template=d??((l=(o=s==null?void 0:s.settings)==null?void 0:o.template)==null?void 0:l.instance)}else if(n){this.fetching=!0;const[d,u]=await Promise.all([this.getVouch(e,i,n),a?this.getTemplate(e,i,a):null]);t.vouch=d,t.template=u??((c=(h=d==null?void 0:d.settings)==null?void 0:h.template)==null?void 0:c.instance)}}finally{this.fetching=!1}},()=>[t.env,t.apiKey,t.data,t.vouchId,t.templateId])}set fetching(t){this._fetching!==t&&(this._fetching=t,this.host.requestUpdate())}get fetching(){return this._fetching}}let Hs;const Wd=new Uint8Array(16);function Yd(){if(!Hs&&(Hs=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!Hs))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return Hs(Wd)}const Nt=[];for(let r=0;r<256;++r)Nt.push((r+256).toString(16).slice(1));function zd(r,t=0){return Nt[r[t+0]]+Nt[r[t+1]]+Nt[r[t+2]]+Nt[r[t+3]]+"-"+Nt[r[t+4]]+Nt[r[t+5]]+"-"+Nt[r[t+6]]+Nt[r[t+7]]+"-"+Nt[r[t+8]]+Nt[r[t+9]]+"-"+Nt[r[t+10]]+Nt[r[t+11]]+Nt[r[t+12]]+Nt[r[t+13]]+Nt[r[t+14]]+Nt[r[t+15]]}const _o={randomUUID:typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function as(r,t,e){if(_o.randomUUID&&!t&&!r)return _o.randomUUID();r=r||{};const i=r.random||(r.rng||Yd)();if(i[6]=i[6]&15|64,i[8]=i[8]&63|128,t){e=e||0;for(let s=0;s<16;++s)t[e+s]=i[s];return t}return zd(i)}const qd=2e3;class Xd{constructor(t){this._tabId=void 0,this._clientId=void 0,this._visitorId=void 0,this._hasPlayed=!1,this._hasLoaded={},this._answersViewed={},this._streamedTime={},this._streamedPrevTimestamp={},this._createVisitor=e=>{var s,n;const{publicApiUrl:i}=Bs(this.host.env);return(n=(s=window.localStorage)==null?void 0:s.setItem)==null||n.call(s,"vouch-uid-visitor",e),navigator.sendBeacon(`${i}/api/visitor`,JSON.stringify({visitorId:e})),e},this._getReportingMetadata=()=>{var n,a;const[e,i]=((a=(n=Intl.DateTimeFormat().resolvedOptions().timeZone)==null?void 0:n.split)==null?void 0:a.call(n,"/"))??[],s={};return[...new URLSearchParams(location.search).entries()].forEach(([o,l])=>{if(/utm/.test(o)){const h=o.toLowerCase().replace(/[-_][a-z0-9]/g,c=>c.slice(-1).toUpperCase());s[h]=l}}),{source:this.host.trackingSource,time:new Date,region:i,country:e,screenHeight:window.screen.height,screenWidth:window.screen.width,referrer:document.referrer,currentUrl:location.href,...s}},this._sendTrackingEvent=(e,i)=>{const{publicApiUrl:s}=Bs(this.host.env),{client:n,tab:a,request:o,visitor:l}=this._getUids();navigator.sendBeacon(`${s}/api/events`,JSON.stringify({event:e,payload:i,context:{"x-uid-client":n,"x-uid-tab":a,"x-uid-request":o,"x-uid-visitor":l,"x-reporting-metadata":this._getReportingMetadata()}}))},this._handleVouchLoaded=({detail:e})=>{e&&(this._hasLoaded[e]||(this._sendTrackingEvent("VOUCH_LOADED",{vouchId:e}),this._hasLoaded[e]=!0))},this._handlePlay=()=>{const e=this._findVouchId();e&&(this._hasPlayed||(this._sendTrackingEvent("VIDEO_PLAYED",{vouchId:e,streamStart:this.host.currentTime}),this._hasPlayed=!0))},this._handleVideoPlay=({detail:{id:e,node:i}})=>{const s=this._findVouchId();s&&(this._answersViewed[e]||(this._sendTrackingEvent("VOUCH_RESPONSE_VIEWED",{vouchId:s,answerId:e}),this._answersViewed[e]=!0),this._streamedTime[e]=i.currentTime,this._streamedPrevTimestamp[e]=Date.now())},this._handleVideoTimeUpdate=({detail:{id:e,node:i}})=>{var a,o;const s=this._findVouchId();if(!s)return;const n=Date.now();!this.host.paused&&e===((o=(a=this.host.scene)==null?void 0:a.video)==null?void 0:o.id)&&n-this._streamedPrevTimestamp[e]>qd&&(this._sendTrackingEvent("VIDEO_STREAMED",{vouchId:s,answerId:e,streamStart:this._streamedTime[e],streamEnd:i.currentTime}),this._streamedTime[e]=i.currentTime,this._streamedPrevTimestamp[e]=n)},this._handleVideoPause=({detail:{id:e,node:i}})=>{const s=this._findVouchId();s&&(this._sendTrackingEvent("VIDEO_STREAMED",{vouchId:s,answerId:e,streamStart:this._streamedTime[e],streamEnd:i.currentTime}),delete this._streamedTime[e],delete this._streamedPrevTimestamp[e])},this.host=t,t.addController(this)}_findVouchId(){if(this.host.data)return"uuid"in this.host.data?this.host.data.uuid:this.host.data.id}_getUids(){var n,a,o,l,h,c,d,u,f,p,g,v;if(typeof window>"u")return{client:null,tab:null,request:as()};const t=this._visitorId||((a=(n=window.localStorage)==null?void 0:n.getItem)==null?void 0:a.call(n,"vouch-uid-visitor"))||this._createVisitor(as()),e=this._clientId||((l=(o=window.localStorage)==null?void 0:o.getItem)==null?void 0:l.call(o,"vouch-uid-client"))||as(),i=this._tabId||((c=(h=window.sessionStorage)==null?void 0:h.getItem)==null?void 0:c.call(h,"vouch-uid-tab"))||as(),s=as();return t!==this._visitorId&&(this._visitorId=t,(u=(d=window.localStorage)==null?void 0:d.setItem)==null||u.call(d,"vouch-uid-visitor",t)),e!==this._clientId&&(this._clientId=e,(p=(f=window.localStorage)==null?void 0:f.setItem)==null||p.call(f,"vouch-uid-client",e)),i!==this._tabId&&(this._tabId=i,(v=(g=window.sessionStorage)==null?void 0:g.setItem)==null||v.call(g,"vouch-uid-tab",i)),{client:e,tab:i,request:s,visitor:t}}hostConnected(){requestAnimationFrame(()=>{var t,e,i,s;this.host.addEventListener("vouch:loaded",this._handleVouchLoaded),(t=this.host.mediaPlayer)==null||t.addEventListener("play",this._handlePlay),(e=this.host.mediaPlayer)==null||e.addEventListener("video:play",this._handleVideoPlay),(i=this.host.mediaPlayer)==null||i.addEventListener("video:pause",this._handleVideoPause),(s=this.host.mediaPlayer)==null||s.addEventListener("video:timeupdate",this._handleVideoTimeUpdate)})}hostDisconnected(){var t,e,i,s;this.host.removeEventListener("vouch:loaded",this._handleVouchLoaded),(t=this.host.mediaPlayer)==null||t.removeEventListener("play",this._handlePlay),(e=this.host.mediaPlayer)==null||e.removeEventListener("video:play",this._handleVideoPlay),(i=this.host.mediaPlayer)==null||i.removeEventListener("video:pause",this._handleVideoPause),(s=this.host.mediaPlayer)==null||s.removeEventListener("video:timeupdate",this._handleVideoTimeUpdate)}}const Qd=(r,t,e,i)=>{if(e==="length"||e==="prototype"||e==="arguments"||e==="caller")return;const s=Object.getOwnPropertyDescriptor(r,e),n=Object.getOwnPropertyDescriptor(t,e);!Zd(s,n)&&i||Object.defineProperty(r,e,n)},Zd=function(r,t){return r===void 0||r.configurable||r.writable===t.writable&&r.enumerable===t.enumerable&&r.configurable===t.configurable&&(r.writable||r.value===t.value)},Jd=(r,t)=>{const e=Object.getPrototypeOf(t);e!==Object.getPrototypeOf(r)&&Object.setPrototypeOf(r,e)},tu=(r,t)=>`/* Wrapped ${r}*/
78
+ ${t}`,eu=Object.getOwnPropertyDescriptor(Function.prototype,"toString"),iu=Object.getOwnPropertyDescriptor(Function.prototype.toString,"name"),su=(r,t,e)=>{const i=e===""?"":`with ${e.trim()}() `,s=tu.bind(null,i,t.toString());Object.defineProperty(s,"name",iu),Object.defineProperty(r,"toString",{...eu,value:s})};function ru(r,t,{ignoreNonConfigurable:e=!1}={}){const{name:i}=r;for(const s of Reflect.ownKeys(t))Qd(r,t,s,e);return Jd(r,t),su(r,t,i),r}const nu=new WeakMap;function os(r,{cacheKey:t=([i])=>i,cache:e=new Map}={}){const i=new Map,s=function(...n){const a=t(n);if(i.has(a))return i.get(a);const o=(async()=>{try{if(e&&await e.has(a))return await e.get(a);const h=await r.apply(this,n);try{return h}finally{e&&await e.set(a,h)}}finally{i.delete(a)}})();return i.set(a,o),o};return ru(s,r,{ignoreNonConfigurable:!0}),nu.set(s,e),s}var Gs=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Jr(r){return r&&r.__esModule&&Object.prototype.hasOwnProperty.call(r,"default")?r.default:r}var tn={exports:{}};(function(r,t){(function(e,i){i(t)})(Gs,function(e){function i(b){var T,k,N=new Error(b);return T=N,k=i.prototype,Object.setPrototypeOf?Object.setPrototypeOf(T,k):T.__proto__=k,N}function s(b,T,k){var N=T.slice(0,k).split(/\n/),U=N.length,K=N[U-1].length+1;throw i(b+=" at line "+U+" col "+K+`:
79
+
80
+ `+T.split(/\n/)[U-1]+`
81
+ `+Array(K).join(" ")+"^")}i.prototype=Object.create(Error.prototype,{name:{value:"Squirrelly Error",enumerable:!1}});var n=new Function("return this")().Promise,a=!1;try{a=new Function("return (async function(){}).constructor")()}catch(b){if(!(b instanceof SyntaxError))throw b}function o(b,T){return Object.prototype.hasOwnProperty.call(b,T)}function l(b,T,k){for(var N in T)o(T,N)&&(T[N]==null||typeof T[N]!="object"||N!=="storage"&&N!=="prefixes"||k?b[N]=T[N]:b[N]=l({},T[N]));return b}var h=/^async +/,c=/`(?:\\[\s\S]|\${(?:[^{}]|{(?:[^{}]|{[^}]*})*})*}|(?!\${)[^\\`])*`/g,d=/'(?:\\[\s\w"'\\`]|[^\n\r'\\])*?'/g,u=/"(?:\\[\s\w"'\\`]|[^\n\r"\\])*?"/g,f=/[.*+\-?^${}()|[\]\\]/g;function p(b){return f.test(b)?b.replace(f,"\\$&"):b}function g(b,T){T.rmWhitespace&&(b=b.replace(/[\r\n]+/g,`
82
+ `).replace(/^\s+|\s+$/gm,"")),c.lastIndex=0,d.lastIndex=0,u.lastIndex=0;var k=T.prefixes,N=[k.h,k.b,k.i,k.r,k.c,k.e].reduce(function(nt,it){return nt&&it?nt+"|"+p(it):it?p(it):nt},""),U=new RegExp("([|()]|=>)|('|\"|`|\\/\\*)|\\s*((\\/)?(-|_)?"+p(T.tags[1])+")","g"),K=new RegExp("([^]*?)"+p(T.tags[0])+"(-|_)?\\s*("+N+")?\\s*","g"),W=0,X=!1;function lt(nt,it){var vt,dt={f:[]},Ct=0,et="c";function ut(Ee){var Ie=b.slice(W,Ee),Ht=Ie.trim();if(et==="f")Ht==="safe"?dt.raw=!0:T.async&&h.test(Ht)?(Ht=Ht.replace(h,""),dt.f.push([Ht,"",!0])):dt.f.push([Ht,""]);else if(et==="fp")dt.f[dt.f.length-1][1]+=Ht;else if(et==="err"){if(Ht){var ne=Ie.search(/\S/);s("invalid syntax",b,W+ne)}}else dt[et]=Ht;W=Ee+1}for(it==="h"||it==="b"||it==="c"?et="n":it==="r"&&(dt.raw=!0,it="i"),U.lastIndex=W;(vt=U.exec(b))!==null;){var bt=vt[1],pt=vt[2],Tt=vt[3],_t=vt[4],Pt=vt[5],ft=vt.index;if(bt)bt==="("?(Ct===0&&(et==="n"?(ut(ft),et="p"):et==="f"&&(ut(ft),et="fp")),Ct++):bt===")"?--Ct===0&&et!=="c"&&(ut(ft),et="err"):Ct===0&&bt==="|"?(ut(ft),et="f"):bt==="=>"&&(ut(ft),W+=1,et="res");else if(pt)if(pt==="/*"){var Yt=b.indexOf("*/",U.lastIndex);Yt===-1&&s("unclosed comment",b,vt.index),U.lastIndex=Yt+2}else pt==="'"?(d.lastIndex=vt.index,d.exec(b)?U.lastIndex=d.lastIndex:s("unclosed string",b,vt.index)):pt==='"'?(u.lastIndex=vt.index,u.exec(b)?U.lastIndex=u.lastIndex:s("unclosed string",b,vt.index)):pt==="`"&&(c.lastIndex=vt.index,c.exec(b)?U.lastIndex=c.lastIndex:s("unclosed string",b,vt.index));else if(Tt)return ut(ft),W=ft+vt[0].length,K.lastIndex=W,X=Pt,_t&&it==="h"&&(it="s"),dt.t=it,dt}return s("unclosed tag",b,nt),dt}var rt=function nt(it,vt){it.b=[],it.d=[];var dt,Ct=!1,et=[];function ut(ne,Ni){ne&&(ne=function(ee,vi,Is,Cs){var Ce,O;return typeof vi.autoTrim=="string"?Ce=O=vi.autoTrim:Array.isArray(vi.autoTrim)&&(Ce=vi.autoTrim[1],O=vi.autoTrim[0]),(Is||Is===!1)&&(Ce=Is),(Cs||Cs===!1)&&(O=Cs),Ce==="slurp"&&O==="slurp"?ee.trim():(Ce==="_"||Ce==="slurp"?ee=String.prototype.trimLeft?ee.trimLeft():ee.replace(/^[\s\uFEFF\xA0]+/,""):Ce!=="-"&&Ce!=="nl"||(ee=ee.replace(/^(?:\n|\r|\r\n)/,"")),O==="_"||O==="slurp"?ee=String.prototype.trimRight?ee.trimRight():ee.replace(/[\s\uFEFF\xA0]+$/,""):O!=="-"&&O!=="nl"||(ee=ee.replace(/(?:\n|\r|\r\n)$/,"")),ee)}(ne,T,X,Ni))&&(ne=ne.replace(/\\|'/g,"\\$&").replace(/\r\n|\n|\r/g,"\\n"),et.push(ne))}for(;(dt=K.exec(b))!==null;){var bt,pt=dt[1],Tt=dt[2],_t=dt[3]||"";for(var Pt in k)if(k[Pt]===_t){bt=Pt;break}ut(pt,Tt),W=dt.index+dt[0].length,bt||s("unrecognized tag type: "+_t,b,W);var ft=lt(dt.index,bt),Yt=ft.t;if(Yt==="h"){var Ee=ft.n||"";T.async&&h.test(Ee)&&(ft.a=!0,ft.n=Ee.replace(h,"")),ft=nt(ft),et.push(ft)}else if(Yt==="c"){if(it.n===ft.n)return Ct?(Ct.d=et,it.b.push(Ct)):it.d=et,it;s("Helper start and end don't match",b,dt.index+dt[0].length)}else if(Yt==="b"){Ct?(Ct.d=et,it.b.push(Ct)):it.d=et;var Ie=ft.n||"";T.async&&h.test(Ie)&&(ft.a=!0,ft.n=Ie.replace(h,"")),Ct=ft,et=[]}else if(Yt==="s"){var Ht=ft.n||"";T.async&&h.test(Ht)&&(ft.a=!0,ft.n=Ht.replace(h,"")),et.push(ft)}else et.push(ft)}if(!vt)throw i('unclosed helper "'+it.n+'"');return ut(b.slice(W,b.length),!1),it.d=et,it}({f:[]},!0);if(T.plugins)for(var at=0;at<T.plugins.length;at++){var Rt=T.plugins[at];Rt.processAST&&(rt.d=Rt.processAST(rt.d,T))}return rt.d}function v(b,T){var k=g(b,T),N="var tR='';"+(T.useWith?"with("+T.varName+"||{}){":"")+S(k,T)+"if(cb){cb(null,tR)} return tR"+(T.useWith?"}":"");if(T.plugins)for(var U=0;U<T.plugins.length;U++){var K=T.plugins[U];K.processFnString&&(N=K.processFnString(N,T))}return N}function E(b,T){for(var k=0;k<T.length;k++){var N=T[k][0],U=T[k][1];b=(T[k][2]?"await ":"")+"c.l('F','"+N+"')("+b,U&&(b+=","+U),b+=")"}return b}function A(b,T,k,N,U,K){var W="{exec:"+(U?"async ":"")+y(k,T,b)+",params:["+N+"]";return K&&(W+=",name:'"+K+"'"),U&&(W+=",async:true"),W+="}"}function L(b,T){for(var k="[",N=0;N<b.length;N++){var U=b[N];k+=A(T,U.res||"",U.d,U.p||"",U.a,U.n),N<b.length&&(k+=",")}return k+="]"}function y(b,T,k){return"function("+T+"){var tR='';"+S(b,k)+"return tR}"}function S(b,T){for(var k=0,N=b.length,U="";k<N;k++){var K=b[k];if(typeof K=="string")U+="tR+='"+K+"';";else{var W=K.t,X=K.c||"",lt=K.f,rt=K.n||"",at=K.p||"",Rt=K.res||"",nt=K.b,it=!!K.a;if(W==="i"){T.defaultFilter&&(X="c.l('F','"+T.defaultFilter+"')("+X+")");var vt=E(X,lt);!K.raw&&T.autoEscape&&(vt="c.l('F','e')("+vt+")"),U+="tR+="+vt+";"}else if(W==="h")if(T.storage.nativeHelpers.get(rt))U+=T.storage.nativeHelpers.get(rt)(K,T);else{var dt=(it?"await ":"")+"c.l('H','"+rt+"')("+A(T,Rt,K.d,at,it);dt+=nt?","+L(nt,T):",[]",U+="tR+="+E(dt+=",c)",lt)+";"}else W==="s"?U+="tR+="+E((it?"await ":"")+"c.l('H','"+rt+"')({params:["+at+"]},[],c)",lt)+";":W==="e"&&(U+=X+`
83
+ `)}}return U}var R=function(){function b(T){this.cache=T}return b.prototype.define=function(T,k){this.cache[T]=k},b.prototype.get=function(T){return this.cache[T]},b.prototype.remove=function(T){delete this.cache[T]},b.prototype.reset=function(){this.cache={}},b.prototype.load=function(T){l(this.cache,T,!0)},b}();function C(b,T,k,N){if(T&&T.length>0)throw i((N?"Native":"")+"Helper '"+b+"' doesn't accept blocks");if(k&&k.length>0)throw i((N?"Native":"")+"Helper '"+b+"' doesn't accept filters")}var M={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"};function D(b){return M[b]}var I=new R({}),G=new R({each:function(b,T){var k="",N=b.params[0];if(C("each",T,!1),b.async)return new Promise(function(K){(function W(X,lt,rt,at,Rt){rt(X[lt],lt).then(function(nt){at+=nt,lt===X.length-1?Rt(at):W(X,lt+1,rt,at,Rt)})})(N,0,b.exec,k,K)});for(var U=0;U<N.length;U++)k+=b.exec(N[U],U);return k},foreach:function(b,T){var k=b.params[0];if(C("foreach",T,!1),b.async)return new Promise(function(K){(function W(X,lt,rt,at,Rt,nt){at(lt[rt],X[lt[rt]]).then(function(it){Rt+=it,rt===lt.length-1?nt(Rt):W(X,lt,rt+1,at,Rt,nt)})})(k,Object.keys(k),0,b.exec,"",K)});var N="";for(var U in k)o(k,U)&&(N+=b.exec(U,k[U]));return N},include:function(b,T,k){C("include",T,!1);var N=k.storage.templates.get(b.params[0]);if(!N)throw i('Could not fetch template "'+b.params[0]+'"');return N(b.params[1],k)},extends:function(b,T,k){var N=b.params[1]||{};N.content=b.exec();for(var U=0;U<T.length;U++){var K=T[U];N[K.name]=K.exec()}var W=k.storage.templates.get(b.params[0]);if(!W)throw i('Could not fetch template "'+b.params[0]+'"');return W(N,k)},useScope:function(b,T){return C("useScope",T,!1),b.exec(b.params[0])}}),F=new R({if:function(b,T){C("if",!1,b.f,!0);var k="if("+b.p+"){"+S(b.d,T)+"}";if(b.b)for(var N=0;N<b.b.length;N++){var U=b.b[N];U.n==="else"?k+="else{"+S(U.d,T)+"}":U.n==="elif"&&(k+="else if("+U.p+"){"+S(U.d,T)+"}")}return k},try:function(b,T){if(C("try",!1,b.f,!0),!b.b||b.b.length!==1||b.b[0].n!=="catch")throw i("native helper 'try' only accepts 1 block, 'catch'");var k="try{"+S(b.d,T)+"}",N=b.b[0];return k+="catch"+(N.res?"("+N.res+")":"")+"{"+S(N.d,T)+"}"},block:function(b,T){return C("block",b.b,b.f,!0),"if(!"+T.varName+"["+b.p+"]){tR+=("+y(b.d,"",T)+")()}else{tR+="+T.varName+"["+b.p+"]}"}}),V=new R({e:function(b){var T=String(b);return/[&<>"']/.test(T)?T.replace(/[&<>"']/g,D):T}}),z={varName:"it",autoTrim:[!1,"nl"],autoEscape:!0,defaultFilter:!1,tags:["{{","}}"],l:function(b,T){if(b==="H"){var k=this.storage.helpers.get(T);if(k)return k;throw i("Can't find helper '"+T+"'")}if(b==="F"){var N=this.storage.filters.get(T);if(N)return N;throw i("Can't find filter '"+T+"'")}},async:!1,storage:{helpers:G,nativeHelpers:F,filters:V,templates:I},prefixes:{h:"@",b:"#",i:"",r:"*",c:"/",e:"!"},cache:!1,plugins:[],useWith:!1};function w(b,T){var k={};return l(k,z),T&&l(k,T),b&&l(k,b),k.l.bind(k),k}function P(b,T){var k=w(T||{}),N=Function;if(k.async){if(!a)throw i("This environment doesn't support async/await");N=a}try{return new N(k.varName,"c","cb",v(b,k))}catch(U){throw U instanceof SyntaxError?i(`Bad template syntax
84
+
85
+ `+U.message+`
86
+ `+Array(U.message.length+1).join("=")+`
87
+ `+v(b,k)):U}}function H(b,T){var k;return T.cache&&T.name&&T.storage.templates.get(T.name)?T.storage.templates.get(T.name):(k=typeof b=="function"?b:P(b,T),T.cache&&T.name&&T.storage.templates.define(T.name,k),k)}z.l.bind(z),e.compile=P,e.compileScope=S,e.compileScopeIntoFunction=y,e.compileToString=v,e.defaultConfig=z,e.filters=V,e.getConfig=w,e.helpers=G,e.nativeHelpers=F,e.parse=g,e.render=function(b,T,k,N){var U=w(k||{});if(!U.async)return H(b,U)(T,U);if(!N){if(typeof n=="function")return new n(function(K,W){try{K(H(b,U)(T,U))}catch(X){W(X)}});throw i("Please provide a callback function, this env doesn't support Promises")}try{H(b,U)(T,U,N)}catch(K){return N(K)}},e.templates=I,Object.defineProperty(e,"__esModule",{value:!0})})})(tn,tn.exports);var ai=tn.exports,en={exports:{}};(function(r,t){var e=typeof globalThis<"u"&&globalThis||typeof self<"u"&&self||typeof Gs<"u"&&Gs,i=function(){function n(){this.fetch=!1,this.DOMException=e.DOMException}return n.prototype=e,new n}();(function(n){(function(a){var o=typeof n<"u"&&n||typeof self<"u"&&self||typeof o<"u"&&o,l={searchParams:"URLSearchParams"in o,iterable:"Symbol"in o&&"iterator"in Symbol,blob:"FileReader"in o&&"Blob"in o&&function(){try{return new Blob,!0}catch{return!1}}(),formData:"FormData"in o,arrayBuffer:"ArrayBuffer"in o};function h(w){return w&&DataView.prototype.isPrototypeOf(w)}if(l.arrayBuffer)var c=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],d=ArrayBuffer.isView||function(w){return w&&c.indexOf(Object.prototype.toString.call(w))>-1};function u(w){if(typeof w!="string"&&(w=String(w)),/[^a-z0-9\-#$%&'*+.^_`|~!]/i.test(w)||w==="")throw new TypeError('Invalid character in header field name: "'+w+'"');return w.toLowerCase()}function f(w){return typeof w!="string"&&(w=String(w)),w}function p(w){var P={next:function(){var H=w.shift();return{done:H===void 0,value:H}}};return l.iterable&&(P[Symbol.iterator]=function(){return P}),P}function g(w){this.map={},w instanceof g?w.forEach(function(P,H){this.append(H,P)},this):Array.isArray(w)?w.forEach(function(P){this.append(P[0],P[1])},this):w&&Object.getOwnPropertyNames(w).forEach(function(P){this.append(P,w[P])},this)}g.prototype.append=function(w,P){w=u(w),P=f(P);var H=this.map[w];this.map[w]=H?H+", "+P:P},g.prototype.delete=function(w){delete this.map[u(w)]},g.prototype.get=function(w){return w=u(w),this.has(w)?this.map[w]:null},g.prototype.has=function(w){return this.map.hasOwnProperty(u(w))},g.prototype.set=function(w,P){this.map[u(w)]=f(P)},g.prototype.forEach=function(w,P){for(var H in this.map)this.map.hasOwnProperty(H)&&w.call(P,this.map[H],H,this)},g.prototype.keys=function(){var w=[];return this.forEach(function(P,H){w.push(H)}),p(w)},g.prototype.values=function(){var w=[];return this.forEach(function(P){w.push(P)}),p(w)},g.prototype.entries=function(){var w=[];return this.forEach(function(P,H){w.push([H,P])}),p(w)},l.iterable&&(g.prototype[Symbol.iterator]=g.prototype.entries);function v(w){if(w.bodyUsed)return Promise.reject(new TypeError("Already read"));w.bodyUsed=!0}function E(w){return new Promise(function(P,H){w.onload=function(){P(w.result)},w.onerror=function(){H(w.error)}})}function A(w){var P=new FileReader,H=E(P);return P.readAsArrayBuffer(w),H}function L(w){var P=new FileReader,H=E(P);return P.readAsText(w),H}function y(w){for(var P=new Uint8Array(w),H=new Array(P.length),b=0;b<P.length;b++)H[b]=String.fromCharCode(P[b]);return H.join("")}function S(w){if(w.slice)return w.slice(0);var P=new Uint8Array(w.byteLength);return P.set(new Uint8Array(w)),P.buffer}function R(){return this.bodyUsed=!1,this._initBody=function(w){this.bodyUsed=this.bodyUsed,this._bodyInit=w,w?typeof w=="string"?this._bodyText=w:l.blob&&Blob.prototype.isPrototypeOf(w)?this._bodyBlob=w:l.formData&&FormData.prototype.isPrototypeOf(w)?this._bodyFormData=w:l.searchParams&&URLSearchParams.prototype.isPrototypeOf(w)?this._bodyText=w.toString():l.arrayBuffer&&l.blob&&h(w)?(this._bodyArrayBuffer=S(w.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):l.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(w)||d(w))?this._bodyArrayBuffer=S(w):this._bodyText=w=Object.prototype.toString.call(w):this._bodyText="",this.headers.get("content-type")||(typeof w=="string"?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):l.searchParams&&URLSearchParams.prototype.isPrototypeOf(w)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},l.blob&&(this.blob=function(){var w=v(this);if(w)return w;if(this._bodyBlob)return Promise.resolve(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(new Blob([this._bodyArrayBuffer]));if(this._bodyFormData)throw new Error("could not read FormData body as blob");return Promise.resolve(new Blob([this._bodyText]))},this.arrayBuffer=function(){if(this._bodyArrayBuffer){var w=v(this);return w||(ArrayBuffer.isView(this._bodyArrayBuffer)?Promise.resolve(this._bodyArrayBuffer.buffer.slice(this._bodyArrayBuffer.byteOffset,this._bodyArrayBuffer.byteOffset+this._bodyArrayBuffer.byteLength)):Promise.resolve(this._bodyArrayBuffer))}else return this.blob().then(A)}),this.text=function(){var w=v(this);if(w)return w;if(this._bodyBlob)return L(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(y(this._bodyArrayBuffer));if(this._bodyFormData)throw new Error("could not read FormData body as text");return Promise.resolve(this._bodyText)},l.formData&&(this.formData=function(){return this.text().then(I)}),this.json=function(){return this.text().then(JSON.parse)},this}var C=["DELETE","GET","HEAD","OPTIONS","POST","PUT"];function M(w){var P=w.toUpperCase();return C.indexOf(P)>-1?P:w}function D(w,P){if(!(this instanceof D))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');P=P||{};var H=P.body;if(w instanceof D){if(w.bodyUsed)throw new TypeError("Already read");this.url=w.url,this.credentials=w.credentials,P.headers||(this.headers=new g(w.headers)),this.method=w.method,this.mode=w.mode,this.signal=w.signal,!H&&w._bodyInit!=null&&(H=w._bodyInit,w.bodyUsed=!0)}else this.url=String(w);if(this.credentials=P.credentials||this.credentials||"same-origin",(P.headers||!this.headers)&&(this.headers=new g(P.headers)),this.method=M(P.method||this.method||"GET"),this.mode=P.mode||this.mode||null,this.signal=P.signal||this.signal,this.referrer=null,(this.method==="GET"||this.method==="HEAD")&&H)throw new TypeError("Body not allowed for GET or HEAD requests");if(this._initBody(H),(this.method==="GET"||this.method==="HEAD")&&(P.cache==="no-store"||P.cache==="no-cache")){var b=/([?&])_=[^&]*/;if(b.test(this.url))this.url=this.url.replace(b,"$1_="+new Date().getTime());else{var T=/\?/;this.url+=(T.test(this.url)?"&":"?")+"_="+new Date().getTime()}}}D.prototype.clone=function(){return new D(this,{body:this._bodyInit})};function I(w){var P=new FormData;return w.trim().split("&").forEach(function(H){if(H){var b=H.split("="),T=b.shift().replace(/\+/g," "),k=b.join("=").replace(/\+/g," ");P.append(decodeURIComponent(T),decodeURIComponent(k))}}),P}function G(w){var P=new g,H=w.replace(/\r?\n[\t ]+/g," ");return H.split("\r").map(function(b){return b.indexOf(`
88
+ `)===0?b.substr(1,b.length):b}).forEach(function(b){var T=b.split(":"),k=T.shift().trim();if(k){var N=T.join(":").trim();P.append(k,N)}}),P}R.call(D.prototype);function F(w,P){if(!(this instanceof F))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');P||(P={}),this.type="default",this.status=P.status===void 0?200:P.status,this.ok=this.status>=200&&this.status<300,this.statusText=P.statusText===void 0?"":""+P.statusText,this.headers=new g(P.headers),this.url=P.url||"",this._initBody(w)}R.call(F.prototype),F.prototype.clone=function(){return new F(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new g(this.headers),url:this.url})},F.error=function(){var w=new F(null,{status:0,statusText:""});return w.type="error",w};var V=[301,302,303,307,308];F.redirect=function(w,P){if(V.indexOf(P)===-1)throw new RangeError("Invalid status code");return new F(null,{status:P,headers:{location:w}})},a.DOMException=o.DOMException;try{new a.DOMException}catch{a.DOMException=function(P,H){this.message=P,this.name=H;var b=Error(P);this.stack=b.stack},a.DOMException.prototype=Object.create(Error.prototype),a.DOMException.prototype.constructor=a.DOMException}function z(w,P){return new Promise(function(H,b){var T=new D(w,P);if(T.signal&&T.signal.aborted)return b(new a.DOMException("Aborted","AbortError"));var k=new XMLHttpRequest;function N(){k.abort()}k.onload=function(){var K={status:k.status,statusText:k.statusText,headers:G(k.getAllResponseHeaders()||"")};K.url="responseURL"in k?k.responseURL:K.headers.get("X-Request-URL");var W="response"in k?k.response:k.responseText;setTimeout(function(){H(new F(W,K))},0)},k.onerror=function(){setTimeout(function(){b(new TypeError("Network request failed"))},0)},k.ontimeout=function(){setTimeout(function(){b(new TypeError("Network request failed"))},0)},k.onabort=function(){setTimeout(function(){b(new a.DOMException("Aborted","AbortError"))},0)};function U(K){try{return K===""&&o.location.href?o.location.href:K}catch{return K}}k.open(T.method,U(T.url),!0),T.credentials==="include"?k.withCredentials=!0:T.credentials==="omit"&&(k.withCredentials=!1),"responseType"in k&&(l.blob?k.responseType="blob":l.arrayBuffer&&T.headers.get("Content-Type")&&T.headers.get("Content-Type").indexOf("application/octet-stream")!==-1&&(k.responseType="arraybuffer")),P&&typeof P.headers=="object"&&!(P.headers instanceof g)?Object.getOwnPropertyNames(P.headers).forEach(function(K){k.setRequestHeader(K,f(P.headers[K]))}):T.headers.forEach(function(K,W){k.setRequestHeader(W,K)}),T.signal&&(T.signal.addEventListener("abort",N),k.onreadystatechange=function(){k.readyState===4&&T.signal.removeEventListener("abort",N)}),k.send(typeof T._bodyInit>"u"?null:T._bodyInit)})}return z.polyfill=!0,o.fetch||(o.fetch=z,o.Headers=g,o.Request=D,o.Response=F),a.Headers=g,a.Request=D,a.Response=F,a.fetch=z,a})({})})(i),i.fetch.ponyfill=!0,delete i.fetch.polyfill;var s=e.fetch?e:i;t=s.fetch,t.default=s.fetch,t.fetch=s.fetch,t.Headers=s.Headers,t.Request=s.Request,t.Response=s.Response,r.exports=t})(en,en.exports);var au=en.exports;const ou=Jr(au);function lu({canvas:r,scenes:t,currentTime:e}){if(t&&r){const i=t.scenes.filter(({start:n,duration:a})=>e>=n&&e<=n+a);if(i.length<=0)return;const s=r.getContext("2d");if(s){const n=t.transitionDuration,a=Math.max(...t.scenes.map(({start:o,duration:l})=>o+l));s.globalCompositeOperation="lighter",s.clearRect(0,0,r.width,r.height),i.forEach(({start:o,duration:l,draw:h,transitionCanvas:c})=>{s.globalAlpha=1,c.width=c.height=0,c.width=r.width,c.height=r.height;const d=c.getContext("2d");if(d){const u=o+l,f=o===0,p=u===a;h({currentTime:e,canvas:c,context:d}),!f&&e>=o&&e<=o+n/2?s.globalAlpha=Math.max(0,Math.min(1,(e-o)/(n/2))):!p&&e>=u-n/2&&e<=u&&(s.globalAlpha=Math.max(0,Math.min(1,(u-e)/(n/2)))),s.drawImage(c,0,0,r.width,r.height)}})}}}function hu(r){if(typeof r=="string"){const[t,e]=r.split(":");return Math.min(parseFloat(t),parseFloat(e))}return r}function cu(r){if(typeof r=="string"){const[t,e]=r.split(":"),i=parseFloat(t),s=parseFloat(e);return i/s}return r}function Ai({resolution:r,aspectRatio:t}){const e=hu(r),i=cu(t),s=i>=1,n=Math.min(s?e*i:e/i,e),a=Math.max(s?e*i:e/i,e);return{resolution:e,aspectRatio:i,height:s?n:a,width:s?a:n}}function du({format:r,resolution:t,aspectRatio:e,videoResolution:i,videoAspectRatio:s}){const{height:n,width:a}=Ai({resolution:t,aspectRatio:e}),{height:o,width:l}=Ai({resolution:i,aspectRatio:s}),h=e>s;let c=1;if(r==="letterbox"||r==="letterbox-video")c=h?n/o:a/l;else if(r==="squarebox"){const g=Math.min(n,a);c=l>=o?g/o:g/l}else(r==="crop"||r==="crop-top")&&(c=h?a/l:n/o);const d=a/c,u=n/c,f=(l-d)/2;let p=(o-u)/2;return r==="crop-top"&&(p=Math.min(0,p)),{sx:f,sy:p,sWidth:d,sHeight:u,scale:c}}function Vs({source:r,sx:t,sy:e,sw:i,sh:s,dx:n,dy:a,dw:o,dh:l}){const h=(r==null?void 0:r.naturalWidth)??(r==null?void 0:r.videoWidth)??(r==null?void 0:r.width),c=(r==null?void 0:r.naturalHeight)??(r==null?void 0:r.videoHeight)??(r==null?void 0:r.height);t=t??0,e=e??0,i=i??h,s=s??c,i<0&&(t+=i,i=Math.abs(i)),s<0&&(e+=s,s=Math.abs(s)),o<0&&(n+=o,o=Math.abs(o)),l<0&&(a+=l,l=Math.abs(l));const d=Math.max(t,0),u=Math.min(t+i,h),f=Math.max(e,0),p=Math.min(e+s,c),g=o/i,v=l/s;return[r,d,f,u-d,p-f,t<0?n-t*g:n,e<0?a-e*v:a,(u-d)*g,(p-f)*v]}function ko({context:r,source:t,format:e="letterbox",videoResolution:i,videoAspectRatio:s,posX:n,posY:a,width:o,height:l,offscreenCanvas:h}){const{sx:c,sy:d,sWidth:u,sHeight:f,scale:p}=du({resolution:Math.min(o,l),aspectRatio:o/l,format:e,videoResolution:i,videoAspectRatio:s}),g=h&&typeof r.filter<"u";if(e==="letterbox"||e==="squarebox"||e==="letterbox-video"&&!g){if(c<0){const y=Math.abs(c)*p;r.fillStyle="black",r.beginPath(),r.rect(n,a,y,l),r.rect(n+o-y,a,y,l),r.fill(),r.closePath()}if(d<0){const y=Math.abs(d)*p;r.fillStyle="black",r.beginPath(),r.rect(n,a,o,y),r.rect(n,a+l-y,o,y),r.fill(),r.closePath()}}if(e==="letterbox-video"&&g){const{width:y,height:S}=Ai({resolution:i,aspectRatio:s});h.width=y,h.height=S;const R=h.getContext("2d",{alpha:!1});if(R==null||R.drawImage(t,0,0,y,S),R){r.save(),r.globalCompositeOperation="destination-out",r.fillRect(n,a,o,l);const C=Vs({source:h,sx:c,sy:d,sw:u,sh:f,dx:n,dy:a,dw:o,dh:l});r.globalCompositeOperation="source-over",r.drawImage(...C),R.save();const M=1.3,D=-(y*M-y)/2,I=-(S*M-S)/2;if(R.filter="blur(40px) brightness(20%)",R.translate(D,I),R.scale(M,M),R.drawImage(h,0,0,y,S),R.restore(),r.globalCompositeOperation="destination-over",c<0){const G=o/s,F=l/G,V=Vs({source:h,sy:(1-F)*S/2,sh:F*S,dx:n,dy:a,dw:o,dh:l});r.drawImage(...V)}if(d<0){const G=l*s,F=o/G,V=Vs({source:h,sx:(1-F)*y/2,sw:F*y,dx:n,dy:a,dw:o,dh:l});r.drawImage(...V)}r.restore()}}else{const y=Vs({source:t,sx:c,sy:d,sw:u,sh:f,dx:n,dy:a,dw:o,dh:l});r.drawImage(...y)}const v=c*-1*p,E=d*-1*p,A=o-v*2,L=l-E*2;return{dx:v,dy:E,dw:A,dh:L}}const uu=/\d{0,2}:?\d{2}:\d{2}\.\d{3}\s-->\s\d{0,2}:?\d{2}:\d{2}\.\d{3}\s{1,2}.*/g,fu=/\d{0,2}:?\d{2}:\d{2}\.\d{3}/g;function Io(r){if(!r)return[];const t=r.match(uu);return t?t==null?void 0:t.map(e=>{const[i,s]=e.replace(`\r
84
89
  `,`
85
90
  `).split(`
86
- `),[n,a]=i.match(xu)||[];return{start:n,end:a,text:s}}):[]}function Gs(r){const[t,e,i]=r.split(":");return i?parseInt(t)*60*60+parseInt(e)*60+parseFloat(i):parseInt(t)*60+parseInt(e)}function Pu({canvas:r,dx:t,dy:e,dw:i,dh:s,relativeTime:n,vttCaptions:a}){if(a){const o=zo(a).find(({start:l,end:h})=>l&&h&&n>=Gs(l)&&n<Gs(h));if(o){const l=r.getContext("2d");if(l){const h=Math.min(i,s);let d=[""];const c=i*.9,u=h*.05;l.font=`${u}px Roobert, Dejavu Sans, sans-serif`,l.textBaseline="middle",o.text.split(" ").forEach(f=>{const p=d.length-1,g=l.measureText(d[p]).width,v=l.measureText(` ${f}`).width;g+v<c?d[p]=`${d[p]} ${f}`:d=[...d,f]}),d.forEach((f,p)=>{const g=f.trim(),v=l.measureText(g),E=t+(i-v.width)/2,T=e+(s*.85-(u+h*.04)*(d.length-1-p)),A=u*.8,y=u/1.5,b=t+(i-v.width-y)/2,S=T-A,R=v.width+y,D=A*2,_=l.globalAlpha;l.save(),l.globalAlpha=.8*_,l.fillStyle="#000000",l.beginPath(),l.roundRect(b,S,R,D,h*.01),l.fill(),l.closePath(),l.globalAlpha=_,l.fillStyle="#FFFFFF",l.fillText(g,E,T),l.restore()})}}}}const we=1.8;function Xi(r){return typeof r=="number"?{top:r,right:r,bottom:r,left:r}:{top:0,right:0,bottom:0,left:0,...r}}function Ou(r,t=1){return typeof r=="number"?{topLeft:r*t,topRight:r*t,bottomRight:r*t,bottomLeft:r*t}:{topLeft:((r==null?void 0:r.topLeft)??0)*t,topRight:((r==null?void 0:r.topRight)??0)*t,bottomRight:((r==null?void 0:r.bottomRight)??0)*t,bottomLeft:((r==null?void 0:r.bottomLeft)??0)*t}}function Vs(r,t){return typeof r=="number"?r:typeof r=="function"?r(t):null}function Ks(r,t){const{w:e,gap:i=0,padding:s=0,direction:n="column",elements:a}=r,{right:o,left:l}=Xi(s);if(e){const h=Vs(e,t);if(h)return h}if(a){const h=a.length;if(n==="row")return o+l+i*(h-1)+a.reduce((d,c)=>d+=Ks(c,t),0);if(n==="column"){let d=0;return a.forEach(c=>{const u=o+l+Ks(c,t);u>d&&(d=u)}),d}}return 0}function Mu(r,t,e){const{w:i=0,gap:s=0,padding:n=0,direction:a="column"}=r,{right:o,left:l}=Xi(n),h=t.length,d=t.reduce((u,f)=>{const{w:p}=f;if(p){const g=Vs(p,e);if(g)return u+=g}return p==="auto"?u+=Ks(f,e):u},0),c=t.filter(({w:u})=>u==="fill").length;return t.reduce((u,f)=>{const{w:p}=f,g=i-o-l,v=Math.min(g,Ks(f,e));if(p==="fill"){if(a==="row"){const E=(i-d-o-l-s*(h-1))/c;return u=[...u,E]}if(a==="column")return u=[...u,g]}return u=[...u,v]},[])}function js(r,t){const{h:e,gap:i=0,padding:s=0,direction:n="column",elements:a}=r,{top:o,bottom:l}=Xi(s);if(e){const h=Vs(e,t);if(h)return h}if(a){const h=a.length;if(n==="row"){let d=0;return a.forEach(c=>{const u=o+l+js(c,t);u>d&&(d=u)}),d}if(n==="column")return o+l+i*(h-1)+a.reduce((d,c)=>d+=js(c,t),0)}return 0}function $u(r,t,e){const{h:i=0,gap:s=0,padding:n=0,direction:a="column"}=r,{top:o,bottom:l}=Xi(n),h=t.length,d=t.reduce((u,f)=>{const{h:p}=f;if(p){const g=Vs(p,e);if(g)return u+=g}return p==="auto"?u+=js(f,e):u},0),c=t.filter(({h:u})=>u==="fill").length;return t.reduce((u,f)=>{const{h:p}=f,g=i-o-l,v=Math.min(g,js(f,e));if(p==="fill"){if(a==="row")return u=[...u,g];if(a==="column"){const E=(i-d-o-l-s*(h-1))/c;return u=[...u,E]}}return u=[...u,v]},[])}function qo({canvas:r,offscreenCanvas:t,debug:e=!1,origin:{x:i=0,y:s=0,w:n=r.width,h:a=r.height}={},parent:o,elements:l=[]}){const h=Math.min(n,a)/1080,d={x:0,y:0,w:n/h,h:a/h,gap:0,padding:0,direction:"column",align:"start",justify:"start",...o},{x:c,y:u,w:f,h:p,gap:g,padding:v,direction:E,align:T,justify:A}=d,{top:y,right:b,bottom:S,left:R}=Xi(v);l.map((D,_)=>{const I=r.getContext("2d",{alpha:!1});if(I){const N=l.length,{x:P,y:F,radius:K,elements:w=[],draw:C}=D,{topLeft:U,topRight:M,bottomRight:B,bottomLeft:H}=Ou(K,h),z=Mu(d,l,{context:I}),[Z,Q,it]=z.reduce((bt,Pt,Yt)=>(Yt<_&&(bt[0]=bt[0]+=Pt),Yt>_&&(bt[1]=bt[1]+=Pt),bt[2]=bt[2]+=Pt,bt),[0,0,0]),tt=z[_],xt=$u(d,l,{context:I,width:tt}),[St,yt,Te]=xt.reduce((bt,Pt,Yt)=>(Yt<_&&(bt[0]=bt[0]+=Pt),Yt>_&&(bt[1]=bt[1]+=Pt),bt[2]=bt[2]+=Pt,bt),[0,0,0]),Et=xt[_],Ue={"row|start|start":R+Z+g*_,"row|center|start":R+Z+g*_,"row|end|start":R+Z+g*_,"row|start|center":f/2-it/2-g*(N-1)/2+Z+g*_,"row|center|center":f/2-it/2-g*(N-1)/2+Z+g*_,"row|end|center":f/2-it/2-g*(N-1)/2+Z+g*_,"row|start|end":f-b-tt-Q-g*(N-_),"row|center|end":f-b-tt-Q-g*(N-_),"row|end|end":f-b-tt-Q-g*(N-_),"column|start|start":R,"column|center|start":f/2-tt/2,"column|end|start":f-b-tt-Q,"column|start|center":R,"column|center|center":f/2-tt/2,"column|end|center":f-b-tt-Q,"column|start|end":R,"column|center|end":f/2-tt/2,"column|end|end":f-b-tt-Q},Di={"row|start|start":y,"row|center|start":p/2-Et/2,"row|end|start":p-S-Et-yt,"row|start|center":y,"row|center|center":p/2-Et/2,"row|end|center":p-S-Et-yt,"row|start|end":y,"row|center|end":p/2-Et/2,"row|end|end":p-S-Et-yt,"column|start|start":y+St+g*_,"column|center|start":y+St+g*_,"column|end|start":y+St+g*_,"column|start|center":p/2-Te/2-g*(N-1)/2+St+g*_,"column|center|center":p/2-Te/2-g*(N-1)+St+g*_,"column|end|center":p/2-Te/2-g*(N-1)+St+g*_,"column|start|end":p-S-Et-yt-g*(N-_),"column|center|end":p-S-Et-yt-g*(N-_),"column|end|end":p-S-Et-yt-g*(N-_)},Be=c+(P??Ue[`${E}|${T}|${A}`]),oi=u+(F??Di[`${E}|${T}|${A}`]),Tt=i+Be*h,mt=s+oi*h,Wt=tt*h,ft=Et*h;C&&(I.save(),K&&(I.beginPath(),I.moveTo(Tt+Math.min(ft/we,U),mt),I.lineTo(Tt+Wt-Math.min(ft/we,M),mt),I.quadraticCurveTo(Tt+Wt,mt,Tt+Wt,mt+Math.min(ft/we,M)),I.lineTo(Tt+Wt,mt+ft-Math.min(ft/we,B)),I.quadraticCurveTo(Tt+Wt,mt+ft,Tt+Wt-Math.min(ft/we,B),mt+ft),I.lineTo(Tt+Math.min(ft/we,H),mt+ft),I.quadraticCurveTo(Tt,mt+ft,Tt,mt+ft-Math.min(ft/we,H)),I.lineTo(Tt,mt+Math.min(ft/we,U)),I.quadraticCurveTo(Tt,mt,Tt+Math.min(ft/we,U),mt),I.closePath(),e&&(I.strokeStyle="blue",I.stroke()),I.clip()),C({scale:h,canvas:r,context:I,offscreenCanvas:t,dx:Tt,dy:mt,dw:Wt,dh:ft}),e&&(I.strokeStyle="red",I.strokeRect(Tt,mt,Wt,ft)),I.restore()),qo({canvas:r,offscreenCanvas:t,debug:e,origin:{x:i,y:s,w:n,h:a},parent:{...D,x:Be,y:oi,w:tt,h:Et},elements:w})}})}function Fu(r){return qo(r)}function Ws({context:r,node:t,maxW:e=1/0}){const i=(t.value??"").split(" ");return i.slice(1).reduce((s,n)=>{const a=`${s[s.length-1].text} ${n}`.trim(),o=r.measureText(a);return o.width>e?s=[...s,{text:n,metrics:r.measureText(n)}]:s[s.length-1]={text:a,metrics:o},s},[{text:i[0],metrics:r.measureText(i[0])}])}function Xo(r){const{visible:t=!0,node:e}=r,i=[...(e==null?void 0:e.elements)??[],...(r==null?void 0:r.elements)??[]];return t?e&&e.type!=="box"&&e.type!=="gradient"?!!e.value:i==null?void 0:i.some(s=>Xo(s)):!1}function Qo({debug:r,elements:t,currentTime:e,relativeTime:i}){return t.map(s=>{const{node:n}=s;if(Xo(s))return{...s,...(n==null?void 0:n.type)==="text"&&n.value?{w:n.fill?"fill":({context:a})=>n&&n.type==="text"&&n.value?(a.font=n.font,a.textBaseline="top",Math.ceil(a.measureText(n.value).width)):0,h:n.fill?"fill":({width:a,context:o})=>{var l,h;if(n&&n.type==="text"){const d=/(?<value>\d+\.?\d*)(?=px)/,c=parseFloat(((h=(l=n.font.match(d))==null?void 0:l.groups)==null?void 0:h.value)??"0");return n.wrap?Ws({context:o,node:n,maxW:a}).length*c:c}return 0}}:{},...(n==null?void 0:n.type)==="image"&&n.image&&n.size?{w:()=>{var a,o,l,h;const d=((a=n.image)==null?void 0:a.naturalWidth)??n.image.width,c=((o=n.image)==null?void 0:o.naturalHeight)??n.image.height,u=d/c,f=(l=n.size)==null?void 0:l.w,p=((h=n.size)==null?void 0:h.h)??0;return f??(u>=1?p:p*u)},h:()=>{var a,o,l,h;const d=((a=n.image)==null?void 0:a.naturalWidth)??n.image.width,c=((o=n.image)==null?void 0:o.naturalHeight)??n.image.height,u=d/c,f=((l=n.size)==null?void 0:l.w)??0;return((h=n.size)==null?void 0:h.h)??(u<1?f:f*u)}}:{},elements:s.elements?Qo({debug:r,elements:s.elements,currentTime:e,relativeTime:i}):void 0,draw:({canvas:a,offscreenCanvas:o,context:l,dx:h,dy:d,dw:c,dh:u,scale:f})=>{var p,g,v,E,T,A,y,b,S,R,D;if(n){const{type:_,from:I=0,to:N=1/0}=n;if(i>=I&&i<=N){if(l.save(),i&&N-.3333333333333333<=i&&(l.globalAlpha=1-(.16666666666666666-(N-i))/.16666666666666666),_==="box"&&(l.fillStyle=n.background,l.fillRect(h,d,c,u)),_==="text"&&n.value){const P=/(?<value>\d+\.?\d*)(?=px)/;let F=0;const K=parseFloat(((g=(p=n.font.match(P))==null?void 0:p.groups)==null?void 0:g.value)??"0")*f;if(n.fill){const{minSize:w,maxSize:C}=n.fill;F=w*f,l.font=n.font.replace(P,F.toString());const U=10*f;let M=0,B=Ws({context:l,node:n,maxW:c});for(;F+U<C*f&&(B.length+1)*(F+U)<u;)if(F+=U,l.font=n.font.replace(P,F.toString()),B=Ws({context:l,node:n,maxW:c}),M=B.reduce((H,z)=>(z.metrics.width>H&&(H=z.metrics.width),H),0),M>c){F-=U;break}l.font=n.font.replace(P,F.toString())}else F=K,l.font=n.font.replace(P,K.toString());l.textBaseline="top",l.fillStyle=n.color,n.wrap?Ws({context:l,node:n,maxW:c}).forEach((w,C)=>{l.fillText(w.text,h,d+F*C)}):l.fillText(n.value,h,d)}if(_==="image"&&n.image&&l.drawImage(n.image,h,d,c,u),_==="video"&&((v=n.video)!=null&&v.node||(E=n.video)!=null&&E.getSource)){const P=n.format??"letterbox",F=((A=(T=n.video)==null?void 0:T.getSource)==null?void 0:A.call(T,i))??n.video.node,K=(F==null?void 0:F.videoWidth)??(F==null?void 0:F.naturalWidth)??(F==null?void 0:F.width),w=(F==null?void 0:F.videoHeight)??(F==null?void 0:F.naturalHeight)??(F==null?void 0:F.height);if(K&&w){const{resolution:U,aspectRatio:M}=gi({resolution:Math.min(K,w),aspectRatio:K/w}),{dx:B,dy:H,dw:z,dh:Z}=Yo({offscreenCanvas:o,context:l,source:F,format:P,videoResolution:U,videoAspectRatio:M,posX:h,posY:d,width:c,height:u});n.elements&&pn({debug:r,canvas:a,offscreenCanvas:o,currentTime:e,relativeTime:i,origin:{x:Math.max(h,h+B),y:Math.max(d,d+H),w:Math.min(c,z),h:Math.min(u,Z)},elements:n.elements})}const C=1/3;if(n.poster&&e>=0&&e<=C){l.save(),l.globalAlpha=1-e/C;const U=((y=n.poster)==null?void 0:y.naturalWidth)??((b=n.poster)==null?void 0:b.width),M=((S=n.poster)==null?void 0:S.naturalHeight)??((R=n.poster)==null?void 0:R.height);if(U&&M){const{resolution:B,aspectRatio:H}=gi({resolution:Math.min(U,M),aspectRatio:U/M}),{dx:z,dy:Z,dw:Q,dh:it}=Yo({offscreenCanvas:o,context:l,source:n.poster,format:P,videoResolution:B,videoAspectRatio:H,posX:h,posY:d,width:c,height:u});n.elements&&pn({debug:r,canvas:a,offscreenCanvas:o,currentTime:e,relativeTime:i,origin:{x:Math.max(h,h+z),y:Math.max(d,d+Z),w:Math.min(c,Q),h:Math.min(u,it)},elements:n.elements})}l.restore()}}if(_==="gradient"&&n.value){const P=l.createLinearGradient(h+c,d,h+c,d+u);(D=n.value)==null||D.forEach(F=>{P.addColorStop(F.percent,F.color)}),l.fillStyle=P,l.fillRect(h,d,c,u)}l.restore()}}}}}).filter(Boolean)}function pn({debug:r,elements:t,currentTime:e,relativeTime:i,...s}){return Fu({...s,debug:r,elements:Qo({debug:r,elements:t,currentTime:e,relativeTime:i})})}const Nu={template:{layouts:[{name:"basic",tree:`[
91
+ `),[n,a]=i.match(fu)||[];return{start:n,end:a,text:s}}):[]}function Ks(r){const[t,e,i]=r.split(":");return i?parseInt(t)*60*60+parseInt(e)*60+parseFloat(i):parseInt(t)*60+parseInt(e)}function pu({canvas:r,dx:t,dy:e,dw:i,dh:s,relativeTime:n,vttCaptions:a}){if(a){const o=Io(a).find(({start:l,end:h})=>l&&h&&n>=Ks(l)&&n<Ks(h));if(o){const l=r.getContext("2d");if(l){const h=Math.min(i,s);let c=[""];const d=i*.9,u=h*.05;l.font=`${u}px Roobert, Dejavu Sans, sans-serif`,l.textBaseline="middle",o.text.split(" ").forEach(f=>{const p=c.length-1,g=l.measureText(c[p]).width,v=l.measureText(` ${f}`).width;g+v<d?c[p]=`${c[p]} ${f}`:c=[...c,f]}),c.forEach((f,p)=>{const g=f.trim(),v=l.measureText(g),E=t+(i-v.width)/2,A=e+(s*.85-(u+h*.04)*(c.length-1-p)),L=u*.8,y=u/1.5,S=t+(i-v.width-y)/2,R=A-L,C=v.width+y,M=L*2,D=l.globalAlpha;l.save(),l.globalAlpha=.8*D,l.fillStyle="#000000",l.beginPath(),l.roundRect(S,R,C,M,h*.01),l.fill(),l.closePath(),l.globalAlpha=D,l.fillStyle="#FFFFFF",l.fillText(g,E,A),l.restore()})}}}}const Pe=1.8;function ls(r){return typeof r=="number"?{top:r,right:r,bottom:r,left:r}:{top:0,right:0,bottom:0,left:0,...r}}function gu(r,t=1){return typeof r=="number"?{topLeft:r*t,topRight:r*t,bottomRight:r*t,bottomLeft:r*t}:{topLeft:((r==null?void 0:r.topLeft)??0)*t,topRight:((r==null?void 0:r.topRight)??0)*t,bottomRight:((r==null?void 0:r.bottomRight)??0)*t,bottomLeft:((r==null?void 0:r.bottomLeft)??0)*t}}function js(r,t){return typeof r=="number"?r:typeof r=="function"?r(t):null}function Ws(r,t){const{w:e,gap:i=0,padding:s=0,direction:n="column",elements:a}=r,{right:o,left:l}=ls(s);if(e){const h=js(e,t);if(h)return h}if(a){const h=a.length;if(n==="row")return o+l+i*(h-1)+a.reduce((c,d)=>c+=Ws(d,t),0);if(n==="column"){let c=0;return a.forEach(d=>{const u=o+l+Ws(d,t);u>c&&(c=u)}),c}}return 0}function mu(r,t,e){const{w:i=0,gap:s=0,padding:n=0,direction:a="column"}=r,{right:o,left:l}=ls(n),h=t.length,c=t.reduce((u,f)=>{const{w:p}=f;if(p){const g=js(p,e);if(g)return u+=g}return p==="auto"?u+=Ws(f,e):u},0),d=t.filter(({w:u})=>u==="fill").length;return t.reduce((u,f)=>{const{w:p}=f,g=i-o-l,v=Math.min(g,Ws(f,e));if(p==="fill"){if(a==="row"){const E=(i-c-o-l-s*(h-1))/d;return u=[...u,E]}if(a==="column")return u=[...u,g]}return u=[...u,v]},[])}function Ys(r,t){const{h:e,gap:i=0,padding:s=0,direction:n="column",elements:a}=r,{top:o,bottom:l}=ls(s);if(e){const h=js(e,t);if(h)return h}if(a){const h=a.length;if(n==="row"){let c=0;return a.forEach(d=>{const u=o+l+Ys(d,t);u>c&&(c=u)}),c}if(n==="column")return o+l+i*(h-1)+a.reduce((c,d)=>c+=Ys(d,t),0)}return 0}function vu(r,t,e){const{h:i=0,gap:s=0,padding:n=0,direction:a="column"}=r,{top:o,bottom:l}=ls(n),h=t.length,c=t.reduce((u,f)=>{const{h:p}=f;if(p){const g=js(p,e);if(g)return u+=g}return p==="auto"?u+=Ys(f,e):u},0),d=t.filter(({h:u})=>u==="fill").length;return t.reduce((u,f)=>{const{h:p}=f,g=i-o-l,v=Math.min(g,Ys(f,e));if(p==="fill"){if(a==="row")return u=[...u,g];if(a==="column"){const E=(i-c-o-l-s*(h-1))/d;return u=[...u,E]}}return u=[...u,v]},[])}function Co({canvas:r,offscreenCanvas:t,debug:e=!1,origin:{x:i=0,y:s=0,w:n=r.width,h:a=r.height}={},parent:o,elements:l=[]}){const h=Math.min(n,a)/1080,c={x:0,y:0,w:n/h,h:a/h,gap:0,padding:0,direction:"column",align:"start",justify:"start",...o},{x:d,y:u,w:f,h:p,gap:g,padding:v,direction:E,align:A,justify:L}=c,{top:y,right:S,bottom:R,left:C}=ls(v);l.map((M,D)=>{const I=r.getContext("2d",{alpha:!1});if(I){const G=l.length,{x:F,y:V,radius:z,elements:w=[],draw:P}=M,{topLeft:H,topRight:b,bottomRight:T,bottomLeft:k}=gu(z,h),N=mu(c,l,{context:I}),[U,K,W]=N.reduce((Tt,_t,Pt)=>(Pt<D&&(Tt[0]=Tt[0]+=_t),Pt>D&&(Tt[1]=Tt[1]+=_t),Tt[2]=Tt[2]+=_t,Tt),[0,0,0]),X=N[D],lt=vu(c,l,{context:I,width:X}),[rt,at,Rt]=lt.reduce((Tt,_t,Pt)=>(Pt<D&&(Tt[0]=Tt[0]+=_t),Pt>D&&(Tt[1]=Tt[1]+=_t),Tt[2]=Tt[2]+=_t,Tt),[0,0,0]),nt=lt[D],it={"row|start|start":C+U+g*D,"row|center|start":C+U+g*D,"row|end|start":C+U+g*D,"row|start|center":f/2-W/2-g*(G-1)/2+U+g*D,"row|center|center":f/2-W/2-g*(G-1)/2+U+g*D,"row|end|center":f/2-W/2-g*(G-1)/2+U+g*D,"row|start|end":f-S-X-K-g*(G-D),"row|center|end":f-S-X-K-g*(G-D),"row|end|end":f-S-X-K-g*(G-D),"column|start|start":C,"column|center|start":f/2-X/2,"column|end|start":f-S-X-K,"column|start|center":C,"column|center|center":f/2-X/2,"column|end|center":f-S-X-K,"column|start|end":C,"column|center|end":f/2-X/2,"column|end|end":f-S-X-K},vt={"row|start|start":y,"row|center|start":p/2-nt/2,"row|end|start":p-R-nt-at,"row|start|center":y,"row|center|center":p/2-nt/2,"row|end|center":p-R-nt-at,"row|start|end":y,"row|center|end":p/2-nt/2,"row|end|end":p-R-nt-at,"column|start|start":y+rt+g*D,"column|center|start":y+rt+g*D,"column|end|start":y+rt+g*D,"column|start|center":p/2-Rt/2-g*(G-1)/2+rt+g*D,"column|center|center":p/2-Rt/2-g*(G-1)+rt+g*D,"column|end|center":p/2-Rt/2-g*(G-1)+rt+g*D,"column|start|end":p-R-nt-at-g*(G-D),"column|center|end":p-R-nt-at-g*(G-D),"column|end|end":p-R-nt-at-g*(G-D)},dt=d+(F??it[`${E}|${A}|${L}`]),Ct=u+(V??vt[`${E}|${A}|${L}`]),et=i+dt*h,ut=s+Ct*h,bt=X*h,pt=nt*h;P&&(I.save(),z&&(I.beginPath(),I.moveTo(et+Math.min(pt/Pe,H),ut),I.lineTo(et+bt-Math.min(pt/Pe,b),ut),I.quadraticCurveTo(et+bt,ut,et+bt,ut+Math.min(pt/Pe,b)),I.lineTo(et+bt,ut+pt-Math.min(pt/Pe,T)),I.quadraticCurveTo(et+bt,ut+pt,et+bt-Math.min(pt/Pe,T),ut+pt),I.lineTo(et+Math.min(pt/Pe,k),ut+pt),I.quadraticCurveTo(et,ut+pt,et,ut+pt-Math.min(pt/Pe,k)),I.lineTo(et,ut+Math.min(pt/Pe,H)),I.quadraticCurveTo(et,ut,et+Math.min(pt/Pe,H),ut),I.closePath(),e&&(I.strokeStyle="blue",I.stroke()),I.clip()),P({scale:h,canvas:r,context:I,offscreenCanvas:t,dx:et,dy:ut,dw:bt,dh:pt}),e&&(I.strokeStyle="red",I.strokeRect(et,ut,bt,pt)),I.restore()),Co({canvas:r,offscreenCanvas:t,debug:e,origin:{x:i,y:s,w:n,h:a},parent:{...M,x:dt,y:Ct,w:X,h:nt},elements:w})}})}function yu(r){return Co(r)}function zs({context:r,node:t,maxW:e=1/0}){const i=(t.value??"").split(" ");return i.slice(1).reduce((s,n)=>{const a=`${s[s.length-1].text} ${n}`.trim(),o=r.measureText(a);return o.width>e?s=[...s,{text:n,metrics:r.measureText(n)}]:s[s.length-1]={text:a,metrics:o},s},[{text:i[0],metrics:r.measureText(i[0])}])}function Do(r){const{visible:t=!0,node:e}=r,i=[...(e==null?void 0:e.elements)??[],...(r==null?void 0:r.elements)??[]];return t?e&&e.type!=="box"&&e.type!=="gradient"?!!e.value:i==null?void 0:i.some(s=>Do(s)):!1}function xo({debug:r,elements:t,currentTime:e,relativeTime:i}){return t.map(s=>{const{node:n}=s;if(Do(s))return{...s,...(n==null?void 0:n.type)==="text"&&n.value?{w:n.fill?"fill":({context:a})=>n&&n.type==="text"&&n.value?(a.font=n.font,a.textBaseline="top",Math.ceil(a.measureText(n.value).width)):0,h:n.fill?"fill":({width:a,context:o})=>{var l,h;if(n&&n.type==="text"){const c=/(?<value>\d+\.?\d*)(?=px)/,d=parseFloat(((h=(l=n.font.match(c))==null?void 0:l.groups)==null?void 0:h.value)??"0");return n.wrap?zs({context:o,node:n,maxW:a}).length*d:d}return 0}}:{},...(n==null?void 0:n.type)==="image"&&n.image&&n.size?{w:()=>{var a,o,l,h,c,d;const u=((a=n.image)==null?void 0:a.naturalWidth)??((o=n.image)==null?void 0:o.width),f=((l=n.image)==null?void 0:l.naturalHeight)??((h=n.image)==null?void 0:h.height),p=u/f,g=(c=n.size)==null?void 0:c.w,v=((d=n.size)==null?void 0:d.h)??0;return g??(p>=1?v:v*p)},h:()=>{var a,o,l,h,c,d;const u=((a=n.image)==null?void 0:a.naturalWidth)??((o=n.image)==null?void 0:o.width),f=((l=n.image)==null?void 0:l.naturalHeight)??((h=n.image)==null?void 0:h.height),p=u/f,g=((c=n.size)==null?void 0:c.w)??0;return((d=n.size)==null?void 0:d.h)??(p<1?g:g*p)}}:{},elements:s.elements?xo({debug:r,elements:s.elements,currentTime:e,relativeTime:i}):void 0,draw:({canvas:a,offscreenCanvas:o,context:l,dx:h,dy:c,dw:d,dh:u,scale:f})=>{var p,g,v,E,A,L,y,S,R,C,M;if(n){const{type:D,from:I=0,to:G=1/0}=n;if(i>=I&&i<=G){if(l.save(),i&&G-.3333333333333333<=i&&(l.globalAlpha=1-(.16666666666666666-(G-i))/.16666666666666666),D==="box"&&(l.fillStyle=n.background,l.fillRect(h,c,d,u)),D==="text"&&n.value){const F=/(?<value>\d+\.?\d*)(?=px)/;let V=0;const z=parseFloat(((g=(p=n.font.match(F))==null?void 0:p.groups)==null?void 0:g.value)??"0")*f;if(n.fill){const{minSize:w,maxSize:P}=n.fill;V=w*f,l.font=n.font.replace(F,V.toString());const H=10*f;let b=0,T=zs({context:l,node:n,maxW:d});for(;V+H<P*f&&(T.length+1)*(V+H)<u;)if(V+=H,l.font=n.font.replace(F,V.toString()),T=zs({context:l,node:n,maxW:d}),b=T.reduce((k,N)=>(N.metrics.width>k&&(k=N.metrics.width),k),0),b>d){V-=H;break}l.font=n.font.replace(F,V.toString())}else V=z,l.font=n.font.replace(F,z.toString());l.textBaseline="top",l.fillStyle=n.color,n.wrap?zs({context:l,node:n,maxW:d}).forEach((w,P)=>{l.fillText(w.text,h,c+V*P)}):l.fillText(n.value,h,c)}if(D==="image"&&n.image&&l.drawImage(n.image,h,c,d,u),D==="video"&&((v=n.video)!=null&&v.node||(E=n.video)!=null&&E.getSource)){const F=n.format??"letterbox",V=((L=(A=n.video)==null?void 0:A.getSource)==null?void 0:L.call(A,i))??n.video.node,z=(V==null?void 0:V.videoWidth)??(V==null?void 0:V.naturalWidth)??(V==null?void 0:V.width),w=(V==null?void 0:V.videoHeight)??(V==null?void 0:V.naturalHeight)??(V==null?void 0:V.height);if(z&&w){const{resolution:H,aspectRatio:b}=Ai({resolution:Math.min(z,w),aspectRatio:z/w}),{dx:T,dy:k,dw:N,dh:U}=ko({offscreenCanvas:o,context:l,source:V,format:F,videoResolution:H,videoAspectRatio:b,posX:h,posY:c,width:d,height:u});n.elements&&sn({debug:r,canvas:a,offscreenCanvas:o,currentTime:e,relativeTime:i,origin:{x:Math.max(h,h+T),y:Math.max(c,c+k),w:Math.min(d,N),h:Math.min(u,U)},elements:n.elements})}const P=1/3;if(n.poster&&e>=0&&e<=P){l.save(),l.globalAlpha=1-e/P;const H=((y=n.poster)==null?void 0:y.naturalWidth)??((S=n.poster)==null?void 0:S.width),b=((R=n.poster)==null?void 0:R.naturalHeight)??((C=n.poster)==null?void 0:C.height);if(H&&b){const{resolution:T,aspectRatio:k}=Ai({resolution:Math.min(H,b),aspectRatio:H/b}),{dx:N,dy:U,dw:K,dh:W}=ko({offscreenCanvas:o,context:l,source:n.poster,format:F,videoResolution:T,videoAspectRatio:k,posX:h,posY:c,width:d,height:u});n.elements&&sn({debug:r,canvas:a,offscreenCanvas:o,currentTime:e,relativeTime:i,origin:{x:Math.max(h,h+N),y:Math.max(c,c+U),w:Math.min(d,K),h:Math.min(u,W)},elements:n.elements})}l.restore()}}if(D==="gradient"&&n.value){const F=l.createLinearGradient(h+d,c,h+d,c+u);(M=n.value)==null||M.forEach(V=>{F.addColorStop(V.percent,V.color)}),l.fillStyle=F,l.fillRect(h,c,d,u)}l.restore()}}}}}).filter(Boolean)}function sn({debug:r,elements:t,currentTime:e,relativeTime:i,...s}){return yu({...s,debug:r,elements:xo({debug:r,elements:t,currentTime:e,relativeTime:i})})}const Eu={id:"default",name:"None",template:{id:"basic",name:"Basic",layouts:[{name:"basic",tree:`[
87
92
  {
88
93
  "w": "fill",
89
94
  "h": "fill",
@@ -94,10 +99,11 @@ var embeds=function(ut){"use strict";var ky=Object.defineProperty;var Cy=(ut,be,
94
99
  "id": {{@ parse(it.id) /}},
95
100
  "src": {{@async resolve-source({ sources: [it.mp4, it.input] }) /}},
96
101
  "playlist": {{@async resolve-source({ sources: [it.playlist] }) /}},
102
+ "poster": {{@ parse(it.poster) /}},
103
+ "captions": {{@ parse(it.captions) /}},
97
104
  "duration": {{@ parse(it.duration) /}},
98
105
  "startOffset": {{@ parse(it.startOffset) /}},
99
- "endOffset": {{@ parse(it.endOffset) /}},
100
- "captions": {{@ parse(it.captions) /}}
106
+ "endOffset": {{@ parse(it.endOffset) /}}
101
107
  }
102
108
  }
103
109
  }
@@ -106,90 +112,72 @@ var embeds=function(ut){"use strict";var ky=Object.defineProperty;var Cy=(ut,be,
106
112
  "mp4": {{@ parse(it.root?.answer?.media?.video) /}},
107
113
  "input": {{@ parse(it.root?.answer?.media?.input) /}},
108
114
  "playlist": {{@ parse(it.root?.answer?.media?.playlist) /}},
115
+ "poster": {{@ parse(it.root?.answer?.media?.thumbnail) /}},
116
+ "captions": {{@ parse(it.root?.answer?.captions?.current) /}},
109
117
  "duration": {{@ parse(it.root?.answer?.metadata?.duration) /}},
110
118
  "startOffset": {{@ parse(it.root?.answer?.settings?.startOffset) /}},
111
- "endOffset": {{@ parse(it.root?.answer?.settings?.endOffset) /}},
112
- "captions": {{@ parse(it.root?.answer?.captions?.current) /}}
119
+ "endOffset": {{@ parse(it.root?.answer?.settings?.endOffset) /}}
113
120
  }`}],root:"{{ it.intro?.questions?.items | stringify }}"},{scenes:[{layout:"basic",data:`{
114
121
  "id": {{@ parse(it.root?.answer?.id) /}},
115
122
  "mp4": {{@ parse(it.root?.answer?.media?.video) /}},
116
123
  "input": {{@ parse(it.root?.answer?.media?.input) /}},
117
124
  "playlist": {{@ parse(it.root?.answer?.media?.playlist) /}},
125
+ "poster": {{@ parse(it.root?.answer?.media?.thumbnail) /}},
126
+ "captions": {{@ parse(it.root?.answer?.captions?.current) /}},
118
127
  "duration": {{@ parse(it.root?.answer?.metadata?.duration) /}},
119
128
  "startOffset": {{@ parse(it.root?.answer?.settings?.startOffset) /}},
120
- "endOffset": {{@ parse(it.root?.answer?.settings?.endOffset) /}},
121
- "captions": {{@ parse(it.root?.answer?.captions?.current) /}}
129
+ "endOffset": {{@ parse(it.root?.answer?.settings?.endOffset) /}}
122
130
  }`}],root:"{{ it.questions?.items | stringify }}"},{scenes:[{layout:"basic",data:`{
123
131
  "id": "{{ it.root?.answer?.id }}-outro",
124
132
  "mp4": {{@ parse(it.root?.answer?.media?.video) /}},
125
133
  "input": {{@ parse(it.root?.answer?.media?.input) /}},
126
134
  "playlist": {{@ parse(it.root?.answer?.media?.playlist) /}},
135
+ "poster": {{@ parse(it.root?.answer?.media?.thumbnail) /}},
136
+ "captions": {{@ parse(it.root?.answer?.captions?.current) /}},
127
137
  "duration": {{@ parse(it.root?.answer?.metadata?.duration) /}},
128
138
  "startOffset": {{@ parse(it.root?.answer?.settings?.startOffset) /}},
129
- "endOffset": {{@ parse(it.root?.answer?.settings?.endOffset) /}},
130
- "captions": {{@ parse(it.root?.answer?.captions?.current) /}}
131
- }`}],root:"{{ it.outro?.questions?.items | stringify }}"}]},meta:{transitionDuration:1/3}};async function Uu(){if(typeof window>"u"){const r=await Promise.resolve().then(()=>Qd);return new r.Image}return new Image}async function Zo(r){return r?new Promise(t=>{Uu().then(e=>{e.onload=()=>{t(e)},e.onerror=()=>{t(null)},e.src=r})}):null}async function gn({element:r},t,e){var i,s,n;let a={...r};const{node:o}=r;if((o==null?void 0:o.type)==="video"&&((i=o==null?void 0:o.value)!=null&&i.src||(s=o==null?void 0:o.value)!=null&&s.playlist)){const l=await t(o.value),h=await Zo(o.value.poster)??void 0;a={...a,node:{...o,video:l,poster:h,meta:await e(o.value,l.node)}}}if((o==null?void 0:o.type)==="image"&&o.value){const l=await Zo(o.value);l&&(a={...a,node:{...o,image:l}})}return a.node&&(n=r.node)!=null&&n.elements&&(a.node.elements=await Promise.all(r.node.elements.map(l=>gn({element:l},t,e)))),r.elements&&(a.elements=await Promise.all(r.elements.map(l=>gn({element:l},t,e)))),a}async function Jo(){if(typeof window>"u"){const r=await Promise.resolve().then(()=>Qd),t=new r.Canvas;return t.gpu=!1,t}return document.createElement("canvas")}async function Bu(r){var t;try{if((t=await Ru(r,{method:"HEAD"}))!=null&&t.ok)return r}catch{return}}async function Hu({sources:r}){let t=null;if(r){const e=r.filter(Boolean).map(i=>Bu(i));t=(await Promise.all(e)).find(Boolean)}return t}Bs.define("stringify",r=>JSON.stringify(r)),Bs.define("nullify",r=>typeof r>"u"?null:r),Bs.define("filter",(r,t)=>{if(!t)return r;if(!Array.isArray(r))throw new Error("Data for filter must be an array");return r.filter((e,i)=>t.includes(i))}),zi.define("parse",r=>{const t=r.params[0];return typeof t=="string"?`"${t.replace(/\n/g,"\\n").replace(/\r/g,"\\r")}"`:typeof t>"u"?null:t}),zi.define("resolve-source",async r=>{const{sources:t}=r.params[0]??{},e=t==null?void 0:t.filter(Boolean),i=e==null?void 0:e.find(a=>a.includes("blob:")),s=e==null?void 0:e.find(a=>!a.includes("http")),n=i??s??await Hu({sources:t});return n?`"${n}"`:"null"});const Ys=(r,t,e)=>Su(r,t,qi({autoEscape:!1,defaultFilter:"nullify",async:!0,asyncHelpers:["resolve-source"],...e}));function mn(r=[]){var t;for(const e of r)return((t=e==null?void 0:e.node)==null?void 0:t.type)==="video"?e.node:mn(e==null?void 0:e.elements)}async function tl({data:r,template:t=Nu,burnCaptions:e=!1},i,s){var n,a,o;const l=(await Promise.all(t.template.content.map(async({scenes:f,root:p})=>{const g={...t.options,...r,intro:t.intro,outro:t.outro};async function v(E){return Promise.all(f.map(async({layout:T,duration:A,data:y,options:b})=>{var S,R,D;const _=y?JSON.parse(await Ys(y,{...g,root:E})):{},I=b?JSON.parse(await Ys(b,g)):{},N=(S=t.template.layouts.find(w=>w.name===T))==null?void 0:S.tree,P=JSON.parse(await Ys(N,{..._,...I})),F=await Promise.all(P.flatMap(w=>gn({element:w},i,s))),K=mn(F);return{duration:A??((R=K==null?void 0:K.meta)==null?void 0:R.duration)??0,captions:(D=K==null?void 0:K.meta)==null?void 0:D.captions,elements:F}}))}if(p){const E=JSON.parse(await Ys(p,g));return Array.isArray(E)?(await Promise.all(E.map(async T=>v(T)))).flatMap(T=>T):v(E)}return v(r)}))).flatMap(f=>f).filter(f=>f.duration>0),h=((n=t.meta)==null?void 0:n.frameRate)??30,d=((a=t.meta)==null?void 0:a.resolution)??720,c=((o=t.meta)==null?void 0:o.transitionDuration)??1/3,u=await Promise.all(l.map(async({duration:f,captions:p,elements:g},v)=>{var E,T;const A=await Jo(),y=await Jo(),b=mn(g),S=l.reduce((R,D,_)=>(_<v&&(R+=D.duration-c/2),R),0);return{draw:({canvas:R,currentTime:D})=>{const _=Math.max(0,D-S);pn({canvas:R,elements:g,currentTime:D,relativeTime:_,offscreenCanvas:A}),p&&e&&Pu({canvas:R,dx:0,dy:0,dw:R.width,dh:R.height,vttCaptions:p,relativeTime:_+((b==null?void 0:b.meta.start)??0)})},duration:f,transitionCanvas:y,start:S,video:b==null?void 0:b.video,videoMeta:b==null?void 0:b.meta,audio:{duration:f,src:(E=b==null?void 0:b.value)==null?void 0:E.src,start:(T=b==null?void 0:b.meta)==null?void 0:T.start}}}));return{scenes:u,frameRate:h,resolution:d,transitionDuration:c,fonts:t.template.fonts??[],duration:Math.max(0,...u.map(({start:f,duration:p})=>f+p))}}/**
132
- * @license
133
- * Copyright 2017 Google LLC
134
- * SPDX-License-Identifier: BSD-3-Clause
135
- */const Qi={ATTRIBUTE:1,CHILD:2,PROPERTY:3,BOOLEAN_ATTRIBUTE:4,EVENT:5,ELEMENT:6},Zi=r=>(...t)=>({_$litDirective$:r,values:t});class zs{constructor(t){}get _$AU(){return this._$AM._$AU}_$AT(t,e,i){this._$Ct=t,this._$AM=e,this._$Ci=i}_$AS(t,e){return this.update(t,e)}update(t,e){return this.render(...e)}}/**
139
+ "endOffset": {{@ parse(it.root?.answer?.settings?.endOffset) /}}
140
+ }`}],root:"{{ it.outro?.questions?.items | stringify }}"}]},meta:{frameRate:30,resolution:720,transitionDuration:1/3}};async function bu(){if(typeof window>"u"){const r=await Promise.resolve().then(()=>kc);return new r.Image}return new Image}const Po=os(async function(r){return r?new Promise((t,e)=>{bu().then(i=>{i.onload=()=>{t(i)},i.onerror=s=>{e(s)},i.src=r})}):null});async function rn({element:r},t,e){var i,s,n;let a={...r};const{node:o}=r;if((o==null?void 0:o.type)==="video"&&((i=o==null?void 0:o.value)!=null&&i.src||(s=o==null?void 0:o.value)!=null&&s.playlist)){const l=await t(o.value);let h;try{h=await Po(o.value.poster)}catch{h=null}a={...a,node:{...o,video:l,poster:h,meta:await e(o.value,l.node)}}}if((o==null?void 0:o.type)==="image"&&o.value){let l;try{l=await Po(o.value)}catch{l=null}a={...a,node:{...o,image:l}}}return a.node&&(n=r.node)!=null&&n.elements&&(a.node.elements=await Promise.all(r.node.elements.map(l=>rn({element:l},t,e)))),r.elements&&(a.elements=await Promise.all(r.elements.map(l=>rn({element:l},t,e)))),a}async function Oo(){if(typeof window>"u"){const r=await Promise.resolve().then(()=>kc),t=new r.Canvas;return t.gpu=!1,t}return document.createElement("canvas")}async function Tu(r){var t;try{if((t=await ou(r,{method:"HEAD"}))!=null&&t.ok)return r}catch{return}}async function Au({sources:r}){let t=null;if(r){const e=r.filter(Boolean).map(i=>Tu(i));t=(await Promise.all(e)).find(Boolean)}return t}ai.filters.define("stringify",r=>JSON.stringify(r)),ai.filters.define("nullify",r=>typeof r>"u"?null:r),ai.filters.define("filter",(r,t)=>{if(!t)return r;if(!Array.isArray(r))throw new Error("Data for filter must be an array");return r.filter((e,i)=>t.includes(i))}),ai.helpers.define("parse",r=>{const t=r.params[0];return typeof t=="string"?`"${t.replace(/\n/g,"\\n").replace(/\r/g,"\\r")}"`:typeof t>"u"?null:t}),ai.helpers.define("resolve-source",os(async r=>{const{sources:t}=r.params[0]??{},e=t==null?void 0:t.filter(Boolean),i=e==null?void 0:e.find(a=>a.includes("blob:")),s=e==null?void 0:e.find(a=>!a.includes("http")),n=i??s??await Au({sources:t});return n?`"${n}"`:"null"},{cacheKey:([r])=>JSON.stringify(r.params[0]??{})}));const qs=(r,t,e)=>ai.render(r,t,ai.getConfig({autoEscape:!1,defaultFilter:"nullify",async:!0,asyncHelpers:["resolve-source"],...e}));function nn(r=[]){var t;for(const e of r){if(((t=e==null?void 0:e.node)==null?void 0:t.type)==="video")return e.node;const i=nn(e==null?void 0:e.elements);if(i)return i}}async function $o({data:r,template:t,burnCaptions:e=!1},i,s){var n,a,o;const l=t??Eu,h=(await Promise.all(l.template.content.map(async({scenes:p,root:g})=>{const v={...l.options,...r,intro:l.intro,outro:l.outro};async function E(A){return Promise.all(p.map(async({layout:L,duration:y,data:S,options:R})=>{var C,M,D;const I=S?JSON.parse(await qs(S,{...v,root:A})):{},G=R?JSON.parse(await qs(R,v)):{},F=(C=l.template.layouts.find(P=>P.name===L))==null?void 0:C.tree,V=JSON.parse(await qs(F,{...I,...G})),z=await Promise.all(V.flatMap(P=>rn({element:P},i,s))),w=nn(z);return{duration:y??((M=w==null?void 0:w.meta)==null?void 0:M.duration)??0,captions:(D=w==null?void 0:w.meta)==null?void 0:D.captions,elements:z}}))}if(g){const A=JSON.parse(await qs(g,v));return Array.isArray(A)?(await Promise.all(A.map(async L=>E(L)))).flatMap(L=>L):E(A)}return E(r)}))).flatMap(p=>p).filter(p=>p.duration>0),c=((n=l.meta)==null?void 0:n.frameRate)??30,d=((a=l.meta)==null?void 0:a.resolution)??720,u=((o=l.meta)==null?void 0:o.transitionDuration)??1/3,f=await Promise.all(h.map(async({duration:p,captions:g,elements:v},E)=>{var A,L;const y=await Oo(),S=await Oo(),R=nn(v),C=h.reduce((M,D,I)=>(I<E&&(M+=D.duration-u/2),M),0);return{draw:({canvas:M,currentTime:D})=>{const I=Math.max(0,D-C);sn({canvas:M,elements:v,currentTime:D,relativeTime:I,offscreenCanvas:y}),g&&e&&pu({canvas:M,dx:0,dy:0,dw:M.width,dh:M.height,vttCaptions:g,relativeTime:I+((R==null?void 0:R.meta.start)??0)})},duration:p,transitionCanvas:S,start:C,video:R==null?void 0:R.video,videoMeta:R==null?void 0:R.meta,audio:{duration:p,src:(A=R==null?void 0:R.value)==null?void 0:A.src,start:(L=R==null?void 0:R.meta)==null?void 0:L.start}}}));return{scenes:f,frameRate:c,resolution:d,transitionDuration:u,fonts:l.template.fonts??[],duration:Math.max(0,...f.map(({start:p,duration:g})=>p+g))}}/**
136
141
  * @license
137
142
  * Copyright 2018 Google LLC
138
143
  * SPDX-License-Identifier: BSD-3-Clause
139
- */const ht=Zi(class extends zs{constructor(r){var t;if(super(r),r.type!==Qi.ATTRIBUTE||r.name!=="class"||((t=r.strings)===null||t===void 0?void 0:t.length)>2)throw Error("`classMap()` can only be used in the `class` attribute and must be the only part in the attribute.")}render(r){return" "+Object.keys(r).filter(t=>r[t]).join(" ")+" "}update(r,[t]){var e,i;if(this.it===void 0){this.it=new Set,r.strings!==void 0&&(this.nt=new Set(r.strings.join(" ").split(/\s/).filter(n=>n!=="")));for(const n in t)t[n]&&!(!((e=this.nt)===null||e===void 0)&&e.has(n))&&this.it.add(n);return this.render(t)}const s=r.element.classList;this.it.forEach(n=>{n in t||(s.remove(n),this.it.delete(n))});for(const n in t){const a=!!t[n];a===this.it.has(n)||!((i=this.nt)===null||i===void 0)&&i.has(n)||(a?(s.add(n),this.it.add(n)):(s.remove(n),this.it.delete(n)))}return he}});/**
140
- * @license
141
- * Copyright 2018 Google LLC
142
- * SPDX-License-Identifier: BSD-3-Clause
143
- */const Ji=r=>r??gt;/**
144
- * @license
145
- * Copyright 2020 Google LLC
146
- * SPDX-License-Identifier: BSD-3-Clause
147
- */const{I:Gu}=vc,Vu=r=>r.strings===void 0,el=()=>document.createComment(""),ts=(r,t,e)=>{var i;const s=r._$AA.parentNode,n=t===void 0?r._$AB:t._$AA;if(e===void 0){const a=s.insertBefore(el(),n),o=s.insertBefore(el(),n);e=new Gu(a,o,r,r.options)}else{const a=e._$AB.nextSibling,o=e._$AM,l=o!==r;if(l){let h;(i=e._$AQ)===null||i===void 0||i.call(e,r),e._$AM=r,e._$AP!==void 0&&(h=r._$AU)!==o._$AU&&e._$AP(h)}if(a!==n||l){let h=e._$AA;for(;h!==a;){const d=h.nextSibling;s.insertBefore(h,n),h=d}}}return e},Xe=(r,t,e=r)=>(r._$AI(t,e),r),Ku={},ju=(r,t=Ku)=>r._$AH=t,Wu=r=>r._$AH,vn=r=>{var t;(t=r._$AP)===null||t===void 0||t.call(r,!1,!0);let e=r._$AA;const i=r._$AB.nextSibling;for(;e!==i;){const s=e.nextSibling;e.remove(),e=s}};/**
148
- * @license
149
- * Copyright 2017 Google LLC
150
- * SPDX-License-Identifier: BSD-3-Clause
151
- */const es=(r,t)=>{var e,i;const s=r._$AN;if(s===void 0)return!1;for(const n of s)(i=(e=n)._$AO)===null||i===void 0||i.call(e,t,!1),es(n,t);return!0},qs=r=>{let t,e;do{if((t=r._$AM)===void 0)break;e=t._$AN,e.delete(r),r=t}while((e==null?void 0:e.size)===0)},il=r=>{for(let t;t=r._$AM;r=t){let e=t._$AN;if(e===void 0)t._$AN=e=new Set;else if(e.has(r))break;e.add(r),qu(t)}};function Yu(r){this._$AN!==void 0?(qs(this),this._$AM=r,il(this)):this._$AM=r}function zu(r,t=!1,e=0){const i=this._$AH,s=this._$AN;if(s!==void 0&&s.size!==0)if(t)if(Array.isArray(i))for(let n=e;n<i.length;n++)es(i[n],!1),qs(i[n]);else i!=null&&(es(i,!1),qs(i));else es(this,r)}const qu=r=>{var t,e,i,s;r.type==Qi.CHILD&&((t=(i=r)._$AP)!==null&&t!==void 0||(i._$AP=zu),(e=(s=r)._$AQ)!==null&&e!==void 0||(s._$AQ=Yu))};let sl=class extends zs{constructor(){super(...arguments),this._$AN=void 0}_$AT(t,e,i){super._$AT(t,e,i),il(this),this.isConnected=t._$AU}_$AO(t,e=!0){var i,s;t!==this.isConnected&&(this.isConnected=t,t?(i=this.reconnected)===null||i===void 0||i.call(this):(s=this.disconnected)===null||s===void 0||s.call(this)),e&&(es(this,t),qs(this))}setValue(t){if(Vu(this._$Ct))this._$Ct._$AI(t,this);else{const e=[...this._$Ct._$AH];e[this._$Ci]=t,this._$Ct._$AI(e,this,0)}}disconnected(){}reconnected(){}};/**
152
- * @license
153
- * Copyright 2020 Google LLC
154
- * SPDX-License-Identifier: BSD-3-Clause
155
- */const de=()=>new Xu;class Xu{}const yn=new WeakMap,ce=Zi(class extends sl{render(r){return gt}update(r,[t]){var e;const i=t!==this.G;return i&&this.G!==void 0&&this.ot(void 0),(i||this.rt!==this.lt)&&(this.G=t,this.ct=(e=r.options)===null||e===void 0?void 0:e.host,this.ot(this.lt=r.element)),gt}ot(r){var t;if(typeof this.G=="function"){const e=(t=this.ct)!==null&&t!==void 0?t:globalThis;let i=yn.get(e);i===void 0&&(i=new WeakMap,yn.set(e,i)),i.get(this.G)!==void 0&&this.G.call(this.ct,void 0),i.set(this.G,r),r!==void 0&&this.G.call(this.ct,r)}else this.G.value=r}get rt(){var r,t,e;return typeof this.G=="function"?(t=yn.get((r=this.ct)!==null&&r!==void 0?r:globalThis))===null||t===void 0?void 0:t.get(this.G):(e=this.G)===null||e===void 0?void 0:e.value}disconnected(){this.rt===this.lt&&this.ot(void 0)}reconnected(){this.ot(this.lt)}});var Qu=is;is.flatten=is,is.unflatten=al;function rl(r){return r&&r.constructor&&typeof r.constructor.isBuffer=="function"&&r.constructor.isBuffer(r)}function nl(r){return r}function is(r,t){t=t||{};const e=t.delimiter||".",i=t.maxDepth,s=t.transformKey||nl,n={};function a(o,l,h){h=h||1,Object.keys(o).forEach(function(d){const c=o[d],u=t.safe&&Array.isArray(c),f=Object.prototype.toString.call(c),p=rl(c),g=f==="[object Object]"||f==="[object Array]",v=l?l+e+s(d):s(d);if(!u&&!p&&g&&Object.keys(c).length&&(!t.maxDepth||h<i))return a(c,v,h+1);n[v]=c})}return a(r),n}function al(r,t){t=t||{};const e=t.delimiter||".",i=t.overwrite||!1,s=t.transformKey||nl,n={};if(rl(r)||Object.prototype.toString.call(r)!=="[object Object]")return r;function o(d){const c=Number(d);return isNaN(c)||d.indexOf(".")!==-1||t.object?d:c}function l(d,c,u){return Object.keys(u).reduce(function(f,p){return f[d+e+p]=u[p],f},c)}function h(d){const c=Object.prototype.toString.call(d),u=c==="[object Array]",f=c==="[object Object]";if(d){if(u)return!d.length;if(f)return!Object.keys(d).length}else return!0}return r=Object.keys(r).reduce(function(d,c){const u=Object.prototype.toString.call(r[c]);return!(u==="[object Object]"||u==="[object Array]")||h(r[c])?(d[c]=r[c],d):l(c,d,is(r[c],t))},{}),Object.keys(r).forEach(function(d){const c=d.split(e).map(s);let u=o(c.shift()),f=o(c[0]),p=n;for(;f!==void 0;){if(u==="__proto__")return;const g=Object.prototype.toString.call(p[u]),v=g==="[object Object]"||g==="[object Array]";if(!i&&!v&&typeof p[u]<"u")return;(i&&!v||!i&&p[u]==null)&&(p[u]=typeof f=="number"&&!t.object?[]:{}),p=p[u],c.length>0&&(u=o(c.shift()),f=o(c[0]))}p[u]=al(r[d],t)}),n}const Zu=un(Qu);/**
144
+ */const wt=is(class extends Fs{constructor(r){var t;if(super(r),r.type!==es.ATTRIBUTE||r.name!=="class"||((t=r.strings)==null?void 0:t.length)>2)throw Error("`classMap()` can only be used in the `class` attribute and must be the only part in the attribute.")}render(r){return" "+Object.keys(r).filter(t=>r[t]).join(" ")+" "}update(r,[t]){var i,s;if(this.it===void 0){this.it=new Set,r.strings!==void 0&&(this.st=new Set(r.strings.join(" ").split(/\s/).filter(n=>n!=="")));for(const n in t)t[n]&&!((i=this.st)!=null&&i.has(n))&&this.it.add(n);return this.render(t)}const e=r.element.classList;for(const n of this.it)n in t||(e.remove(n),this.it.delete(n));for(const n in t){const a=!!t[n];a===this.it.has(n)||(s=this.st)!=null&&s.has(n)||(a?(e.add(n),this.it.add(n)):(e.remove(n),this.it.delete(n)))}return Ze}});var wu=hs;hs.flatten=hs,hs.unflatten=No;function Mo(r){return r&&r.constructor&&typeof r.constructor.isBuffer=="function"&&r.constructor.isBuffer(r)}function Fo(r){return r}function hs(r,t){t=t||{};const e=t.delimiter||".",i=t.maxDepth,s=t.transformKey||Fo,n={};function a(o,l,h){h=h||1,Object.keys(o).forEach(function(c){const d=o[c],u=t.safe&&Array.isArray(d),f=Object.prototype.toString.call(d),p=Mo(d),g=f==="[object Object]"||f==="[object Array]",v=l?l+e+s(c):s(c);if(!u&&!p&&g&&Object.keys(d).length&&(!t.maxDepth||h<i))return a(d,v,h+1);n[v]=d})}return a(r),n}function No(r,t){t=t||{};const e=t.delimiter||".",i=t.overwrite||!1,s=t.transformKey||Fo,n={};if(Mo(r)||Object.prototype.toString.call(r)!=="[object Object]")return r;function o(c){const d=Number(c);return isNaN(d)||c.indexOf(".")!==-1||t.object?c:d}function l(c,d,u){return Object.keys(u).reduce(function(f,p){return f[c+e+p]=u[p],f},d)}function h(c){const d=Object.prototype.toString.call(c),u=d==="[object Array]",f=d==="[object Object]";if(c){if(u)return!c.length;if(f)return!Object.keys(c).length}else return!0}return r=Object.keys(r).reduce(function(c,d){const u=Object.prototype.toString.call(r[d]);return!(u==="[object Object]"||u==="[object Array]")||h(r[d])?(c[d]=r[d],c):l(d,c,hs(r[d],t))},{}),Object.keys(r).forEach(function(c){const d=c.split(e).map(s);let u=o(d.shift()),f=o(d[0]),p=n;for(;f!==void 0;){if(u==="__proto__")return;const g=Object.prototype.toString.call(p[u]),v=g==="[object Object]"||g==="[object Array]";if(!i&&!v&&typeof p[u]<"u")return;(i&&!v||!i&&p[u]==null)&&(p[u]=typeof f=="number"&&!t.object?[]:{}),p=p[u],d.length>0&&(u=o(d.shift()),f=o(d[0]))}p[u]=No(r[c],t)}),n}const Su=Jr(wu);/**
156
145
  * @license
157
146
  * Copyright 2017 Google LLC
158
147
  * SPDX-License-Identifier: BSD-3-Clause
159
- */const ol=(r,t,e)=>{const i=new Map;for(let s=t;s<=e;s++)i.set(r[s],s);return i},ll=Zi(class extends zs{constructor(r){if(super(r),r.type!==Qi.CHILD)throw Error("repeat() can only be used in text expressions")}dt(r,t,e){let i;e===void 0?e=t:t!==void 0&&(i=t);const s=[],n=[];let a=0;for(const o of r)s[a]=i?i(o,a):a,n[a]=e(o,a),a++;return{values:n,keys:s}}render(r,t,e){return this.dt(r,t,e).values}update(r,[t,e,i]){var s;const n=Wu(r),{values:a,keys:o}=this.dt(t,e,i);if(!Array.isArray(n))return this.ht=o,a;const l=(s=this.ht)!==null&&s!==void 0?s:this.ht=[],h=[];let d,c,u=0,f=n.length-1,p=0,g=a.length-1;for(;u<=f&&p<=g;)if(n[u]===null)u++;else if(n[f]===null)f--;else if(l[u]===o[p])h[p]=Xe(n[u],a[p]),u++,p++;else if(l[f]===o[g])h[g]=Xe(n[f],a[g]),f--,g--;else if(l[u]===o[g])h[g]=Xe(n[u],a[g]),ts(r,h[g+1],n[u]),u++,g--;else if(l[f]===o[p])h[p]=Xe(n[f],a[p]),ts(r,n[u],n[f]),f--,p++;else if(d===void 0&&(d=ol(o,p,g),c=ol(l,u,f)),d.has(l[u]))if(d.has(l[f])){const v=c.get(o[p]),E=v!==void 0?n[v]:null;if(E===null){const T=ts(r,n[u]);Xe(T,a[p]),h[p]=T}else h[p]=Xe(E,a[p]),ts(r,n[u],E),n[v]=null;p++}else vn(n[f]),f--;else vn(n[u]),u++;for(;p<=g;){const v=ts(r,h[g+1]);Xe(v,a[p]),h[p++]=v}for(;u<=f;){const v=n[u++];v!==null&&vn(v)}return this.ht=o,ju(r,h),he}});var Bt="top",Xt="bottom",Qt="right",Ht="left",En="auto",ss=[Bt,Xt,Qt,Ht],mi="start",rs="end",Ju="clippingParents",hl="viewport",ns="popper",tf="reference",dl=ss.reduce(function(r,t){return r.concat([t+"-"+mi,t+"-"+rs])},[]),cl=[].concat(ss,[En]).reduce(function(r,t){return r.concat([t,t+"-"+mi,t+"-"+rs])},[]),ef="beforeRead",sf="read",rf="afterRead",nf="beforeMain",af="main",of="afterMain",lf="beforeWrite",hf="write",df="afterWrite",cf=[ef,sf,rf,nf,af,of,lf,hf,df];function ue(r){return r?(r.nodeName||"").toLowerCase():null}function zt(r){if(r==null)return window;if(r.toString()!=="[object Window]"){var t=r.ownerDocument;return t&&t.defaultView||window}return r}function Qe(r){var t=zt(r).Element;return r instanceof t||r instanceof Element}function Zt(r){var t=zt(r).HTMLElement;return r instanceof t||r instanceof HTMLElement}function Tn(r){if(typeof ShadowRoot>"u")return!1;var t=zt(r).ShadowRoot;return r instanceof t||r instanceof ShadowRoot}function uf(r){var t=r.state;Object.keys(t.elements).forEach(function(e){var i=t.styles[e]||{},s=t.attributes[e]||{},n=t.elements[e];!Zt(n)||!ue(n)||(Object.assign(n.style,i),Object.keys(s).forEach(function(a){var o=s[a];o===!1?n.removeAttribute(a):n.setAttribute(a,o===!0?"":o)}))})}function ff(r){var t=r.state,e={popper:{position:t.options.strategy,left:"0",top:"0",margin:"0"},arrow:{position:"absolute"},reference:{}};return Object.assign(t.elements.popper.style,e.popper),t.styles=e,t.elements.arrow&&Object.assign(t.elements.arrow.style,e.arrow),function(){Object.keys(t.elements).forEach(function(i){var s=t.elements[i],n=t.attributes[i]||{},a=Object.keys(t.styles.hasOwnProperty(i)?t.styles[i]:e[i]),o=a.reduce(function(l,h){return l[h]="",l},{});!Zt(s)||!ue(s)||(Object.assign(s.style,o),Object.keys(n).forEach(function(l){s.removeAttribute(l)}))})}}const ul={name:"applyStyles",enabled:!0,phase:"write",fn:uf,effect:ff,requires:["computeStyles"]};function fe(r){return r.split("-")[0]}var Ze=Math.max,Xs=Math.min,vi=Math.round;function bn(){var r=navigator.userAgentData;return r!=null&&r.brands&&Array.isArray(r.brands)?r.brands.map(function(t){return t.brand+"/"+t.version}).join(" "):navigator.userAgent}function fl(){return!/^((?!chrome|android).)*safari/i.test(bn())}function yi(r,t,e){t===void 0&&(t=!1),e===void 0&&(e=!1);var i=r.getBoundingClientRect(),s=1,n=1;t&&Zt(r)&&(s=r.offsetWidth>0&&vi(i.width)/r.offsetWidth||1,n=r.offsetHeight>0&&vi(i.height)/r.offsetHeight||1);var a=Qe(r)?zt(r):window,o=a.visualViewport,l=!fl()&&e,h=(i.left+(l&&o?o.offsetLeft:0))/s,d=(i.top+(l&&o?o.offsetTop:0))/n,c=i.width/s,u=i.height/n;return{width:c,height:u,top:d,right:h+c,bottom:d+u,left:h,x:h,y:d}}function An(r){var t=yi(r),e=r.offsetWidth,i=r.offsetHeight;return Math.abs(t.width-e)<=1&&(e=t.width),Math.abs(t.height-i)<=1&&(i=t.height),{x:r.offsetLeft,y:r.offsetTop,width:e,height:i}}function pl(r,t){var e=t.getRootNode&&t.getRootNode();if(r.contains(t))return!0;if(e&&Tn(e)){var i=t;do{if(i&&r.isSameNode(i))return!0;i=i.parentNode||i.host}while(i)}return!1}function Se(r){return zt(r).getComputedStyle(r)}function pf(r){return["table","td","th"].indexOf(ue(r))>=0}function Pe(r){return((Qe(r)?r.ownerDocument:r.document)||window.document).documentElement}function Qs(r){return ue(r)==="html"?r:r.assignedSlot||r.parentNode||(Tn(r)?r.host:null)||Pe(r)}function gl(r){return!Zt(r)||Se(r).position==="fixed"?null:r.offsetParent}function gf(r){var t=/firefox/i.test(bn()),e=/Trident/i.test(bn());if(e&&Zt(r)){var i=Se(r);if(i.position==="fixed")return null}var s=Qs(r);for(Tn(s)&&(s=s.host);Zt(s)&&["html","body"].indexOf(ue(s))<0;){var n=Se(s);if(n.transform!=="none"||n.perspective!=="none"||n.contain==="paint"||["transform","perspective"].indexOf(n.willChange)!==-1||t&&n.willChange==="filter"||t&&n.filter&&n.filter!=="none")return s;s=s.parentNode}return null}function as(r){for(var t=zt(r),e=gl(r);e&&pf(e)&&Se(e).position==="static";)e=gl(e);return e&&(ue(e)==="html"||ue(e)==="body"&&Se(e).position==="static")?t:e||gf(r)||t}function wn(r){return["top","bottom"].indexOf(r)>=0?"x":"y"}function os(r,t,e){return Ze(r,Xs(t,e))}function mf(r,t,e){var i=os(r,t,e);return i>e?e:i}function ml(){return{top:0,right:0,bottom:0,left:0}}function vl(r){return Object.assign({},ml(),r)}function yl(r,t){return t.reduce(function(e,i){return e[i]=r,e},{})}var vf=function(t,e){return t=typeof t=="function"?t(Object.assign({},e.rects,{placement:e.placement})):t,vl(typeof t!="number"?t:yl(t,ss))};function yf(r){var t,e=r.state,i=r.name,s=r.options,n=e.elements.arrow,a=e.modifiersData.popperOffsets,o=fe(e.placement),l=wn(o),h=[Ht,Qt].indexOf(o)>=0,d=h?"height":"width";if(!(!n||!a)){var c=vf(s.padding,e),u=An(n),f=l==="y"?Bt:Ht,p=l==="y"?Xt:Qt,g=e.rects.reference[d]+e.rects.reference[l]-a[l]-e.rects.popper[d],v=a[l]-e.rects.reference[l],E=as(n),T=E?l==="y"?E.clientHeight||0:E.clientWidth||0:0,A=g/2-v/2,y=c[f],b=T-u[d]-c[p],S=T/2-u[d]/2+A,R=os(y,S,b),D=l;e.modifiersData[i]=(t={},t[D]=R,t.centerOffset=R-S,t)}}function Ef(r){var t=r.state,e=r.options,i=e.element,s=i===void 0?"[data-popper-arrow]":i;s!=null&&(typeof s=="string"&&(s=t.elements.popper.querySelector(s),!s)||pl(t.elements.popper,s)&&(t.elements.arrow=s))}const Tf={name:"arrow",enabled:!0,phase:"main",fn:yf,effect:Ef,requires:["popperOffsets"],requiresIfExists:["preventOverflow"]};function Ei(r){return r.split("-")[1]}var bf={top:"auto",right:"auto",bottom:"auto",left:"auto"};function Af(r,t){var e=r.x,i=r.y,s=t.devicePixelRatio||1;return{x:vi(e*s)/s||0,y:vi(i*s)/s||0}}function El(r){var t,e=r.popper,i=r.popperRect,s=r.placement,n=r.variation,a=r.offsets,o=r.position,l=r.gpuAcceleration,h=r.adaptive,d=r.roundOffsets,c=r.isFixed,u=a.x,f=u===void 0?0:u,p=a.y,g=p===void 0?0:p,v=typeof d=="function"?d({x:f,y:g}):{x:f,y:g};f=v.x,g=v.y;var E=a.hasOwnProperty("x"),T=a.hasOwnProperty("y"),A=Ht,y=Bt,b=window;if(h){var S=as(e),R="clientHeight",D="clientWidth";if(S===zt(e)&&(S=Pe(e),Se(S).position!=="static"&&o==="absolute"&&(R="scrollHeight",D="scrollWidth")),S=S,s===Bt||(s===Ht||s===Qt)&&n===rs){y=Xt;var _=c&&S===b&&b.visualViewport?b.visualViewport.height:S[R];g-=_-i.height,g*=l?1:-1}if(s===Ht||(s===Bt||s===Xt)&&n===rs){A=Qt;var I=c&&S===b&&b.visualViewport?b.visualViewport.width:S[D];f-=I-i.width,f*=l?1:-1}}var N=Object.assign({position:o},h&&bf),P=d===!0?Af({x:f,y:g},zt(e)):{x:f,y:g};if(f=P.x,g=P.y,l){var F;return Object.assign({},N,(F={},F[y]=T?"0":"",F[A]=E?"0":"",F.transform=(b.devicePixelRatio||1)<=1?"translate("+f+"px, "+g+"px)":"translate3d("+f+"px, "+g+"px, 0)",F))}return Object.assign({},N,(t={},t[y]=T?g+"px":"",t[A]=E?f+"px":"",t.transform="",t))}function wf(r){var t=r.state,e=r.options,i=e.gpuAcceleration,s=i===void 0?!0:i,n=e.adaptive,a=n===void 0?!0:n,o=e.roundOffsets,l=o===void 0?!0:o,h={placement:fe(t.placement),variation:Ei(t.placement),popper:t.elements.popper,popperRect:t.rects.popper,gpuAcceleration:s,isFixed:t.options.strategy==="fixed"};t.modifiersData.popperOffsets!=null&&(t.styles.popper=Object.assign({},t.styles.popper,El(Object.assign({},h,{offsets:t.modifiersData.popperOffsets,position:t.options.strategy,adaptive:a,roundOffsets:l})))),t.modifiersData.arrow!=null&&(t.styles.arrow=Object.assign({},t.styles.arrow,El(Object.assign({},h,{offsets:t.modifiersData.arrow,position:"absolute",adaptive:!1,roundOffsets:l})))),t.attributes.popper=Object.assign({},t.attributes.popper,{"data-popper-placement":t.placement})}const Sf={name:"computeStyles",enabled:!0,phase:"beforeWrite",fn:wf,data:{}};var Zs={passive:!0};function Lf(r){var t=r.state,e=r.instance,i=r.options,s=i.scroll,n=s===void 0?!0:s,a=i.resize,o=a===void 0?!0:a,l=zt(t.elements.popper),h=[].concat(t.scrollParents.reference,t.scrollParents.popper);return n&&h.forEach(function(d){d.addEventListener("scroll",e.update,Zs)}),o&&l.addEventListener("resize",e.update,Zs),function(){n&&h.forEach(function(d){d.removeEventListener("scroll",e.update,Zs)}),o&&l.removeEventListener("resize",e.update,Zs)}}const Rf={name:"eventListeners",enabled:!0,phase:"write",fn:function(){},effect:Lf,data:{}};var _f={left:"right",right:"left",bottom:"top",top:"bottom"};function Js(r){return r.replace(/left|right|bottom|top/g,function(t){return _f[t]})}var If={start:"end",end:"start"};function Tl(r){return r.replace(/start|end/g,function(t){return If[t]})}function Sn(r){var t=zt(r),e=t.pageXOffset,i=t.pageYOffset;return{scrollLeft:e,scrollTop:i}}function Ln(r){return yi(Pe(r)).left+Sn(r).scrollLeft}function kf(r,t){var e=zt(r),i=Pe(r),s=e.visualViewport,n=i.clientWidth,a=i.clientHeight,o=0,l=0;if(s){n=s.width,a=s.height;var h=fl();(h||!h&&t==="fixed")&&(o=s.offsetLeft,l=s.offsetTop)}return{width:n,height:a,x:o+Ln(r),y:l}}function Cf(r){var t,e=Pe(r),i=Sn(r),s=(t=r.ownerDocument)==null?void 0:t.body,n=Ze(e.scrollWidth,e.clientWidth,s?s.scrollWidth:0,s?s.clientWidth:0),a=Ze(e.scrollHeight,e.clientHeight,s?s.scrollHeight:0,s?s.clientHeight:0),o=-i.scrollLeft+Ln(r),l=-i.scrollTop;return Se(s||e).direction==="rtl"&&(o+=Ze(e.clientWidth,s?s.clientWidth:0)-n),{width:n,height:a,x:o,y:l}}function Rn(r){var t=Se(r),e=t.overflow,i=t.overflowX,s=t.overflowY;return/auto|scroll|overlay|hidden/.test(e+s+i)}function bl(r){return["html","body","#document"].indexOf(ue(r))>=0?r.ownerDocument.body:Zt(r)&&Rn(r)?r:bl(Qs(r))}function ls(r,t){var e;t===void 0&&(t=[]);var i=bl(r),s=i===((e=r.ownerDocument)==null?void 0:e.body),n=zt(i),a=s?[n].concat(n.visualViewport||[],Rn(i)?i:[]):i,o=t.concat(a);return s?o:o.concat(ls(Qs(a)))}function _n(r){return Object.assign({},r,{left:r.x,top:r.y,right:r.x+r.width,bottom:r.y+r.height})}function Df(r,t){var e=yi(r,!1,t==="fixed");return e.top=e.top+r.clientTop,e.left=e.left+r.clientLeft,e.bottom=e.top+r.clientHeight,e.right=e.left+r.clientWidth,e.width=r.clientWidth,e.height=r.clientHeight,e.x=e.left,e.y=e.top,e}function Al(r,t,e){return t===hl?_n(kf(r,e)):Qe(t)?Df(t,e):_n(Cf(Pe(r)))}function xf(r){var t=ls(Qs(r)),e=["absolute","fixed"].indexOf(Se(r).position)>=0,i=e&&Zt(r)?as(r):r;return Qe(i)?t.filter(function(s){return Qe(s)&&pl(s,i)&&ue(s)!=="body"}):[]}function Pf(r,t,e,i){var s=t==="clippingParents"?xf(r):[].concat(t),n=[].concat(s,[e]),a=n[0],o=n.reduce(function(l,h){var d=Al(r,h,i);return l.top=Ze(d.top,l.top),l.right=Xs(d.right,l.right),l.bottom=Xs(d.bottom,l.bottom),l.left=Ze(d.left,l.left),l},Al(r,a,i));return o.width=o.right-o.left,o.height=o.bottom-o.top,o.x=o.left,o.y=o.top,o}function wl(r){var t=r.reference,e=r.element,i=r.placement,s=i?fe(i):null,n=i?Ei(i):null,a=t.x+t.width/2-e.width/2,o=t.y+t.height/2-e.height/2,l;switch(s){case Bt:l={x:a,y:t.y-e.height};break;case Xt:l={x:a,y:t.y+t.height};break;case Qt:l={x:t.x+t.width,y:o};break;case Ht:l={x:t.x-e.width,y:o};break;default:l={x:t.x,y:t.y}}var h=s?wn(s):null;if(h!=null){var d=h==="y"?"height":"width";switch(n){case mi:l[h]=l[h]-(t[d]/2-e[d]/2);break;case rs:l[h]=l[h]+(t[d]/2-e[d]/2);break}}return l}function hs(r,t){t===void 0&&(t={});var e=t,i=e.placement,s=i===void 0?r.placement:i,n=e.strategy,a=n===void 0?r.strategy:n,o=e.boundary,l=o===void 0?Ju:o,h=e.rootBoundary,d=h===void 0?hl:h,c=e.elementContext,u=c===void 0?ns:c,f=e.altBoundary,p=f===void 0?!1:f,g=e.padding,v=g===void 0?0:g,E=vl(typeof v!="number"?v:yl(v,ss)),T=u===ns?tf:ns,A=r.rects.popper,y=r.elements[p?T:u],b=Pf(Qe(y)?y:y.contextElement||Pe(r.elements.popper),l,d,a),S=yi(r.elements.reference),R=wl({reference:S,element:A,strategy:"absolute",placement:s}),D=_n(Object.assign({},A,R)),_=u===ns?D:S,I={top:b.top-_.top+E.top,bottom:_.bottom-b.bottom+E.bottom,left:b.left-_.left+E.left,right:_.right-b.right+E.right},N=r.modifiersData.offset;if(u===ns&&N){var P=N[s];Object.keys(I).forEach(function(F){var K=[Qt,Xt].indexOf(F)>=0?1:-1,w=[Bt,Xt].indexOf(F)>=0?"y":"x";I[F]+=P[w]*K})}return I}function Of(r,t){t===void 0&&(t={});var e=t,i=e.placement,s=e.boundary,n=e.rootBoundary,a=e.padding,o=e.flipVariations,l=e.allowedAutoPlacements,h=l===void 0?cl:l,d=Ei(i),c=d?o?dl:dl.filter(function(p){return Ei(p)===d}):ss,u=c.filter(function(p){return h.indexOf(p)>=0});u.length===0&&(u=c);var f=u.reduce(function(p,g){return p[g]=hs(r,{placement:g,boundary:s,rootBoundary:n,padding:a})[fe(g)],p},{});return Object.keys(f).sort(function(p,g){return f[p]-f[g]})}function Mf(r){if(fe(r)===En)return[];var t=Js(r);return[Tl(r),t,Tl(t)]}function $f(r){var t=r.state,e=r.options,i=r.name;if(!t.modifiersData[i]._skip){for(var s=e.mainAxis,n=s===void 0?!0:s,a=e.altAxis,o=a===void 0?!0:a,l=e.fallbackPlacements,h=e.padding,d=e.boundary,c=e.rootBoundary,u=e.altBoundary,f=e.flipVariations,p=f===void 0?!0:f,g=e.allowedAutoPlacements,v=t.options.placement,E=fe(v),T=E===v,A=l||(T||!p?[Js(v)]:Mf(v)),y=[v].concat(A).reduce(function(it,tt){return it.concat(fe(tt)===En?Of(t,{placement:tt,boundary:d,rootBoundary:c,padding:h,flipVariations:p,allowedAutoPlacements:g}):tt)},[]),b=t.rects.reference,S=t.rects.popper,R=new Map,D=!0,_=y[0],I=0;I<y.length;I++){var N=y[I],P=fe(N),F=Ei(N)===mi,K=[Bt,Xt].indexOf(P)>=0,w=K?"width":"height",C=hs(t,{placement:N,boundary:d,rootBoundary:c,altBoundary:u,padding:h}),U=K?F?Qt:Ht:F?Xt:Bt;b[w]>S[w]&&(U=Js(U));var M=Js(U),B=[];if(n&&B.push(C[P]<=0),o&&B.push(C[U]<=0,C[M]<=0),B.every(function(it){return it})){_=N,D=!1;break}R.set(N,B)}if(D)for(var H=p?3:1,z=function(tt){var xt=y.find(function(St){var yt=R.get(St);if(yt)return yt.slice(0,tt).every(function(Te){return Te})});if(xt)return _=xt,"break"},Z=H;Z>0;Z--){var Q=z(Z);if(Q==="break")break}t.placement!==_&&(t.modifiersData[i]._skip=!0,t.placement=_,t.reset=!0)}}const Ff={name:"flip",enabled:!0,phase:"main",fn:$f,requiresIfExists:["offset"],data:{_skip:!1}};function Sl(r,t,e){return e===void 0&&(e={x:0,y:0}),{top:r.top-t.height-e.y,right:r.right-t.width+e.x,bottom:r.bottom-t.height+e.y,left:r.left-t.width-e.x}}function Ll(r){return[Bt,Qt,Xt,Ht].some(function(t){return r[t]>=0})}function Nf(r){var t=r.state,e=r.name,i=t.rects.reference,s=t.rects.popper,n=t.modifiersData.preventOverflow,a=hs(t,{elementContext:"reference"}),o=hs(t,{altBoundary:!0}),l=Sl(a,i),h=Sl(o,s,n),d=Ll(l),c=Ll(h);t.modifiersData[e]={referenceClippingOffsets:l,popperEscapeOffsets:h,isReferenceHidden:d,hasPopperEscaped:c},t.attributes.popper=Object.assign({},t.attributes.popper,{"data-popper-reference-hidden":d,"data-popper-escaped":c})}const Uf={name:"hide",enabled:!0,phase:"main",requiresIfExists:["preventOverflow"],fn:Nf};function Bf(r,t,e){var i=fe(r),s=[Ht,Bt].indexOf(i)>=0?-1:1,n=typeof e=="function"?e(Object.assign({},t,{placement:r})):e,a=n[0],o=n[1];return a=a||0,o=(o||0)*s,[Ht,Qt].indexOf(i)>=0?{x:o,y:a}:{x:a,y:o}}function Hf(r){var t=r.state,e=r.options,i=r.name,s=e.offset,n=s===void 0?[0,0]:s,a=cl.reduce(function(d,c){return d[c]=Bf(c,t.rects,n),d},{}),o=a[t.placement],l=o.x,h=o.y;t.modifiersData.popperOffsets!=null&&(t.modifiersData.popperOffsets.x+=l,t.modifiersData.popperOffsets.y+=h),t.modifiersData[i]=a}const Gf={name:"offset",enabled:!0,phase:"main",requires:["popperOffsets"],fn:Hf};function Vf(r){var t=r.state,e=r.name;t.modifiersData[e]=wl({reference:t.rects.reference,element:t.rects.popper,strategy:"absolute",placement:t.placement})}const Kf={name:"popperOffsets",enabled:!0,phase:"read",fn:Vf,data:{}};function jf(r){return r==="x"?"y":"x"}function Wf(r){var t=r.state,e=r.options,i=r.name,s=e.mainAxis,n=s===void 0?!0:s,a=e.altAxis,o=a===void 0?!1:a,l=e.boundary,h=e.rootBoundary,d=e.altBoundary,c=e.padding,u=e.tether,f=u===void 0?!0:u,p=e.tetherOffset,g=p===void 0?0:p,v=hs(t,{boundary:l,rootBoundary:h,padding:c,altBoundary:d}),E=fe(t.placement),T=Ei(t.placement),A=!T,y=wn(E),b=jf(y),S=t.modifiersData.popperOffsets,R=t.rects.reference,D=t.rects.popper,_=typeof g=="function"?g(Object.assign({},t.rects,{placement:t.placement})):g,I=typeof _=="number"?{mainAxis:_,altAxis:_}:Object.assign({mainAxis:0,altAxis:0},_),N=t.modifiersData.offset?t.modifiersData.offset[t.placement]:null,P={x:0,y:0};if(S){if(n){var F,K=y==="y"?Bt:Ht,w=y==="y"?Xt:Qt,C=y==="y"?"height":"width",U=S[y],M=U+v[K],B=U-v[w],H=f?-D[C]/2:0,z=T===mi?R[C]:D[C],Z=T===mi?-D[C]:-R[C],Q=t.elements.arrow,it=f&&Q?An(Q):{width:0,height:0},tt=t.modifiersData["arrow#persistent"]?t.modifiersData["arrow#persistent"].padding:ml(),xt=tt[K],St=tt[w],yt=os(0,R[C],it[C]),Te=A?R[C]/2-H-yt-xt-I.mainAxis:z-yt-xt-I.mainAxis,Et=A?-R[C]/2+H+yt+St+I.mainAxis:Z+yt+St+I.mainAxis,Ue=t.elements.arrow&&as(t.elements.arrow),Di=Ue?y==="y"?Ue.clientTop||0:Ue.clientLeft||0:0,Be=(F=N==null?void 0:N[y])!=null?F:0,oi=U+Te-Be-Di,Tt=U+Et-Be,mt=os(f?Xs(M,oi):M,U,f?Ze(B,Tt):B);S[y]=mt,P[y]=mt-U}if(o){var Wt,ft=y==="x"?Bt:Ht,bt=y==="x"?Xt:Qt,Pt=S[b],Yt=b==="y"?"height":"width",As=Pt+v[ft],li=Pt-v[bt],ws=[Bt,Ht].indexOf(E)!==-1,Ir=(Wt=N==null?void 0:N[b])!=null?Wt:0,kr=ws?As:Pt-R[Yt]-D[Yt]-Ir+I.altAxis,Cr=ws?Pt+R[Yt]+D[Yt]-Ir-I.altAxis:li,Dr=f&&ws?mf(kr,Pt,Cr):os(f?kr:As,Pt,f?Cr:li);S[b]=Dr,P[b]=Dr-Pt}t.modifiersData[i]=P}}const Yf={name:"preventOverflow",enabled:!0,phase:"main",fn:Wf,requiresIfExists:["offset"]};function zf(r){return{scrollLeft:r.scrollLeft,scrollTop:r.scrollTop}}function qf(r){return r===zt(r)||!Zt(r)?Sn(r):zf(r)}function Xf(r){var t=r.getBoundingClientRect(),e=vi(t.width)/r.offsetWidth||1,i=vi(t.height)/r.offsetHeight||1;return e!==1||i!==1}function Qf(r,t,e){e===void 0&&(e=!1);var i=Zt(t),s=Zt(t)&&Xf(t),n=Pe(t),a=yi(r,s,e),o={scrollLeft:0,scrollTop:0},l={x:0,y:0};return(i||!i&&!e)&&((ue(t)!=="body"||Rn(n))&&(o=qf(t)),Zt(t)?(l=yi(t,!0),l.x+=t.clientLeft,l.y+=t.clientTop):n&&(l.x=Ln(n))),{x:a.left+o.scrollLeft-l.x,y:a.top+o.scrollTop-l.y,width:a.width,height:a.height}}function Zf(r){var t=new Map,e=new Set,i=[];r.forEach(function(n){t.set(n.name,n)});function s(n){e.add(n.name);var a=[].concat(n.requires||[],n.requiresIfExists||[]);a.forEach(function(o){if(!e.has(o)){var l=t.get(o);l&&s(l)}}),i.push(n)}return r.forEach(function(n){e.has(n.name)||s(n)}),i}function Jf(r){var t=Zf(r);return cf.reduce(function(e,i){return e.concat(t.filter(function(s){return s.phase===i}))},[])}function tp(r){var t;return function(){return t||(t=new Promise(function(e){Promise.resolve().then(function(){t=void 0,e(r())})})),t}}function ep(r){var t=r.reduce(function(e,i){var s=e[i.name];return e[i.name]=s?Object.assign({},s,i,{options:Object.assign({},s.options,i.options),data:Object.assign({},s.data,i.data)}):i,e},{});return Object.keys(t).map(function(e){return t[e]})}var Rl={placement:"bottom",modifiers:[],strategy:"absolute"};function _l(){for(var r=arguments.length,t=new Array(r),e=0;e<r;e++)t[e]=arguments[e];return!t.some(function(i){return!(i&&typeof i.getBoundingClientRect=="function")})}function ip(r){r===void 0&&(r={});var t=r,e=t.defaultModifiers,i=e===void 0?[]:e,s=t.defaultOptions,n=s===void 0?Rl:s;return function(o,l,h){h===void 0&&(h=n);var d={placement:"bottom",orderedModifiers:[],options:Object.assign({},Rl,n),modifiersData:{},elements:{reference:o,popper:l},attributes:{},styles:{}},c=[],u=!1,f={state:d,setOptions:function(E){var T=typeof E=="function"?E(d.options):E;g(),d.options=Object.assign({},n,d.options,T),d.scrollParents={reference:Qe(o)?ls(o):o.contextElement?ls(o.contextElement):[],popper:ls(l)};var A=Jf(ep([].concat(i,d.options.modifiers)));return d.orderedModifiers=A.filter(function(y){return y.enabled}),p(),f.update()},forceUpdate:function(){if(!u){var E=d.elements,T=E.reference,A=E.popper;if(_l(T,A)){d.rects={reference:Qf(T,as(A),d.options.strategy==="fixed"),popper:An(A)},d.reset=!1,d.placement=d.options.placement,d.orderedModifiers.forEach(function(I){return d.modifiersData[I.name]=Object.assign({},I.data)});for(var y=0;y<d.orderedModifiers.length;y++){if(d.reset===!0){d.reset=!1,y=-1;continue}var b=d.orderedModifiers[y],S=b.fn,R=b.options,D=R===void 0?{}:R,_=b.name;typeof S=="function"&&(d=S({state:d,options:D,name:_,instance:f})||d)}}}},update:tp(function(){return new Promise(function(v){f.forceUpdate(),v(d)})}),destroy:function(){g(),u=!0}};if(!_l(o,l))return f;f.setOptions(h).then(function(v){!u&&h.onFirstUpdate&&h.onFirstUpdate(v)});function p(){d.orderedModifiers.forEach(function(v){var E=v.name,T=v.options,A=T===void 0?{}:T,y=v.effect;if(typeof y=="function"){var b=y({state:d,name:E,instance:f,options:A}),S=function(){};c.push(b||S)}})}function g(){c.forEach(function(v){return v()}),c=[]}return f}}var sp=[Rf,Kf,Sf,ul,Gf,Ff,Yf,Tf,Uf],rp=ip({defaultModifiers:sp}),np="tippy-box",Il="tippy-content",ap="tippy-backdrop",kl="tippy-arrow",Cl="tippy-svg-arrow",Je={passive:!0,capture:!0},Dl=function(){return document.body};function In(r,t,e){if(Array.isArray(r)){var i=r[t];return i??(Array.isArray(e)?e[t]:e)}return r}function kn(r,t){var e={}.toString.call(r);return e.indexOf("[object")===0&&e.indexOf(t+"]")>-1}function xl(r,t){return typeof r=="function"?r.apply(void 0,t):r}function Pl(r,t){if(t===0)return r;var e;return function(i){clearTimeout(e),e=setTimeout(function(){r(i)},t)}}function op(r){return r.split(/\s+/).filter(Boolean)}function Ti(r){return[].concat(r)}function Ol(r,t){r.indexOf(t)===-1&&r.push(t)}function lp(r){return r.filter(function(t,e){return r.indexOf(t)===e})}function hp(r){return r.split("-")[0]}function tr(r){return[].slice.call(r)}function Ml(r){return Object.keys(r).reduce(function(t,e){return r[e]!==void 0&&(t[e]=r[e]),t},{})}function ds(){return document.createElement("div")}function er(r){return["Element","Fragment"].some(function(t){return kn(r,t)})}function dp(r){return kn(r,"NodeList")}function cp(r){return kn(r,"MouseEvent")}function up(r){return!!(r&&r._tippy&&r._tippy.reference===r)}function fp(r){return er(r)?[r]:dp(r)?tr(r):Array.isArray(r)?r:tr(document.querySelectorAll(r))}function Cn(r,t){r.forEach(function(e){e&&(e.style.transitionDuration=t+"ms")})}function $l(r,t){r.forEach(function(e){e&&e.setAttribute("data-state",t)})}function pp(r){var t,e=Ti(r),i=e[0];return i!=null&&(t=i.ownerDocument)!=null&&t.body?i.ownerDocument:document}function gp(r,t){var e=t.clientX,i=t.clientY;return r.every(function(s){var n=s.popperRect,a=s.popperState,o=s.props,l=o.interactiveBorder,h=hp(a.placement),d=a.modifiersData.offset;if(!d)return!0;var c=h==="bottom"?d.top.y:0,u=h==="top"?d.bottom.y:0,f=h==="right"?d.left.x:0,p=h==="left"?d.right.x:0,g=n.top-i+c>l,v=i-n.bottom-u>l,E=n.left-e+f>l,T=e-n.right-p>l;return g||v||E||T})}function Dn(r,t,e){var i=t+"EventListener";["transitionend","webkitTransitionEnd"].forEach(function(s){r[i](s,e)})}function Fl(r,t){for(var e=t;e;){var i;if(r.contains(e))return!0;e=e.getRootNode==null||(i=e.getRootNode())==null?void 0:i.host}return!1}var pe={isTouch:!1},Nl=0;function mp(){pe.isTouch||(pe.isTouch=!0,window.performance&&document.addEventListener("mousemove",Ul))}function Ul(){var r=performance.now();r-Nl<20&&(pe.isTouch=!1,document.removeEventListener("mousemove",Ul)),Nl=r}function vp(){var r=document.activeElement;if(up(r)){var t=r._tippy;r.blur&&!t.state.isVisible&&r.blur()}}function yp(){document.addEventListener("touchstart",mp,Je),window.addEventListener("blur",vp)}var Ep=typeof window<"u"&&typeof document<"u",Tp=Ep?!!window.msCrypto:!1,bp={animateFill:!1,followCursor:!1,inlinePositioning:!1,sticky:!1},Ap={allowHTML:!1,animation:"fade",arrow:!0,content:"",inertia:!1,maxWidth:350,role:"tooltip",theme:"",zIndex:9999},re=Object.assign({appendTo:Dl,aria:{content:"auto",expanded:"auto"},delay:0,duration:[300,250],getReferenceClientRect:null,hideOnClick:!0,ignoreAttributes:!1,interactive:!1,interactiveBorder:2,interactiveDebounce:0,moveTransition:"",offset:[0,10],onAfterUpdate:function(){},onBeforeUpdate:function(){},onCreate:function(){},onDestroy:function(){},onHidden:function(){},onHide:function(){},onMount:function(){},onShow:function(){},onShown:function(){},onTrigger:function(){},onUntrigger:function(){},onClickOutside:function(){},placement:"top",plugins:[],popperOptions:{},render:null,showOnCreate:!1,touch:!0,trigger:"mouseenter focus",triggerTarget:null},bp,Ap),wp=Object.keys(re),Sp=function(t){var e=Object.keys(t);e.forEach(function(i){re[i]=t[i]})};function Bl(r){var t=r.plugins||[],e=t.reduce(function(i,s){var n=s.name,a=s.defaultValue;if(n){var o;i[n]=r[n]!==void 0?r[n]:(o=re[n])!=null?o:a}return i},{});return Object.assign({},r,e)}function Lp(r,t){var e=t?Object.keys(Bl(Object.assign({},re,{plugins:t}))):wp,i=e.reduce(function(s,n){var a=(r.getAttribute("data-tippy-"+n)||"").trim();if(!a)return s;if(n==="content")s[n]=a;else try{s[n]=JSON.parse(a)}catch{s[n]=a}return s},{});return i}function Hl(r,t){var e=Object.assign({},t,{content:xl(t.content,[r])},t.ignoreAttributes?{}:Lp(r,t.plugins));return e.aria=Object.assign({},re.aria,e.aria),e.aria={expanded:e.aria.expanded==="auto"?t.interactive:e.aria.expanded,content:e.aria.content==="auto"?t.interactive?null:"describedby":e.aria.content},e}var Rp=function(){return"innerHTML"};function xn(r,t){r[Rp()]=t}function Gl(r){var t=ds();return r===!0?t.className=kl:(t.className=Cl,er(r)?t.appendChild(r):xn(t,r)),t}function Vl(r,t){er(t.content)?(xn(r,""),r.appendChild(t.content)):typeof t.content!="function"&&(t.allowHTML?xn(r,t.content):r.textContent=t.content)}function Pn(r){var t=r.firstElementChild,e=tr(t.children);return{box:t,content:e.find(function(i){return i.classList.contains(Il)}),arrow:e.find(function(i){return i.classList.contains(kl)||i.classList.contains(Cl)}),backdrop:e.find(function(i){return i.classList.contains(ap)})}}function Kl(r){var t=ds(),e=ds();e.className=np,e.setAttribute("data-state","hidden"),e.setAttribute("tabindex","-1");var i=ds();i.className=Il,i.setAttribute("data-state","hidden"),Vl(i,r.props),t.appendChild(e),e.appendChild(i),s(r.props,r.props);function s(n,a){var o=Pn(t),l=o.box,h=o.content,d=o.arrow;a.theme?l.setAttribute("data-theme",a.theme):l.removeAttribute("data-theme"),typeof a.animation=="string"?l.setAttribute("data-animation",a.animation):l.removeAttribute("data-animation"),a.inertia?l.setAttribute("data-inertia",""):l.removeAttribute("data-inertia"),l.style.maxWidth=typeof a.maxWidth=="number"?a.maxWidth+"px":a.maxWidth,a.role?l.setAttribute("role",a.role):l.removeAttribute("role"),(n.content!==a.content||n.allowHTML!==a.allowHTML)&&Vl(h,r.props),a.arrow?d?n.arrow!==a.arrow&&(l.removeChild(d),l.appendChild(Gl(a.arrow))):l.appendChild(Gl(a.arrow)):d&&l.removeChild(d)}return{popper:t,onUpdate:s}}Kl.$$tippy=!0;var _p=1,ir=[],On=[];function Ip(r,t){var e=Hl(r,Object.assign({},re,Bl(Ml(t)))),i,s,n,a=!1,o=!1,l=!1,h=!1,d,c,u,f=[],p=Pl(oi,e.interactiveDebounce),g,v=_p++,E=null,T=lp(e.plugins),A={isEnabled:!0,isVisible:!1,isDestroyed:!1,isMounted:!1,isShown:!1},y={id:v,reference:r,popper:ds(),popperInstance:E,props:e,state:A,plugins:T,clearDelayTimeouts:kr,setProps:Cr,setContent:Dr,show:wy,hide:Sy,hideWithInteractivity:Ly,enable:ws,disable:Ir,unmount:Ry,destroy:_y};if(!e.render)return y;var b=e.render(y),S=b.popper,R=b.onUpdate;S.setAttribute("data-tippy-root",""),S.id="tippy-"+y.id,y.popper=S,r._tippy=y,S._tippy=y;var D=T.map(function(O){return O.fn(y)}),_=r.hasAttribute("aria-expanded");return Ue(),H(),U(),M("onCreate",[y]),e.showOnCreate&&As(),S.addEventListener("mouseenter",function(){y.props.interactive&&y.state.isVisible&&y.clearDelayTimeouts()}),S.addEventListener("mouseleave",function(){y.props.interactive&&y.props.trigger.indexOf("mouseenter")>=0&&K().addEventListener("mousemove",p)}),y;function I(){var O=y.props.touch;return Array.isArray(O)?O:[O,0]}function N(){return I()[0]==="hold"}function P(){var O;return!!((O=y.props.render)!=null&&O.$$tippy)}function F(){return g||r}function K(){var O=F().parentNode;return O?pp(O):document}function w(){return Pn(S)}function C(O){return y.state.isMounted&&!y.state.isVisible||pe.isTouch||d&&d.type==="focus"?0:In(y.props.delay,O?0:1,re.delay)}function U(O){O===void 0&&(O=!1),S.style.pointerEvents=y.props.interactive&&!O?"":"none",S.style.zIndex=""+y.props.zIndex}function M(O,V,X){if(X===void 0&&(X=!0),D.forEach(function(st){st[O]&&st[O].apply(st,V)}),X){var nt;(nt=y.props)[O].apply(nt,V)}}function B(){var O=y.props.aria;if(O.content){var V="aria-"+O.content,X=S.id,nt=Ti(y.props.triggerTarget||r);nt.forEach(function(st){var Ut=st.getAttribute(V);if(y.state.isVisible)st.setAttribute(V,Ut?Ut+" "+X:X);else{var se=Ut&&Ut.replace(X,"").trim();se?st.setAttribute(V,se):st.removeAttribute(V)}})}}function H(){if(!(_||!y.props.aria.expanded)){var O=Ti(y.props.triggerTarget||r);O.forEach(function(V){y.props.interactive?V.setAttribute("aria-expanded",y.state.isVisible&&V===F()?"true":"false"):V.removeAttribute("aria-expanded")})}}function z(){K().removeEventListener("mousemove",p),ir=ir.filter(function(O){return O!==p})}function Z(O){if(!(pe.isTouch&&(l||O.type==="mousedown"))){var V=O.composedPath&&O.composedPath()[0]||O.target;if(!(y.props.interactive&&Fl(S,V))){if(Ti(y.props.triggerTarget||r).some(function(X){return Fl(X,V)})){if(pe.isTouch||y.state.isVisible&&y.props.trigger.indexOf("click")>=0)return}else M("onClickOutside",[y,O]);y.props.hideOnClick===!0&&(y.clearDelayTimeouts(),y.hide(),o=!0,setTimeout(function(){o=!1}),y.state.isMounted||xt())}}}function Q(){l=!0}function it(){l=!1}function tt(){var O=K();O.addEventListener("mousedown",Z,!0),O.addEventListener("touchend",Z,Je),O.addEventListener("touchstart",it,Je),O.addEventListener("touchmove",Q,Je)}function xt(){var O=K();O.removeEventListener("mousedown",Z,!0),O.removeEventListener("touchend",Z,Je),O.removeEventListener("touchstart",it,Je),O.removeEventListener("touchmove",Q,Je)}function St(O,V){Te(O,function(){!y.state.isVisible&&S.parentNode&&S.parentNode.contains(S)&&V()})}function yt(O,V){Te(O,V)}function Te(O,V){var X=w().box;function nt(st){st.target===X&&(Dn(X,"remove",nt),V())}if(O===0)return V();Dn(X,"remove",c),Dn(X,"add",nt),c=nt}function Et(O,V,X){X===void 0&&(X=!1);var nt=Ti(y.props.triggerTarget||r);nt.forEach(function(st){st.addEventListener(O,V,X),f.push({node:st,eventType:O,handler:V,options:X})})}function Ue(){N()&&(Et("touchstart",Be,{passive:!0}),Et("touchend",Tt,{passive:!0})),op(y.props.trigger).forEach(function(O){if(O!=="manual")switch(Et(O,Be),O){case"mouseenter":Et("mouseleave",Tt);break;case"focus":Et(Tp?"focusout":"blur",mt);break;case"focusin":Et("focusout",mt);break}})}function Di(){f.forEach(function(O){var V=O.node,X=O.eventType,nt=O.handler,st=O.options;V.removeEventListener(X,nt,st)}),f=[]}function Be(O){var V,X=!1;if(!(!y.state.isEnabled||Wt(O)||o)){var nt=((V=d)==null?void 0:V.type)==="focus";d=O,g=O.currentTarget,H(),!y.state.isVisible&&cp(O)&&ir.forEach(function(st){return st(O)}),O.type==="click"&&(y.props.trigger.indexOf("mouseenter")<0||a)&&y.props.hideOnClick!==!1&&y.state.isVisible?X=!0:As(O),O.type==="click"&&(a=!X),X&&!nt&&li(O)}}function oi(O){var V=O.target,X=F().contains(V)||S.contains(V);if(!(O.type==="mousemove"&&X)){var nt=Yt().concat(S).map(function(st){var Ut,se=st._tippy,xi=(Ut=se.popperInstance)==null?void 0:Ut.state;return xi?{popperRect:st.getBoundingClientRect(),popperState:xi,props:e}:null}).filter(Boolean);gp(nt,O)&&(z(),li(O))}}function Tt(O){var V=Wt(O)||y.props.trigger.indexOf("click")>=0&&a;if(!V){if(y.props.interactive){y.hideWithInteractivity(O);return}li(O)}}function mt(O){y.props.trigger.indexOf("focusin")<0&&O.target!==F()||y.props.interactive&&O.relatedTarget&&S.contains(O.relatedTarget)||li(O)}function Wt(O){return pe.isTouch?N()!==O.type.indexOf("touch")>=0:!1}function ft(){bt();var O=y.props,V=O.popperOptions,X=O.placement,nt=O.offset,st=O.getReferenceClientRect,Ut=O.moveTransition,se=P()?Pn(S).arrow:null,xi=st?{getBoundingClientRect:st,contextElement:st.contextElement||F()}:r,Zd={name:"$$tippy",enabled:!0,phase:"beforeWrite",requires:["computeStyles"],fn:function(xr){var Pi=xr.state;if(P()){var Iy=w(),Va=Iy.box;["placement","reference-hidden","escaped"].forEach(function(Pr){Pr==="placement"?Va.setAttribute("data-placement",Pi.placement):Pi.attributes.popper["data-popper-"+Pr]?Va.setAttribute("data-"+Pr,""):Va.removeAttribute("data-"+Pr)}),Pi.attributes.popper={}}}},hi=[{name:"offset",options:{offset:nt}},{name:"preventOverflow",options:{padding:{top:2,bottom:2,left:5,right:5}}},{name:"flip",options:{padding:5}},{name:"computeStyles",options:{adaptive:!Ut}},Zd];P()&&se&&hi.push({name:"arrow",options:{element:se,padding:3}}),hi.push.apply(hi,(V==null?void 0:V.modifiers)||[]),y.popperInstance=rp(xi,S,Object.assign({},V,{placement:X,onFirstUpdate:u,modifiers:hi}))}function bt(){y.popperInstance&&(y.popperInstance.destroy(),y.popperInstance=null)}function Pt(){var O=y.props.appendTo,V,X=F();y.props.interactive&&O===Dl||O==="parent"?V=X.parentNode:V=xl(O,[X]),V.contains(S)||V.appendChild(S),y.state.isMounted=!0,ft()}function Yt(){return tr(S.querySelectorAll("[data-tippy-root]"))}function As(O){y.clearDelayTimeouts(),O&&M("onTrigger",[y,O]),tt();var V=C(!0),X=I(),nt=X[0],st=X[1];pe.isTouch&&nt==="hold"&&st&&(V=st),V?i=setTimeout(function(){y.show()},V):y.show()}function li(O){if(y.clearDelayTimeouts(),M("onUntrigger",[y,O]),!y.state.isVisible){xt();return}if(!(y.props.trigger.indexOf("mouseenter")>=0&&y.props.trigger.indexOf("click")>=0&&["mouseleave","mousemove"].indexOf(O.type)>=0&&a)){var V=C(!1);V?s=setTimeout(function(){y.state.isVisible&&y.hide()},V):n=requestAnimationFrame(function(){y.hide()})}}function ws(){y.state.isEnabled=!0}function Ir(){y.hide(),y.state.isEnabled=!1}function kr(){clearTimeout(i),clearTimeout(s),cancelAnimationFrame(n)}function Cr(O){if(!y.state.isDestroyed){M("onBeforeUpdate",[y,O]),Di();var V=y.props,X=Hl(r,Object.assign({},V,Ml(O),{ignoreAttributes:!0}));y.props=X,Ue(),V.interactiveDebounce!==X.interactiveDebounce&&(z(),p=Pl(oi,X.interactiveDebounce)),V.triggerTarget&&!X.triggerTarget?Ti(V.triggerTarget).forEach(function(nt){nt.removeAttribute("aria-expanded")}):X.triggerTarget&&r.removeAttribute("aria-expanded"),H(),U(),R&&R(V,X),y.popperInstance&&(ft(),Yt().forEach(function(nt){requestAnimationFrame(nt._tippy.popperInstance.forceUpdate)})),M("onAfterUpdate",[y,O])}}function Dr(O){y.setProps({content:O})}function wy(){var O=y.state.isVisible,V=y.state.isDestroyed,X=!y.state.isEnabled,nt=pe.isTouch&&!y.props.touch,st=In(y.props.duration,0,re.duration);if(!(O||V||X||nt)&&!F().hasAttribute("disabled")&&(M("onShow",[y],!1),y.props.onShow(y)!==!1)){if(y.state.isVisible=!0,P()&&(S.style.visibility="visible"),U(),tt(),y.state.isMounted||(S.style.transition="none"),P()){var Ut=w(),se=Ut.box,xi=Ut.content;Cn([se,xi],0)}u=function(){var hi;if(!(!y.state.isVisible||h)){if(h=!0,S.offsetHeight,S.style.transition=y.props.moveTransition,P()&&y.props.animation){var Ga=w(),xr=Ga.box,Pi=Ga.content;Cn([xr,Pi],st),$l([xr,Pi],"visible")}B(),H(),Ol(On,y),(hi=y.popperInstance)==null||hi.forceUpdate(),M("onMount",[y]),y.props.animation&&P()&&yt(st,function(){y.state.isShown=!0,M("onShown",[y])})}},Pt()}}function Sy(){var O=!y.state.isVisible,V=y.state.isDestroyed,X=!y.state.isEnabled,nt=In(y.props.duration,1,re.duration);if(!(O||V||X)&&(M("onHide",[y],!1),y.props.onHide(y)!==!1)){if(y.state.isVisible=!1,y.state.isShown=!1,h=!1,a=!1,P()&&(S.style.visibility="hidden"),z(),xt(),U(!0),P()){var st=w(),Ut=st.box,se=st.content;y.props.animation&&(Cn([Ut,se],nt),$l([Ut,se],"hidden"))}B(),H(),y.props.animation?P()&&St(nt,y.unmount):y.unmount()}}function Ly(O){K().addEventListener("mousemove",p),Ol(ir,p),p(O)}function Ry(){y.state.isVisible&&y.hide(),y.state.isMounted&&(bt(),Yt().forEach(function(O){O._tippy.unmount()}),S.parentNode&&S.parentNode.removeChild(S),On=On.filter(function(O){return O!==y}),y.state.isMounted=!1,M("onHidden",[y]))}function _y(){y.state.isDestroyed||(y.clearDelayTimeouts(),y.unmount(),Di(),delete r._tippy,y.state.isDestroyed=!0,M("onDestroy",[y]))}}function ti(r,t){t===void 0&&(t={});var e=re.plugins.concat(t.plugins||[]);yp();var i=Object.assign({},t,{plugins:e}),s=fp(r),n=s.reduce(function(a,o){var l=o&&Ip(o,i);return l&&a.push(l),a},[]);return er(r)?n[0]:n}ti.defaultProps=re,ti.setDefaultProps=Sp,ti.currentInput=pe,Object.assign({},ul,{effect:function(t){var e=t.state,i={popper:{position:e.options.strategy,left:"0",top:"0",margin:"0"},arrow:{position:"absolute"},reference:{}};Object.assign(e.elements.popper.style,i.popper),e.styles=i,e.elements.arrow&&Object.assign(e.elements.arrow.style,i.arrow)}}),ti.setDefaultProps({render:Kl});const kp=5;class Cp{constructor(t){this._caption="",this._currentTime=0,this._activeScenes=[],this._upcomingScenes=[],this._fakeBufferSegments=[],this._canvas=de(),this._controls=de(),this.host=t}set activeScenes(t){if(t!==this._activeScenes){const e=t[0],i=this._activeScenes[0];this._activeScenes=t,e!==i&&(this.host.dispatchEvent(new CustomEvent("scenechange",{detail:t[0]})),this.host.requestUpdate())}}get activeScenes(){return this._activeScenes}set currentTime(t){var e,i,s,n,a;const o=Math.min(this.host.duration,Math.max(0,t));this._currentTime=o,this.activeScenes=((e=this.host.scenes)==null?void 0:e.filter(({start:d,duration:c})=>o>=d&&o<=d+c))??[],this._upcomingScenes=((i=this.host.scenes)==null?void 0:i.filter(({start:d})=>o>=d-kp&&o<d))??[],this.loadScenes(),this.syncVideoState(),(s=this._controls.value)==null||s.setAttribute("currentTime",o.toString());const l=this.activeScenes[0],h=zo((n=l==null?void 0:l.videoMeta)==null?void 0:n.captions);this.caption=((a=h.find(({start:d,end:c})=>{var u;const f=o-l.start+(((u=l.videoMeta)==null?void 0:u.start)??0);return d&&c&&f>=Gs(d)&&f<=Gs(c)}))==null?void 0:a.text)??"",this.draw(o),!this.host.paused&&!this.host.loading&&!this.host.processing&&!this.host.waiting&&!this.host.stalled&&this.host.dispatchEvent(new CustomEvent("timeupdate",{detail:o}))}get currentTime(){return this._currentTime}set fakeBufferSegments(t){t!==this._fakeBufferSegments&&(this._fakeBufferSegments=t,this.host.requestUpdate())}get fakeBufferSegments(){return this._fakeBufferSegments}set caption(t){t!==this._caption&&(this._caption=t,this.host.requestUpdate())}get caption(){return this._caption}canvas(){return ce(this._canvas)}controls(){return ce(this._controls)}loadScenes(){var t;let e=this.fakeBufferSegments;(t=this.host.scenes)==null||t.forEach(i=>{var s,n;const{start:a,duration:o,video:l,videoMeta:h}=i,d=this.activeScenes.includes(i),c=(this._upcomingScenes.includes(i)||d)&&(this.host.currentTime>0||this.host.preload==="auto"||!this.host.paused);if(l&&h){const{id:u,hls:f,node:p}=l,{start:g,duration:v}=h,E=this.host.videoState[u];p&&E&&(p.currentTime>=g+v||p.ended||c&&(f?(s=f.startLoadOnce)==null||s.call(f,p.currentTime):E.initialised||(n=p.startLoadOnce)==null||n.call(p)))}else if(c){const u={start:Math.max(0,a/this.host.duration*100),end:Math.min((a+o)/this.host.duration*100,100)};this.fakeBufferSegments.find(({start:f})=>f===u.start)||(e=[...e,u])}}),this.fakeBufferSegments=e}syncVideoState(){var t;(t=this.host.scenes)==null||t.forEach(e=>{if(e.video){const{id:i,node:s}=e.video,n=this.host.videoState[i],a=this.activeScenes.includes(e);if(s&&n)if(a&&!this.host.waiting&&!this.host.loading&&!this.host.paused){if(s.paused&&n.initialised)return s.play()}else s.paused||s.pause()}})}draw(t=this.currentTime){var e,i;this.host.sceneConfig&&this._canvas.value&&((i=(e=this.host).compilation)==null||i.call(e,{currentTime:t,scenes:this.host.sceneConfig,canvas:this._canvas.value}))}clear(){var t;const e=this._canvas.value;(t=e==null?void 0:e.getContext("2d"))==null||t.clearRect(0,0,e.width,e.height)}}function Dp(r){return r&&r.__esModule&&Object.prototype.hasOwnProperty.call(r,"default")?r.default:r}var jl={exports:{}};(function(r,t){(function(e){var i=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,s=/^(?=([^\/?#]*))\1([^]*)$/,n=/(?:\/|^)\.(?=\/)/g,a=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,o={buildAbsoluteURL:function(l,h,d){if(d=d||{},l=l.trim(),h=h.trim(),!h){if(!d.alwaysNormalize)return l;var c=o.parseURL(l);if(!c)throw new Error("Error trying to parse base URL.");return c.path=o.normalizePath(c.path),o.buildURLFromParts(c)}var u=o.parseURL(h);if(!u)throw new Error("Error trying to parse relative URL.");if(u.scheme)return d.alwaysNormalize?(u.path=o.normalizePath(u.path),o.buildURLFromParts(u)):h;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 p=s.exec(f.path);f.netLoc=p[1],f.path=p[2]}f.netLoc&&!f.path&&(f.path="/");var g={scheme:f.scheme,netLoc:u.netLoc,path:null,params:u.params,query:u.query,fragment:u.fragment};if(!u.netLoc&&(g.netLoc=f.netLoc,u.path[0]!=="/"))if(!u.path)g.path=f.path,u.params||(g.params=f.params,u.query||(g.query=f.query));else{var v=f.path,E=v.substring(0,v.lastIndexOf("/")+1)+u.path;g.path=o.normalizePath(E)}return g.path===null&&(g.path=d.alwaysNormalize?o.normalizePath(u.path):u.path),o.buildURLFromParts(g)},parseURL:function(l){var h=i.exec(l);return h?{scheme:h[1]||"",netLoc:h[2]||"",path:h[3]||"",params:h[4]||"",query:h[5]||"",fragment:h[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}};r.exports=o})()})(jl);var Mn=jl.exports;function Wl(r,t){var e=Object.keys(r);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(r);t&&(i=i.filter(function(s){return Object.getOwnPropertyDescriptor(r,s).enumerable})),e.push.apply(e,i)}return e}function Gt(r){for(var t=1;t<arguments.length;t++){var e=arguments[t]!=null?arguments[t]:{};t%2?Wl(Object(e),!0).forEach(function(i){xp(r,i,e[i])}):Object.getOwnPropertyDescriptors?Object.defineProperties(r,Object.getOwnPropertyDescriptors(e)):Wl(Object(e)).forEach(function(i){Object.defineProperty(r,i,Object.getOwnPropertyDescriptor(e,i))})}return r}function xp(r,t,e){return t=Op(t),t in r?Object.defineProperty(r,t,{value:e,enumerable:!0,configurable:!0,writable:!0}):r[t]=e,r}function At(){return At=Object.assign?Object.assign.bind():function(r){for(var t=1;t<arguments.length;t++){var e=arguments[t];for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&(r[i]=e[i])}return r},At.apply(this,arguments)}function Pp(r,t){if(typeof r!="object"||r===null)return r;var e=r[Symbol.toPrimitive];if(e!==void 0){var i=e.call(r,t||"default");if(typeof i!="object")return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(r)}function Op(r){var t=Pp(r,"string");return typeof t=="symbol"?t:String(t)}const j=Number.isFinite||function(r){return typeof r=="number"&&isFinite(r)};let m=function(r){return r.MEDIA_ATTACHING="hlsMediaAttaching",r.MEDIA_ATTACHED="hlsMediaAttached",r.MEDIA_DETACHING="hlsMediaDetaching",r.MEDIA_DETACHED="hlsMediaDetached",r.BUFFER_RESET="hlsBufferReset",r.BUFFER_CODECS="hlsBufferCodecs",r.BUFFER_CREATED="hlsBufferCreated",r.BUFFER_APPENDING="hlsBufferAppending",r.BUFFER_APPENDED="hlsBufferAppended",r.BUFFER_EOS="hlsBufferEos",r.BUFFER_FLUSHING="hlsBufferFlushing",r.BUFFER_FLUSHED="hlsBufferFlushed",r.MANIFEST_LOADING="hlsManifestLoading",r.MANIFEST_LOADED="hlsManifestLoaded",r.MANIFEST_PARSED="hlsManifestParsed",r.LEVEL_SWITCHING="hlsLevelSwitching",r.LEVEL_SWITCHED="hlsLevelSwitched",r.LEVEL_LOADING="hlsLevelLoading",r.LEVEL_LOADED="hlsLevelLoaded",r.LEVEL_UPDATED="hlsLevelUpdated",r.LEVEL_PTS_UPDATED="hlsLevelPtsUpdated",r.LEVELS_UPDATED="hlsLevelsUpdated",r.AUDIO_TRACKS_UPDATED="hlsAudioTracksUpdated",r.AUDIO_TRACK_SWITCHING="hlsAudioTrackSwitching",r.AUDIO_TRACK_SWITCHED="hlsAudioTrackSwitched",r.AUDIO_TRACK_LOADING="hlsAudioTrackLoading",r.AUDIO_TRACK_LOADED="hlsAudioTrackLoaded",r.SUBTITLE_TRACKS_UPDATED="hlsSubtitleTracksUpdated",r.SUBTITLE_TRACKS_CLEARED="hlsSubtitleTracksCleared",r.SUBTITLE_TRACK_SWITCH="hlsSubtitleTrackSwitch",r.SUBTITLE_TRACK_LOADING="hlsSubtitleTrackLoading",r.SUBTITLE_TRACK_LOADED="hlsSubtitleTrackLoaded",r.SUBTITLE_FRAG_PROCESSED="hlsSubtitleFragProcessed",r.CUES_PARSED="hlsCuesParsed",r.NON_NATIVE_TEXT_TRACKS_FOUND="hlsNonNativeTextTracksFound",r.INIT_PTS_FOUND="hlsInitPtsFound",r.FRAG_LOADING="hlsFragLoading",r.FRAG_LOAD_EMERGENCY_ABORTED="hlsFragLoadEmergencyAborted",r.FRAG_LOADED="hlsFragLoaded",r.FRAG_DECRYPTED="hlsFragDecrypted",r.FRAG_PARSING_INIT_SEGMENT="hlsFragParsingInitSegment",r.FRAG_PARSING_USERDATA="hlsFragParsingUserdata",r.FRAG_PARSING_METADATA="hlsFragParsingMetadata",r.FRAG_PARSED="hlsFragParsed",r.FRAG_BUFFERED="hlsFragBuffered",r.FRAG_CHANGED="hlsFragChanged",r.FPS_DROP="hlsFpsDrop",r.FPS_DROP_LEVEL_CAPPING="hlsFpsDropLevelCapping",r.ERROR="hlsError",r.DESTROYING="hlsDestroying",r.KEY_LOADING="hlsKeyLoading",r.KEY_LOADED="hlsKeyLoaded",r.LIVE_BACK_BUFFER_REACHED="hlsLiveBackBufferReached",r.BACK_BUFFER_REACHED="hlsBackBufferReached",r}({}),W=function(r){return r.NETWORK_ERROR="networkError",r.MEDIA_ERROR="mediaError",r.KEY_SYSTEM_ERROR="keySystemError",r.MUX_ERROR="muxError",r.OTHER_ERROR="otherError",r}({}),x=function(r){return r.KEY_SYSTEM_NO_KEYS="keySystemNoKeys",r.KEY_SYSTEM_NO_ACCESS="keySystemNoAccess",r.KEY_SYSTEM_NO_SESSION="keySystemNoSession",r.KEY_SYSTEM_NO_CONFIGURED_LICENSE="keySystemNoConfiguredLicense",r.KEY_SYSTEM_LICENSE_REQUEST_FAILED="keySystemLicenseRequestFailed",r.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED="keySystemServerCertificateRequestFailed",r.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED="keySystemServerCertificateUpdateFailed",r.KEY_SYSTEM_SESSION_UPDATE_FAILED="keySystemSessionUpdateFailed",r.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED="keySystemStatusOutputRestricted",r.KEY_SYSTEM_STATUS_INTERNAL_ERROR="keySystemStatusInternalError",r.MANIFEST_LOAD_ERROR="manifestLoadError",r.MANIFEST_LOAD_TIMEOUT="manifestLoadTimeOut",r.MANIFEST_PARSING_ERROR="manifestParsingError",r.MANIFEST_INCOMPATIBLE_CODECS_ERROR="manifestIncompatibleCodecsError",r.LEVEL_EMPTY_ERROR="levelEmptyError",r.LEVEL_LOAD_ERROR="levelLoadError",r.LEVEL_LOAD_TIMEOUT="levelLoadTimeOut",r.LEVEL_PARSING_ERROR="levelParsingError",r.LEVEL_SWITCH_ERROR="levelSwitchError",r.AUDIO_TRACK_LOAD_ERROR="audioTrackLoadError",r.AUDIO_TRACK_LOAD_TIMEOUT="audioTrackLoadTimeOut",r.SUBTITLE_LOAD_ERROR="subtitleTrackLoadError",r.SUBTITLE_TRACK_LOAD_TIMEOUT="subtitleTrackLoadTimeOut",r.FRAG_LOAD_ERROR="fragLoadError",r.FRAG_LOAD_TIMEOUT="fragLoadTimeOut",r.FRAG_DECRYPT_ERROR="fragDecryptError",r.FRAG_PARSING_ERROR="fragParsingError",r.FRAG_GAP="fragGap",r.REMUX_ALLOC_ERROR="remuxAllocError",r.KEY_LOAD_ERROR="keyLoadError",r.KEY_LOAD_TIMEOUT="keyLoadTimeOut",r.BUFFER_ADD_CODEC_ERROR="bufferAddCodecError",r.BUFFER_INCOMPATIBLE_CODECS_ERROR="bufferIncompatibleCodecsError",r.BUFFER_APPEND_ERROR="bufferAppendError",r.BUFFER_APPENDING_ERROR="bufferAppendingError",r.BUFFER_STALLED_ERROR="bufferStalledError",r.BUFFER_FULL_ERROR="bufferFullError",r.BUFFER_SEEK_OVER_HOLE="bufferSeekOverHole",r.BUFFER_NUDGE_ON_STALL="bufferNudgeOnStall",r.INTERNAL_EXCEPTION="internalException",r.INTERNAL_ABORTED="aborted",r.UNKNOWN="unknown",r}({});const ei=function(){},$n={trace:ei,debug:ei,log:ei,warn:ei,info:ei,error:ei};let cs=$n;function Mp(r){const t=self.console[r];return t?t.bind(self.console,`[${r}] >`):ei}function $p(r,...t){t.forEach(function(e){cs[e]=r[e]?r[e].bind(r):Mp(e)})}function Fp(r,t){if(self.console&&r===!0||typeof r=="object"){$p(r,"debug","log","info","warn","error");try{cs.log(`Debug logs enabled for "${t}" in hls.js version 1.4.12`)}catch{cs=$n}}else cs=$n}const L=cs,Np=/^(\d+)x(\d+)$/,Yl=/(.+?)=(".*?"|.*?)(?:,|$)/g;class dt{constructor(t){typeof t=="string"&&(t=dt.parseAttrList(t));for(const e in t)t.hasOwnProperty(e)&&(e.substring(0,2)==="X-"&&(this.clientAttrs=this.clientAttrs||[],this.clientAttrs.push(e)),this[e]=t[e])}decimalInteger(t){const e=parseInt(this[t],10);return e>Number.MAX_SAFE_INTEGER?1/0:e}hexadecimalInteger(t){if(this[t]){let e=(this[t]||"0x").slice(2);e=(e.length&1?"0":"")+e;const i=new Uint8Array(e.length/2);for(let s=0;s<e.length/2;s++)i[s]=parseInt(e.slice(s*2,s*2+2),16);return i}else return null}hexadecimalIntegerAsNumber(t){const e=parseInt(this[t],16);return e>Number.MAX_SAFE_INTEGER?1/0:e}decimalFloatingPoint(t){return parseFloat(this[t])}optionalFloat(t,e){const i=this[t];return i?parseFloat(i):e}enumeratedString(t){return this[t]}bool(t){return this[t]==="YES"}decimalResolution(t){const e=Np.exec(this[t]);if(e!==null)return{width:parseInt(e[1],10),height:parseInt(e[2],10)}}static parseAttrList(t){let e;const i={},s='"';for(Yl.lastIndex=0;(e=Yl.exec(t))!==null;){let n=e[2];n.indexOf(s)===0&&n.lastIndexOf(s)===n.length-1&&(n=n.slice(1,-1));const a=e[1].trim();i[a]=n}return i}}function Up(r){return r!=="ID"&&r!=="CLASS"&&r!=="START-DATE"&&r!=="DURATION"&&r!=="END-DATE"&&r!=="END-ON-NEXT"}function Bp(r){return r==="SCTE35-OUT"||r==="SCTE35-IN"}class zl{constructor(t,e){if(this.attr=void 0,this._startDate=void 0,this._endDate=void 0,this._badValueForSameId=void 0,e){const i=e.attr;for(const s in i)if(Object.prototype.hasOwnProperty.call(t,s)&&t[s]!==i[s]){L.warn(`DATERANGE tag attribute: "${s}" does not match for tags with ID: "${t.ID}"`),this._badValueForSameId=s;break}t=At(new dt({}),i,t)}if(this.attr=t,this._startDate=new Date(t["START-DATE"]),"END-DATE"in this.attr){const i=new Date(this.attr["END-DATE"]);j(i.getTime())&&(this._endDate=i)}}get id(){return this.attr.ID}get class(){return this.attr.CLASS}get startDate(){return this._startDate}get endDate(){if(this._endDate)return this._endDate;const t=this.duration;return t!==null?new Date(this._startDate.getTime()+t*1e3):null}get duration(){if("DURATION"in this.attr){const t=this.attr.decimalFloatingPoint("DURATION");if(j(t))return t}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 isValid(){return!!this.id&&!this._badValueForSameId&&j(this.startDate.getTime())&&(this.duration===null||this.duration>=0)&&(!this.endOnNext||!!this.class)}}class sr{constructor(){this.aborted=!1,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}}}var at={AUDIO:"audio",VIDEO:"video",AUDIOVIDEO:"audiovideo"};class ql{constructor(t){this._byteRange=null,this._url=null,this.baseurl=void 0,this.relurl=void 0,this.elementaryStreams={[at.AUDIO]:null,[at.VIDEO]:null,[at.AUDIOVIDEO]:null},this.baseurl=t}setByteRange(t,e){const i=t.split("@",2),s=[];i.length===1?s[0]=e?e.byteRangeEndOffset:0:s[0]=parseInt(i[1]),s[1]=parseInt(i[0])+s[0],this._byteRange=s}get byteRange(){return this._byteRange?this._byteRange:[]}get byteRangeStartOffset(){return this.byteRange[0]}get byteRangeEndOffset(){return this.byteRange[1]}get url(){return!this._url&&this.baseurl&&this.relurl&&(this._url=Mn.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""}set url(t){this._url=t}}class Fn extends ql{constructor(t,e){super(e),this._decryptdata=null,this.rawProgramDateTime=null,this.programDateTime=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.deltaPTS=void 0,this.maxStartPTS=void 0,this.minEndPTS=void 0,this.stats=new sr,this.urlId=0,this.data=void 0,this.bitrateTest=!1,this.title=null,this.initSegment=null,this.endList=void 0,this.gap=void 0,this.type=t}get decryptdata(){const{levelkeys:t}=this;if(!t&&!this._decryptdata)return null;if(!this._decryptdata&&this.levelkeys&&!this.levelkeys.NONE){const e=this.levelkeys.identity;if(e)this._decryptdata=e.getDecryptData(this.sn);else{const i=Object.keys(this.levelkeys);if(i.length===1)return this._decryptdata=this.levelkeys[i[0]].getDecryptData(this.sn)}}return this._decryptdata}get end(){return this.start+this.duration}get endProgramDateTime(){if(this.programDateTime===null||!j(this.programDateTime))return null;const t=j(this.duration)?this.duration:0;return this.programDateTime+t*1e3}get encrypted(){var t;if((t=this._decryptdata)!=null&&t.encrypted)return!0;if(this.levelkeys){const e=Object.keys(this.levelkeys),i=e.length;if(i>1||i===1&&this.levelkeys[e[0]].encrypted)return!0}return!1}setKeyFormat(t){if(this.levelkeys){const e=this.levelkeys[t];e&&!this._decryptdata&&(this._decryptdata=e.getDecryptData(this.sn))}}abortRequests(){var t,e;(t=this.loader)==null||t.abort(),(e=this.keyLoader)==null||e.abort()}setElementaryStreamInfo(t,e,i,s,n,a=!1){const{elementaryStreams:o}=this,l=o[t];if(!l){o[t]={startPTS:e,endPTS:i,startDTS:s,endDTS:n,partial:a};return}l.startPTS=Math.min(l.startPTS,e),l.endPTS=Math.max(l.endPTS,i),l.startDTS=Math.min(l.startDTS,s),l.endDTS=Math.max(l.endDTS,n)}clearElementaryStreamInfo(){const{elementaryStreams:t}=this;t[at.AUDIO]=null,t[at.VIDEO]=null,t[at.AUDIOVIDEO]=null}}class Hp extends ql{constructor(t,e,i,s,n){super(i),this.fragOffset=0,this.duration=0,this.gap=!1,this.independent=!1,this.relurl=void 0,this.fragment=void 0,this.index=void 0,this.stats=new sr,this.duration=t.decimalFloatingPoint("DURATION"),this.gap=t.bool("GAP"),this.independent=t.bool("INDEPENDENT"),this.relurl=t.enumeratedString("URI"),this.fragment=e,this.index=s;const a=t.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(){const{elementaryStreams:t}=this;return!!(t.audio||t.video||t.audiovideo)}}const Gp=10;class Vp{constructor(t){this.PTSKnown=!1,this.alignedSliding=!1,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.live=!0,this.ageHeader=0,this.advancedDateTime=void 0,this.updated=!0,this.advanced=!0,this.availabilityDelay=void 0,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=!1,this.canSkipUntil=0,this.canSkipDateRanges=!1,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=!1,this.fragments=[],this.encryptedFragments=[],this.dateRanges={},this.url=t}reloaded(t){if(!t){this.advanced=!0,this.updated=!0;return}const e=this.lastPartSn-t.lastPartSn,i=this.lastPartIndex-t.lastPartIndex;this.updated=this.endSN!==t.endSN||!!i||!!e||!this.live,this.advanced=this.endSN>t.endSN||e>0||e===0&&i>0,this.updated||this.advanced?this.misses=Math.floor(t.misses*.6):this.misses=t.misses+1,this.availabilityDelay=t.availabilityDelay}get hasProgramDateTime(){return this.fragments.length?j(this.fragments[this.fragments.length-1].programDateTime):!1}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||Gp}get drift(){const t=this.driftEndTime-this.driftStartTime;return t>0?(this.driftEnd-this.driftStart)*1e3/t:1}get edge(){return this.partEnd||this.fragmentEnd}get partEnd(){var t;return(t=this.partList)!=null&&t.length?this.partList[this.partList.length-1].end:this.fragmentEnd}get fragmentEnd(){var t;return(t=this.fragments)!=null&&t.length?this.fragments[this.fragments.length-1].end:0}get age(){return this.advancedDateTime?Math.max(Date.now()-this.advancedDateTime,0)/1e3:0}get lastPartIndex(){var t;return(t=this.partList)!=null&&t.length?this.partList[this.partList.length-1].index:-1}get lastPartSn(){var t;return(t=this.partList)!=null&&t.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}}function Nn(r){return Uint8Array.from(atob(r),t=>t.charCodeAt(0))}function Kp(r){const t=Xl(r).subarray(0,16),e=new Uint8Array(16);return e.set(t,16-t.length),e}function jp(r){const t=function(e,i,s){const n=e[i];e[i]=e[s],e[s]=n};t(r,0,3),t(r,1,2),t(r,4,5),t(r,6,7)}function Wp(r){const t=r.split(":");let e=null;if(t[0]==="data"&&t.length===2){const i=t[1].split(";"),s=i[i.length-1].split(",");if(s.length===2){const n=s[0]==="base64",a=s[1];n?(i.splice(-1,1),e=Nn(a)):e=Kp(a)}}return e}function Xl(r){return Uint8Array.from(unescape(encodeURIComponent(r)),t=>t.charCodeAt(0))}var ct={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},Vt={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.streamingkeydelivery",PLAYREADY:"com.microsoft.playready",WIDEVINE:"urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed"};function Ql(r){switch(r){case Vt.FAIRPLAY:return ct.FAIRPLAY;case Vt.PLAYREADY:return ct.PLAYREADY;case Vt.WIDEVINE:return ct.WIDEVINE;case Vt.CLEARKEY:return ct.CLEARKEY}}var Zl={WIDEVINE:"edef8ba979d64acea3c827dcd51d21ed"};function Yp(r){if(r===Zl.WIDEVINE)return ct.WIDEVINE}function Jl(r){switch(r){case ct.FAIRPLAY:return Vt.FAIRPLAY;case ct.PLAYREADY:return Vt.PLAYREADY;case ct.WIDEVINE:return Vt.WIDEVINE;case ct.CLEARKEY:return Vt.CLEARKEY}}function Un(r){const{drmSystems:t,widevineLicenseUrl:e}=r,i=t?[ct.FAIRPLAY,ct.WIDEVINE,ct.PLAYREADY,ct.CLEARKEY].filter(s=>!!t[s]):[];return!i[ct.WIDEVINE]&&e&&i.push(ct.WIDEVINE),i}const th=function(){return typeof self<"u"&&self.navigator&&self.navigator.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null}();function zp(r,t,e,i){let s;switch(r){case ct.FAIRPLAY:s=["cenc","sinf"];break;case ct.WIDEVINE:case ct.PLAYREADY:s=["cenc"];break;case ct.CLEARKEY:s=["cenc","keyids"];break;default:throw new Error(`Unknown key-system: ${r}`)}return qp(s,t,e,i)}function qp(r,t,e,i){return[{initDataTypes:r,persistentState:i.persistentState||"not-allowed",distinctiveIdentifier:i.distinctiveIdentifier||"not-allowed",sessionTypes:i.sessionTypes||[i.sessionType||"temporary"],audioCapabilities:t.map(s=>({contentType:`audio/mp4; codecs="${s}"`,robustness:i.audioRobustness||"",encryptionScheme:i.audioEncryptionScheme||null})),videoCapabilities:e.map(s=>({contentType:`video/mp4; codecs="${s}"`,robustness:i.videoRobustness||"",encryptionScheme:i.videoEncryptionScheme||null}))}]}function ii(r,t,e){return Uint8Array.prototype.slice?r.slice(t,e):new Uint8Array(Array.prototype.slice.call(r,t,e))}const Bn=(r,t)=>t+10<=r.length&&r[t]===73&&r[t+1]===68&&r[t+2]===51&&r[t+3]<255&&r[t+4]<255&&r[t+6]<128&&r[t+7]<128&&r[t+8]<128&&r[t+9]<128,eh=(r,t)=>t+10<=r.length&&r[t]===51&&r[t+1]===68&&r[t+2]===73&&r[t+3]<255&&r[t+4]<255&&r[t+6]<128&&r[t+7]<128&&r[t+8]<128&&r[t+9]<128,rr=(r,t)=>{const e=t;let i=0;for(;Bn(r,t);){i+=10;const s=nr(r,t+6);i+=s,eh(r,t+10)&&(i+=10),t+=i}if(i>0)return r.subarray(e,e+i)},nr=(r,t)=>{let e=0;return e=(r[t]&127)<<21,e|=(r[t+1]&127)<<14,e|=(r[t+2]&127)<<7,e|=r[t+3]&127,e},Xp=(r,t)=>Bn(r,t)&&nr(r,t+6)+10<=r.length-t,Qp=r=>{const t=sh(r);for(let e=0;e<t.length;e++){const i=t[e];if(ih(i))return sg(i)}},ih=r=>r&&r.key==="PRIV"&&r.info==="com.apple.streaming.transportStreamTimestamp",Zp=r=>{const t=String.fromCharCode(r[0],r[1],r[2],r[3]),e=nr(r,4),i=10;return{type:t,size:e,data:r.subarray(i,i+e)}},sh=r=>{let t=0;const e=[];for(;Bn(r,t);){const i=nr(r,t+6);t+=10;const s=t+i;for(;t+8<s;){const n=Zp(r.subarray(t)),a=Jp(n);a&&e.push(a),t+=n.size+10}eh(r,t)&&(t+=10)}return e},Jp=r=>r.type==="PRIV"?tg(r):r.type[0]==="W"?ig(r):eg(r),tg=r=>{if(r.size<2)return;const t=ge(r.data,!0),e=new Uint8Array(r.data.subarray(t.length+1));return{key:r.type,info:t,data:e.buffer}},eg=r=>{if(r.size<2)return;if(r.type==="TXXX"){let e=1;const i=ge(r.data.subarray(e),!0);e+=i.length+1;const s=ge(r.data.subarray(e));return{key:r.type,info:i,data:s}}const t=ge(r.data.subarray(1));return{key:r.type,data:t}},ig=r=>{if(r.type==="WXXX"){if(r.size<2)return;let e=1;const i=ge(r.data.subarray(e),!0);e+=i.length+1;const s=ge(r.data.subarray(e));return{key:r.type,info:i,data:s}}const t=ge(r.data);return{key:r.type,data:t}},sg=r=>{if(r.data.byteLength===8){const t=new Uint8Array(r.data),e=t[3]&1;let i=(t[4]<<23)+(t[5]<<15)+(t[6]<<7)+t[7];return i/=45,e&&(i+=4772185884e-2),Math.round(i)}},ge=(r,t=!1)=>{const e=rg();if(e){const h=e.decode(r);if(t){const d=h.indexOf("\0");return d!==-1?h.substring(0,d):h}return h.replace(/\0/g,"")}const i=r.length;let s,n,a,o="",l=0;for(;l<i;){if(s=r[l++],s===0&&t)return o;if(!(s===0||s===3))switch(s>>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:o+=String.fromCharCode(s);break;case 12:case 13:n=r[l++],o+=String.fromCharCode((s&31)<<6|n&63);break;case 14:n=r[l++],a=r[l++],o+=String.fromCharCode((s&15)<<12|(n&63)<<6|(a&63)<<0);break}}return o};let Hn;function rg(){return!Hn&&typeof self.TextDecoder<"u"&&(Hn=new self.TextDecoder("utf-8")),Hn}const me={hexDump:function(r){let t="";for(let e=0;e<r.length;e++){let i=r[e].toString(16);i.length<2&&(i="0"+i),t+=i}return t}},ar=Math.pow(2,32)-1,ng=[].push,rh={video:1,audio:2,id3:3,text:4};function Ct(r){return String.fromCharCode.apply(null,r)}function nh(r,t){const e=r[t]<<8|r[t+1];return e<0?65536+e:e}function q(r,t){const e=ah(r,t);return e<0?4294967296+e:e}function ah(r,t){return r[t]<<24|r[t+1]<<16|r[t+2]<<8|r[t+3]}function Gn(r,t,e){r[t]=e>>24,r[t+1]=e>>16&255,r[t+2]=e>>8&255,r[t+3]=e&255}function et(r,t){const e=[];if(!t.length)return e;const i=r.byteLength;for(let s=0;s<i;){const n=q(r,s),a=Ct(r.subarray(s+4,s+8)),o=n>1?s+n:i;if(a===t[0])if(t.length===1)e.push(r.subarray(s+8,o));else{const l=et(r.subarray(s+8,o),t.slice(1));l.length&&ng.apply(e,l)}s=o}return e}function ag(r){const t=[],e=r[0];let i=8;const s=q(r,i);i+=4;const n=0,a=0;e===0?i+=8:i+=16,i+=2;let o=r.length+a;const l=nh(r,i);i+=2;for(let h=0;h<l;h++){let d=i;const c=q(r,d);d+=4;const u=c&2147483647;if((c&2147483648)>>>31===1)return L.warn("SIDX has hierarchical references (not supported)"),null;const f=q(r,d);d+=4,t.push({referenceSize:u,subsegmentDuration:f,info:{duration:f/s,start:o,end:o+u-1}}),o+=u,d+=4,i=d}return{earliestPresentationTime:n,timescale:s,version:e,referencesCount:l,references:t}}function oh(r){const t=[],e=et(r,["moov","trak"]);for(let i=0;i<e.length;i++){const s=e[i],n=et(s,["tkhd"])[0];if(n){let a=n[0],o=a===0?12:20;const l=q(n,o),h=et(s,["mdia","mdhd"])[0];if(h){a=h[0],o=a===0?12:20;const d=q(h,o),c=et(s,["mdia","hdlr"])[0];if(c){const u=Ct(c.subarray(8,12)),f={soun:at.AUDIO,vide:at.VIDEO}[u];if(f){const p=et(s,["mdia","minf","stbl","stsd"])[0];let g;p&&(g=Ct(p.subarray(12,16))),t[l]={timescale:d,type:f},t[f]={timescale:d,id:l,codec:g}}}}}}return et(r,["moov","mvex","trex"]).forEach(i=>{const s=q(i,4),n=t[s];n&&(n.default={duration:q(i,12),flags:q(i,20)})}),t}function og(r,t){if(!r||!t)return r;const e=t.keyId;return e&&t.isCommonEncryption&&et(r,["moov","trak"]).forEach(i=>{const s=et(i,["mdia","minf","stbl","stsd"])[0].subarray(8);let n=et(s,["enca"]);const a=n.length>0;a||(n=et(s,["encv"])),n.forEach(o=>{const l=a?o.subarray(28):o.subarray(78);et(l,["sinf"]).forEach(h=>{const d=lh(h);if(d){const c=d.subarray(8,24);c.some(u=>u!==0)||(L.log(`[eme] Patching keyId in 'enc${a?"a":"v"}>sinf>>tenc' box: ${me.hexDump(c)} -> ${me.hexDump(e)}`),d.set(e,8))}})})}),r}function lh(r){const t=et(r,["schm"])[0];if(t){const e=Ct(t.subarray(4,8));if(e==="cbcs"||e==="cenc")return et(r,["schi","tenc"])[0]}return L.error("[eme] missing 'schm' box"),null}function lg(r,t){return et(t,["moof","traf"]).reduce((e,i)=>{const s=et(i,["tfdt"])[0],n=s[0],a=et(i,["tfhd"]).reduce((o,l)=>{const h=q(l,4),d=r[h];if(d){let c=q(s,4);if(n===1){if(c===ar)return L.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"),o;c*=ar+1,c+=q(s,8)}const u=d.timescale||9e4,f=c/u;if(isFinite(f)&&(o===null||f<o))return f}return o},null);return a!==null&&isFinite(a)&&(e===null||a<e)?a:e},null)}function hg(r,t){let e=0,i=0,s=0;const n=et(r,["moof","traf"]);for(let a=0;a<n.length;a++){const o=n[a],l=et(o,["tfhd"])[0],h=q(l,4),d=t[h];if(!d)continue;const c=d.default,u=q(l,0)|(c==null?void 0:c.flags);let f=c==null?void 0:c.duration;u&8&&(u&2?f=q(l,12):f=q(l,8));const p=d.timescale||9e4,g=et(o,["trun"]);for(let v=0;v<g.length;v++){if(e=dg(g[v]),!e&&f){const E=q(g[v],4);e=f*E}d.type===at.VIDEO?i+=e/p:d.type===at.AUDIO&&(s+=e/p)}}if(i===0&&s===0){let a=0;const o=et(r,["sidx"]);for(let l=0;l<o.length;l++){const h=ag(o[l]);h!=null&&h.references&&(a+=h.references.reduce((d,c)=>d+c.info.duration||0,0))}return a}return i||s}function dg(r){const t=q(r,0);let e=8;t&1&&(e+=4),t&4&&(e+=4);let i=0;const s=q(r,4);for(let n=0;n<s;n++){if(t&256){const a=q(r,e);i+=a,e+=4}t&512&&(e+=4),t&1024&&(e+=4),t&2048&&(e+=4)}return i}function cg(r,t,e){et(t,["moof","traf"]).forEach(i=>{et(i,["tfhd"]).forEach(s=>{const n=q(s,4),a=r[n];if(!a)return;const o=a.timescale||9e4;et(i,["tfdt"]).forEach(l=>{const h=l[0];let d=q(l,4);if(h===0)d-=e*o,d=Math.max(d,0),Gn(l,4,d);else{d*=Math.pow(2,32),d+=q(l,8),d-=e*o,d=Math.max(d,0);const c=Math.floor(d/(ar+1)),u=Math.floor(d%(ar+1));Gn(l,4,c),Gn(l,8,u)}})})})}function ug(r){const t={valid:null,remainder:null},e=et(r,["moof"]);if(e){if(e.length<2)return t.remainder=r,t}else return t;const i=e[e.length-1];return t.valid=ii(r,0,i.byteOffset-8),t.remainder=ii(r,i.byteOffset-8),t}function si(r,t){const e=new Uint8Array(r.length+t.length);return e.set(r),e.set(t,r.length),e}function hh(r,t){const e=[],i=t.samples,s=t.timescale,n=t.id;let a=!1;return et(i,["moof"]).map(o=>{const l=o.byteOffset-8;et(o,["traf"]).map(h=>{const d=et(h,["tfdt"]).map(c=>{const u=c[0];let f=q(c,4);return u===1&&(f*=Math.pow(2,32),f+=q(c,8)),f/s})[0];return d!==void 0&&(r=d),et(h,["tfhd"]).map(c=>{const u=q(c,4),f=q(c,0)&16777215,p=(f&1)!==0,g=(f&2)!==0,v=(f&8)!==0;let E=0;const T=(f&16)!==0;let A=0;const y=(f&32)!==0;let b=8;u===n&&(p&&(b+=8),g&&(b+=4),v&&(E=q(c,b),b+=4),T&&(A=q(c,b),b+=4),y&&(b+=4),t.type==="video"&&(a=fg(t.codec)),et(h,["trun"]).map(S=>{const R=S[0],D=q(S,0)&16777215,_=(D&1)!==0;let I=0;const N=(D&4)!==0,P=(D&256)!==0;let F=0;const K=(D&512)!==0;let w=0;const C=(D&1024)!==0,U=(D&2048)!==0;let M=0;const B=q(S,4);let H=8;_&&(I=q(S,H),H+=4),N&&(H+=4);let z=I+l;for(let Z=0;Z<B;Z++){if(P?(F=q(S,H),H+=4):F=E,K?(w=q(S,H),H+=4):w=A,C&&(H+=4),U&&(R===0?M=q(S,H):M=ah(S,H),H+=4),t.type===at.VIDEO){let Q=0;for(;Q<w;){const it=q(i,z);if(z+=4,pg(a,i[z])){const tt=i.subarray(z,z+it);dh(tt,a?2:1,r+M/s,e)}z+=it,Q+=it+4}}r+=F/s}}))})})}),e}function fg(r){if(!r)return!1;const t=r.indexOf("."),e=t<0?r:r.substring(0,t);return e==="hvc1"||e==="hev1"||e==="dvh1"||e==="dvhe"}function pg(r,t){if(r){const e=t>>1&63;return e===39||e===40}else return(t&31)===6}function dh(r,t,e,i){const s=ch(r);let n=0;n+=t;let a=0,o=0,l=!1,h=0;for(;n<s.length;){a=0;do{if(n>=s.length)break;h=s[n++],a+=h}while(h===255);o=0;do{if(n>=s.length)break;h=s[n++],o+=h}while(h===255);const d=s.length-n;if(!l&&a===4&&n<s.length){if(l=!0,s[n++]===181){const c=nh(s,n);if(n+=2,c===49){const u=q(s,n);if(n+=4,u===1195456820){const f=s[n++];if(f===3){const p=s[n++],g=31&p,v=64&p,E=v?2+g*3:0,T=new Uint8Array(E);if(v){T[0]=p;for(let A=1;A<E;A++)T[A]=s[n++]}i.push({type:f,payloadType:a,pts:e,bytes:T})}}}}}else if(a===5&&o<d){if(l=!0,o>16){const c=[];for(let p=0;p<16;p++){const g=s[n++].toString(16);c.push(g.length==1?"0"+g:g),(p===3||p===5||p===7||p===9)&&c.push("-")}const u=o-16,f=new Uint8Array(u);for(let p=0;p<u;p++)f[p]=s[n++];i.push({payloadType:a,pts:e,uuid:c.join(""),userData:ge(f),userDataBytes:f})}}else if(o<d)n+=o;else if(o>d)break}}function ch(r){const t=r.byteLength,e=[];let i=1;for(;i<t-2;)r[i]===0&&r[i+1]===0&&r[i+2]===3?(e.push(i+2),i+=2):i++;if(e.length===0)return r;const s=t-e.length,n=new Uint8Array(s);let a=0;for(i=0;i<s;a++,i++)a===e[0]&&(a++,e.shift()),n[i]=r[a];return n}function gg(r){const t=r[0];let e="",i="",s=0,n=0,a=0,o=0,l=0,h=0;if(t===0){for(;Ct(r.subarray(h,h+1))!=="\0";)e+=Ct(r.subarray(h,h+1)),h+=1;for(e+=Ct(r.subarray(h,h+1)),h+=1;Ct(r.subarray(h,h+1))!=="\0";)i+=Ct(r.subarray(h,h+1)),h+=1;i+=Ct(r.subarray(h,h+1)),h+=1,s=q(r,12),n=q(r,16),o=q(r,20),l=q(r,24),h=28}else if(t===1){h+=4,s=q(r,h),h+=4;const c=q(r,h);h+=4;const u=q(r,h);for(h+=4,a=4294967296*c+u,Number.isSafeInteger(a)||(a=Number.MAX_SAFE_INTEGER,L.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),o=q(r,h),h+=4,l=q(r,h),h+=4;Ct(r.subarray(h,h+1))!=="\0";)e+=Ct(r.subarray(h,h+1)),h+=1;for(e+=Ct(r.subarray(h,h+1)),h+=1;Ct(r.subarray(h,h+1))!=="\0";)i+=Ct(r.subarray(h,h+1)),h+=1;i+=Ct(r.subarray(h,h+1)),h+=1}const d=r.subarray(h,r.byteLength);return{schemeIdUri:e,value:i,timeScale:s,presentationTime:a,presentationTimeDelta:n,eventDuration:o,id:l,payload:d}}function mg(r,...t){const e=t.length;let i=8,s=e;for(;s--;)i+=t[s].byteLength;const 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(r,4),s=0,i=8;s<e;s++)n.set(t[s],i),i+=t[s].byteLength;return n}function vg(r,t,e){if(r.byteLength!==16)throw new RangeError("Invalid system id");let i,s;if(t){i=1,s=new Uint8Array(t.length*16);for(let o=0;o<t.length;o++){const l=t[o];if(l.byteLength!==16)throw new RangeError("Invalid key");s.set(l,o*16)}}else i=0,s=new Uint8Array;let n;i>0?(n=new Uint8Array(4),t.length>0&&new DataView(n.buffer).setUint32(0,t.length,!1)):n=new Uint8Array;const a=new Uint8Array(4);return e&&e.byteLength>0&&new DataView(a.buffer).setUint32(0,e.byteLength,!1),mg([112,115,115,104],new Uint8Array([i,0,0,0]),r,n,s,a,e||new Uint8Array)}function yg(r){if(!(r instanceof ArrayBuffer)||r.byteLength<32)return null;const t={version:0,systemId:"",kids:null,data:null},e=new DataView(r),i=e.getUint32(0);if(r.byteLength!==i&&i>44||e.getUint32(4)!==1886614376||(t.version=e.getUint32(8)>>>24,t.version>1))return null;t.systemId=me.hexDump(new Uint8Array(r,12,16));const s=e.getUint32(28);if(t.version===0){if(i-32<s)return null;t.data=new Uint8Array(r,32,s)}else if(t.version===1){t.kids=[];for(let n=0;n<s;n++)t.kids.push(new Uint8Array(r,32+n*16,16))}return t}let or={};class us{static clearKeyUriToKeyIdMap(){or={}}constructor(t,e,i,s=[1],n=null){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=t,this.uri=e,this.keyFormat=i,this.keyFormatVersions=s,this.iv=n,this.encrypted=t?t!=="NONE":!1,this.isCommonEncryption=this.encrypted&&t!=="AES-128"}isSupported(){if(this.method){if(this.method==="AES-128"||this.method==="NONE")return!0;if(this.keyFormat==="identity")return this.method==="SAMPLE-AES";switch(this.keyFormat){case Vt.FAIRPLAY:case Vt.WIDEVINE:case Vt.PLAYREADY:case Vt.CLEARKEY:return["ISO-23001-7","SAMPLE-AES","SAMPLE-AES-CENC","SAMPLE-AES-CTR"].indexOf(this.method)!==-1}}return!1}getDecryptData(t){if(!this.encrypted||!this.uri)return null;if(this.method==="AES-128"&&this.uri&&!this.iv){typeof t!="number"&&(this.method==="AES-128"&&!this.iv&&L.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),t=0);const i=Eg(t);return new us(this.method,this.uri,"identity",this.keyFormatVersions,i)}const e=Wp(this.uri);if(e)switch(this.keyFormat){case Vt.WIDEVINE:this.pssh=e,e.length>=22&&(this.keyId=e.subarray(e.length-22,e.length-6));break;case Vt.PLAYREADY:{const i=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=vg(i,null,e);const s=new Uint16Array(e.buffer,e.byteOffset,e.byteLength/2),n=String.fromCharCode.apply(null,Array.from(s)),a=n.substring(n.indexOf("<"),n.length),o=new DOMParser().parseFromString(a,"text/xml").getElementsByTagName("KID")[0];if(o){const l=o.childNodes[0]?o.childNodes[0].nodeValue:o.getAttribute("VALUE");if(l){const h=Nn(l).subarray(0,16);jp(h),this.keyId=h}}break}default:{let i=e.subarray(0,16);if(i.length!==16){const s=new Uint8Array(16);s.set(i,16-i.length),i=s}this.keyId=i;break}}if(!this.keyId||this.keyId.byteLength!==16){let i=or[this.uri];if(!i){const s=Object.keys(or).length%Number.MAX_SAFE_INTEGER;i=new Uint8Array(16),new DataView(i.buffer,12,4).setUint32(0,s),or[this.uri]=i}this.keyId=i}return this}}function Eg(r){const t=new Uint8Array(16);for(let e=12;e<16;e++)t[e]=r>>8*(15-e)&255;return t}const uh=/\{\$([a-zA-Z0-9-_]+)\}/g;function fh(r){return uh.test(r)}function Kt(r,t,e){if(r.variableList!==null||r.hasVariableRefs)for(let i=e.length;i--;){const s=e[i],n=t[s];n&&(t[s]=Vn(r,n))}}function Vn(r,t){if(r.variableList!==null||r.hasVariableRefs){const e=r.variableList;return t.replace(uh,i=>{const s=i.substring(2,i.length-1),n=e==null?void 0:e[s];return n===void 0?(r.playlistParsingError||(r.playlistParsingError=new Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${s}"`)),i):n})}return t}function ph(r,t,e){let i=r.variableList;i||(r.variableList=i={});let s,n;if("QUERYPARAM"in t){s=t.QUERYPARAM;try{const a=new self.URL(e).searchParams;if(a.has(s))n=a.get(s);else throw new Error(`"${s}" does not match any query parameter in URI: "${e}"`)}catch(a){r.playlistParsingError||(r.playlistParsingError=new Error(`EXT-X-DEFINE QUERYPARAM: ${a.message}`))}}else s=t.NAME,n=t.VALUE;s in i?r.playlistParsingError||(r.playlistParsingError=new Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${s}"`)):i[s]=n||""}function Tg(r,t,e){const i=t.IMPORT;if(e&&i in e){let s=r.variableList;s||(r.variableList=s={}),s[i]=e[i]}else r.playlistParsingError||(r.playlistParsingError=new Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${i}"`))}function lr(){if(!(typeof self>"u"))return self.MediaSource||self.WebKitMediaSource}const bg={audio:{a3ds:!0,"ac-3":!0,"ac-4":!0,alac:!0,alaw:!0,dra1:!0,"dts+":!0,"dts-":!0,dtsc:!0,dtse:!0,dtsh:!0,"ec-3":!0,enca:!0,g719:!0,g726:!0,m4ae:!0,mha1:!0,mha2:!0,mhm1:!0,mhm2:!0,mlpa:!0,mp4a:!0,"raw ":!0,Opus:!0,opus:!0,samr:!0,sawb:!0,sawp:!0,sevc:!0,sqcp:!0,ssmv:!0,twos:!0,ulaw:!0},video:{avc1:!0,avc2:!0,avc3:!0,avc4:!0,avcp:!0,av01:!0,drac:!0,dva1:!0,dvav:!0,dvh1:!0,dvhe:!0,encv:!0,hev1:!0,hvc1:!0,mjp2:!0,mp4v:!0,mvc1:!0,mvc2:!0,mvc3:!0,mvc4:!0,resv:!0,rv60:!0,s263:!0,svc1:!0,svc2:!0,"vc-1":!0,vp08:!0,vp09:!0},text:{stpp:!0,wvtt:!0}},gh=lr();function Ag(r,t){const e=bg[t];return!!e&&e[r.slice(0,4)]===!0}function Kn(r,t){var e;return(e=gh==null?void 0:gh.isTypeSupported(`${t||"video"}/mp4;codecs="${r}"`))!=null?e:!1}const mh=/#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,vh=/#EXT-X-MEDIA:(.*)/g,wg=/^#EXT(?:INF|-X-TARGETDURATION):/m,yh=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[\S ]*)/.source,/#EXT-X-BYTERANGE:*(.+)/.source,/#EXT-X-PROGRAM-DATE-TIME:(.+)/.source,/#.*/.source].join("|"),"g"),Sg=new RegExp([/#(EXTM3U)/.source,/#EXT-X-(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)/.source,/(#)([^:]*):(.*)/.source,/(#)(.*)(?:.*)\r?\n?/.source].join("|"));class ne{static findGroup(t,e){for(let i=0;i<t.length;i++){const s=t[i];if(s.id===e)return s}}static convertAVC1ToAVCOTI(t){const e=t.split(".");if(e.length>2){let i=e.shift()+".";return i+=parseInt(e.shift()).toString(16),i+=("000"+parseInt(e.shift()).toString(16)).slice(-4),i}return t}static resolve(t,e){return Mn.buildAbsoluteURL(e,t,{alwaysNormalize:!0})}static isMediaPlaylist(t){return wg.test(t)}static parseMasterPlaylist(t,e){const i=fh(t),s={contentSteering:null,levels:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:i},n=[];mh.lastIndex=0;let a;for(;(a=mh.exec(t))!=null;)if(a[1]){var o;const h=new dt(a[1]);Kt(s,h,["CODECS","SUPPLEMENTAL-CODECS","ALLOWED-CPC","PATHWAY-ID","STABLE-VARIANT-ID","AUDIO","VIDEO","SUBTITLES","CLOSED-CAPTIONS","NAME"]);const d=Vn(s,a[2]),c={attrs:h,bitrate:h.decimalInteger("AVERAGE-BANDWIDTH")||h.decimalInteger("BANDWIDTH"),name:h.NAME,url:ne.resolve(d,e)},u=h.decimalResolution("RESOLUTION");u&&(c.width=u.width,c.height=u.height),Lg((h.CODECS||"").split(/[ ,]+/).filter(f=>f),c),c.videoCodec&&c.videoCodec.indexOf("avc1")!==-1&&(c.videoCodec=ne.convertAVC1ToAVCOTI(c.videoCodec)),(o=c.unknownCodecs)!=null&&o.length||n.push(c),s.levels.push(c)}else if(a[3]){const h=a[3],d=a[4];switch(h){case"SESSION-DATA":{const c=new dt(d);Kt(s,c,["DATA-ID","LANGUAGE","VALUE","URI"]);const u=c["DATA-ID"];u&&(s.sessionData===null&&(s.sessionData={}),s.sessionData[u]=c);break}case"SESSION-KEY":{const c=Eh(d,e,s);c.encrypted&&c.isSupported()?(s.sessionKeys===null&&(s.sessionKeys=[]),s.sessionKeys.push(c)):L.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${d}"`);break}case"DEFINE":{{const c=new dt(d);Kt(s,c,["NAME","VALUE","QUERYPARAM"]),ph(s,c,e)}break}case"CONTENT-STEERING":{const c=new dt(d);Kt(s,c,["SERVER-URI","PATHWAY-ID"]),s.contentSteering={uri:ne.resolve(c["SERVER-URI"],e),pathwayId:c["PATHWAY-ID"]||"."};break}case"START":{s.startTimeOffset=Th(d);break}}}const l=n.length>0&&n.length<s.levels.length;return s.levels=l?n:s.levels,s.levels.length===0&&(s.playlistParsingError=new Error("no levels found in manifest")),s}static parseMasterPlaylistMedia(t,e,i){let s;const n={},a=i.levels,o={AUDIO:a.map(h=>({id:h.attrs.AUDIO,audioCodec:h.audioCodec})),SUBTITLES:a.map(h=>({id:h.attrs.SUBTITLES,textCodec:h.textCodec})),"CLOSED-CAPTIONS":[]};let l=0;for(vh.lastIndex=0;(s=vh.exec(t))!==null;){const h=new dt(s[1]),d=h.TYPE;if(d){const c=o[d],u=n[d]||[];n[d]=u,Kt(i,h,["URI","GROUP-ID","LANGUAGE","ASSOC-LANGUAGE","STABLE-RENDITION-ID","NAME","INSTREAM-ID","CHARACTERISTICS","CHANNELS"]);const f={attrs:h,bitrate:0,id:l++,groupId:h["GROUP-ID"]||"",instreamId:h["INSTREAM-ID"],name:h.NAME||h.LANGUAGE||"",type:d,default:h.bool("DEFAULT"),autoselect:h.bool("AUTOSELECT"),forced:h.bool("FORCED"),lang:h.LANGUAGE,url:h.URI?ne.resolve(h.URI,e):""};if(c!=null&&c.length){const p=ne.findGroup(c,f.groupId)||c[0];bh(f,p,"audioCodec"),bh(f,p,"textCodec")}u.push(f)}}return n}static parseLevelPlaylist(t,e,i,s,n,a){const o=new Vp(e),l=o.fragments;let h=null,d=0,c=0,u=0,f=0,p=null,g=new Fn(s,e),v,E,T,A=-1,y=!1;for(yh.lastIndex=0,o.m3u8=t,o.hasVariableRefs=fh(t);(v=yh.exec(t))!==null;){y&&(y=!1,g=new Fn(s,e),g.start=u,g.sn=d,g.cc=f,g.level=i,h&&(g.initSegment=h,g.rawProgramDateTime=h.rawProgramDateTime,h.rawProgramDateTime=null));const D=v[1];if(D){g.duration=parseFloat(D);const _=(" "+v[2]).slice(1);g.title=_||null,g.tagList.push(_?["INF",D,_]:["INF",D])}else if(v[3]){if(j(g.duration)){g.start=u,T&&Sh(g,T,o),g.sn=d,g.level=i,g.cc=f,g.urlId=n,l.push(g);const _=(" "+v[3]).slice(1);g.relurl=Vn(o,_),Ah(g,p),p=g,u+=g.duration,d++,c=0,y=!0}}else if(v[4]){const _=(" "+v[4]).slice(1);p?g.setByteRange(_,p):g.setByteRange(_)}else if(v[5])g.rawProgramDateTime=(" "+v[5]).slice(1),g.tagList.push(["PROGRAM-DATE-TIME",g.rawProgramDateTime]),A===-1&&(A=l.length);else{if(v=v[0].match(Sg),!v){L.warn("No matches on slow regex match for level playlist!");continue}for(E=1;E<v.length&&!(typeof v[E]<"u");E++);const _=(" "+v[E]).slice(1),I=(" "+v[E+1]).slice(1),N=v[E+2]?(" "+v[E+2]).slice(1):"";switch(_){case"PLAYLIST-TYPE":o.type=I.toUpperCase();break;case"MEDIA-SEQUENCE":d=o.startSN=parseInt(I);break;case"SKIP":{const P=new dt(I);Kt(o,P,["RECENTLY-REMOVED-DATERANGES"]);const F=P.decimalInteger("SKIPPED-SEGMENTS");if(j(F)){o.skippedSegments=F;for(let w=F;w--;)l.unshift(null);d+=F}const K=P.enumeratedString("RECENTLY-REMOVED-DATERANGES");K&&(o.recentlyRemovedDateranges=K.split(" "));break}case"TARGETDURATION":o.targetduration=Math.max(parseInt(I),1);break;case"VERSION":o.version=parseInt(I);break;case"EXTM3U":break;case"ENDLIST":o.live=!1;break;case"#":(I||N)&&g.tagList.push(N?[I,N]:[I]);break;case"DISCONTINUITY":f++,g.tagList.push(["DIS"]);break;case"GAP":g.gap=!0,g.tagList.push([_]);break;case"BITRATE":g.tagList.push([_,I]);break;case"DATERANGE":{const P=new dt(I);Kt(o,P,["ID","CLASS","START-DATE","END-DATE","SCTE35-CMD","SCTE35-OUT","SCTE35-IN"]),Kt(o,P,P.clientAttrs);const F=new zl(P,o.dateRanges[P.ID]);F.isValid||o.skippedSegments?o.dateRanges[F.id]=F:L.warn(`Ignoring invalid DATERANGE tag: "${I}"`),g.tagList.push(["EXT-X-DATERANGE",I]);break}case"DEFINE":{{const P=new dt(I);Kt(o,P,["NAME","VALUE","IMPORT","QUERYPARAM"]),"IMPORT"in P?Tg(o,P,a):ph(o,P,e)}break}case"DISCONTINUITY-SEQUENCE":f=parseInt(I);break;case"KEY":{const P=Eh(I,e,o);if(P.isSupported()){if(P.method==="NONE"){T=void 0;break}T||(T={}),T[P.keyFormat]&&(T=At({},T)),T[P.keyFormat]=P}else L.warn(`[Keys] Ignoring invalid EXT-X-KEY tag: "${I}"`);break}case"START":o.startTimeOffset=Th(I);break;case"MAP":{const P=new dt(I);if(Kt(o,P,["BYTERANGE","URI"]),g.duration){const F=new Fn(s,e);wh(F,P,i,T),h=F,g.initSegment=h,h.rawProgramDateTime&&!g.rawProgramDateTime&&(g.rawProgramDateTime=h.rawProgramDateTime)}else wh(g,P,i,T),h=g,y=!0;break}case"SERVER-CONTROL":{const P=new dt(I);o.canBlockReload=P.bool("CAN-BLOCK-RELOAD"),o.canSkipUntil=P.optionalFloat("CAN-SKIP-UNTIL",0),o.canSkipDateRanges=o.canSkipUntil>0&&P.bool("CAN-SKIP-DATERANGES"),o.partHoldBack=P.optionalFloat("PART-HOLD-BACK",0),o.holdBack=P.optionalFloat("HOLD-BACK",0);break}case"PART-INF":{const P=new dt(I);o.partTarget=P.decimalFloatingPoint("PART-TARGET");break}case"PART":{let P=o.partList;P||(P=o.partList=[]);const F=c>0?P[P.length-1]:void 0,K=c++,w=new dt(I);Kt(o,w,["BYTERANGE","URI"]);const C=new Hp(w,g,e,K,F);P.push(C),g.duration+=C.duration;break}case"PRELOAD-HINT":{const P=new dt(I);Kt(o,P,["URI"]),o.preloadHint=P;break}case"RENDITION-REPORT":{const P=new dt(I);Kt(o,P,["URI"]),o.renditionReports=o.renditionReports||[],o.renditionReports.push(P);break}default:L.warn(`line parsed but not handled: ${v}`);break}}}p&&!p.relurl?(l.pop(),u-=p.duration,o.partList&&(o.fragmentHint=p)):o.partList&&(Ah(g,p),g.cc=f,o.fragmentHint=g,T&&Sh(g,T,o));const b=l.length,S=l[0],R=l[b-1];if(u+=o.skippedSegments*o.targetduration,u>0&&b&&R){o.averagetargetduration=u/b;const D=R.sn;o.endSN=D!=="initSegment"?D:0,o.live||(R.endList=!0),S&&(o.startCC=S.cc)}else o.endSN=0,o.startCC=0;return o.fragmentHint&&(u+=o.fragmentHint.duration),o.totalduration=u,o.endCC=f,A>0&&Rg(l,A),o}}function Eh(r,t,e){var i,s;const n=new dt(r);Kt(e,n,["KEYFORMAT","KEYFORMATVERSIONS","URI","IV","URI"]);const a=(i=n.METHOD)!=null?i:"",o=n.URI,l=n.hexadecimalInteger("IV"),h=n.KEYFORMATVERSIONS,d=(s=n.KEYFORMAT)!=null?s:"identity";o&&n.IV&&!l&&L.error(`Invalid IV: ${n.IV}`);const c=o?ne.resolve(o,t):"",u=(h||"1").split("/").map(Number).filter(Number.isFinite);return new us(a,c,d,u,l)}function Th(r){const t=new dt(r).decimalFloatingPoint("TIME-OFFSET");return j(t)?t:null}function Lg(r,t){["video","audio","text"].forEach(e=>{const i=r.filter(s=>Ag(s,e));if(i.length){const s=i.filter(n=>n.lastIndexOf("avc1",0)===0||n.lastIndexOf("mp4a",0)===0);t[`${e}Codec`]=s.length>0?s[0]:i[0],r=r.filter(n=>i.indexOf(n)===-1)}}),t.unknownCodecs=r}function bh(r,t,e){const i=t[e];i&&(r[e]=i)}function Rg(r,t){let e=r[t];for(let i=t;i--;){const s=r[i];if(!s)return;s.programDateTime=e.programDateTime-s.duration*1e3,e=s}}function Ah(r,t){r.rawProgramDateTime?r.programDateTime=Date.parse(r.rawProgramDateTime):t!=null&&t.programDateTime&&(r.programDateTime=t.endProgramDateTime),j(r.programDateTime)||(r.programDateTime=null,r.rawProgramDateTime=null)}function wh(r,t,e,i){r.relurl=t.URI,t.BYTERANGE&&r.setByteRange(t.BYTERANGE),r.level=e,r.sn="initSegment",i&&(r.levelkeys=i),r.initSegment=null}function Sh(r,t,e){r.levelkeys=t;const{encryptedFragments:i}=e;(!i.length||i[i.length-1].levelkeys!==t)&&Object.keys(t).some(s=>t[s].isCommonEncryption)&&i.push(r)}var rt={MANIFEST:"manifest",LEVEL:"level",AUDIO_TRACK:"audioTrack",SUBTITLE_TRACK:"subtitleTrack"},Y={MAIN:"main",AUDIO:"audio",SUBTITLE:"subtitle"};function Lh(r){const{type:t}=r;switch(t){case rt.AUDIO_TRACK:return Y.AUDIO;case rt.SUBTITLE_TRACK:return Y.SUBTITLE;default:return Y.MAIN}}function jn(r,t){let e=r.url;return(e===void 0||e.indexOf("data:")===0)&&(e=t.url),e}class _g{constructor(t){this.hls=void 0,this.loaders=Object.create(null),this.variableList=null,this.hls=t,this.registerListeners()}startLoad(t){}stopLoad(){this.destroyInternalLoaders()}registerListeners(){const{hls:t}=this;t.on(m.MANIFEST_LOADING,this.onManifestLoading,this),t.on(m.LEVEL_LOADING,this.onLevelLoading,this),t.on(m.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),t.on(m.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this)}unregisterListeners(){const{hls:t}=this;t.off(m.MANIFEST_LOADING,this.onManifestLoading,this),t.off(m.LEVEL_LOADING,this.onLevelLoading,this),t.off(m.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),t.off(m.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this)}createInternalLoader(t){const e=this.hls.config,i=e.pLoader,s=e.loader,n=i||s,a=new n(e);return this.loaders[t.type]=a,a}getInternalLoader(t){return this.loaders[t.type]}resetInternalLoader(t){this.loaders[t]&&delete this.loaders[t]}destroyInternalLoaders(){for(const t in this.loaders){const e=this.loaders[t];e&&e.destroy(),this.resetInternalLoader(t)}}destroy(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders()}onManifestLoading(t,e){const{url:i}=e;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:rt.MANIFEST,url:i,deliveryDirectives:null})}onLevelLoading(t,e){const{id:i,level:s,url:n,deliveryDirectives:a}=e;this.load({id:i,level:s,responseType:"text",type:rt.LEVEL,url:n,deliveryDirectives:a})}onAudioTrackLoading(t,e){const{id:i,groupId:s,url:n,deliveryDirectives:a}=e;this.load({id:i,groupId:s,level:null,responseType:"text",type:rt.AUDIO_TRACK,url:n,deliveryDirectives:a})}onSubtitleTrackLoading(t,e){const{id:i,groupId:s,url:n,deliveryDirectives:a}=e;this.load({id:i,groupId:s,level:null,responseType:"text",type:rt.SUBTITLE_TRACK,url:n,deliveryDirectives:a})}load(t){var e;const i=this.hls.config;let s=this.getInternalLoader(t);if(s){const h=s.context;if(h&&h.url===t.url){L.trace("[playlist-loader]: playlist request ongoing");return}L.log(`[playlist-loader]: aborting previous loader for type: ${t.type}`),s.abort()}let n;if(t.type===rt.MANIFEST?n=i.manifestLoadPolicy.default:n=At({},i.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),s=this.createInternalLoader(t),(e=t.deliveryDirectives)!=null&&e.part){let h;if(t.type===rt.LEVEL&&t.level!==null?h=this.hls.levels[t.level].details:t.type===rt.AUDIO_TRACK&&t.id!==null?h=this.hls.audioTracks[t.id].details:t.type===rt.SUBTITLE_TRACK&&t.id!==null&&(h=this.hls.subtitleTracks[t.id].details),h){const d=h.partTarget,c=h.targetduration;if(d&&c){const u=Math.max(d*3,c*.8)*1e3;n=At({},n,{maxTimeToFirstByteMs:Math.min(u,n.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(u,n.maxTimeToFirstByteMs)})}}}const 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:(h,d,c,u)=>{const f=this.getInternalLoader(c);this.resetInternalLoader(c.type);const p=h.data;if(p.indexOf("#EXTM3U")!==0){this.handleManifestParsingError(h,c,new Error("no EXTM3U delimiter"),u||null,d);return}d.parsing.start=performance.now(),ne.isMediaPlaylist(p)?this.handleTrackOrLevelPlaylist(h,d,c,u||null,f):this.handleMasterPlaylist(h,d,c,u)},onError:(h,d,c,u)=>{this.handleNetworkError(d,c,!1,h,u)},onTimeout:(h,d,c)=>{this.handleNetworkError(d,c,!0,void 0,h)}};s.load(t,o,l)}handleMasterPlaylist(t,e,i,s){const n=this.hls,a=t.data,o=jn(t,i),l=ne.parseMasterPlaylist(a,o);if(l.playlistParsingError){this.handleManifestParsingError(t,i,l.playlistParsingError,s,e);return}const{contentSteering:h,levels:d,sessionData:c,sessionKeys:u,startTimeOffset:f,variableList:p}=l;this.variableList=p;const{AUDIO:g=[],SUBTITLES:v,"CLOSED-CAPTIONS":E}=ne.parseMasterPlaylistMedia(a,o,l);g.length&&!g.some(T=>!T.url)&&d[0].audioCodec&&!d[0].attrs.AUDIO&&(L.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),g.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new dt({}),bitrate:0,url:""})),n.trigger(m.MANIFEST_LOADED,{levels:d,audioTracks:g,subtitles:v,captions:E,contentSteering:h,url:o,stats:e,networkDetails:s,sessionData:c,sessionKeys:u,startTimeOffset:f,variableList:p})}handleTrackOrLevelPlaylist(t,e,i,s,n){const a=this.hls,{id:o,level:l,type:h}=i,d=jn(t,i),c=j(o)?o:0,u=j(l)?l:c,f=Lh(i),p=ne.parseLevelPlaylist(t.data,d,u,f,c,this.variableList);if(h===rt.MANIFEST){const g={attrs:new dt({}),bitrate:0,details:p,name:"",url:d};a.trigger(m.MANIFEST_LOADED,{levels:[g],audioTracks:[],url:d,stats:e,networkDetails:s,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}e.parsing.end=performance.now(),i.levelDetails=p,this.handlePlaylistLoaded(p,t,e,i,s,n)}handleManifestParsingError(t,e,i,s,n){this.hls.trigger(m.ERROR,{type:W.NETWORK_ERROR,details:x.MANIFEST_PARSING_ERROR,fatal:e.type===rt.MANIFEST,url:t.url,err:i,error:i,reason:i.message,response:t,context:e,networkDetails:s,stats:n})}handleNetworkError(t,e,i=!1,s,n){let a=`A network ${i?"timeout":"error"+(s?" (status "+s.code+")":"")} occurred while loading ${t.type}`;t.type===rt.LEVEL?a+=`: ${t.level} id: ${t.id}`:(t.type===rt.AUDIO_TRACK||t.type===rt.SUBTITLE_TRACK)&&(a+=` id: ${t.id} group-id: "${t.groupId}"`);const o=new Error(a);L.warn(`[playlist-loader]: ${a}`);let l=x.UNKNOWN,h=!1;const d=this.getInternalLoader(t);switch(t.type){case rt.MANIFEST:l=i?x.MANIFEST_LOAD_TIMEOUT:x.MANIFEST_LOAD_ERROR,h=!0;break;case rt.LEVEL:l=i?x.LEVEL_LOAD_TIMEOUT:x.LEVEL_LOAD_ERROR,h=!1;break;case rt.AUDIO_TRACK:l=i?x.AUDIO_TRACK_LOAD_TIMEOUT:x.AUDIO_TRACK_LOAD_ERROR,h=!1;break;case rt.SUBTITLE_TRACK:l=i?x.SUBTITLE_TRACK_LOAD_TIMEOUT:x.SUBTITLE_LOAD_ERROR,h=!1;break}d&&this.resetInternalLoader(t.type);const c={type:W.NETWORK_ERROR,details:l,fatal:h,url:t.url,loader:d,context:t,error:o,networkDetails:e,stats:n};if(s){const u=(e==null?void 0:e.url)||t.url;c.response=Gt({url:u,data:void 0},s)}this.hls.trigger(m.ERROR,c)}handlePlaylistLoaded(t,e,i,s,n,a){const o=this.hls,{type:l,level:h,id:d,groupId:c,deliveryDirectives:u}=s,f=jn(e,s),p=Lh(s),g=typeof s.level=="number"&&p===Y.MAIN?h:void 0;if(!t.fragments.length){const E=new Error("No Segments found in Playlist");o.trigger(m.ERROR,{type:W.NETWORK_ERROR,details:x.LEVEL_EMPTY_ERROR,fatal:!1,url:f,error:E,reason:E.message,response:e,context:s,level:g,parent:p,networkDetails:n,stats:i});return}t.targetduration||(t.playlistParsingError=new Error("Missing Target Duration"));const v=t.playlistParsingError;if(v){o.trigger(m.ERROR,{type:W.NETWORK_ERROR,details:x.LEVEL_PARSING_ERROR,fatal:!1,url:f,error:v,reason:v.message,response:e,context:s,level:g,parent:p,networkDetails:n,stats:i});return}switch(t.live&&a&&(a.getCacheAge&&(t.ageHeader=a.getCacheAge()||0),(!a.getCacheAge||isNaN(t.ageHeader))&&(t.ageHeader=0)),l){case rt.MANIFEST:case rt.LEVEL:o.trigger(m.LEVEL_LOADED,{details:t,level:g||0,id:d||0,stats:i,networkDetails:n,deliveryDirectives:u});break;case rt.AUDIO_TRACK:o.trigger(m.AUDIO_TRACK_LOADED,{details:t,id:d||0,groupId:c||"",stats:i,networkDetails:n,deliveryDirectives:u});break;case rt.SUBTITLE_TRACK:o.trigger(m.SUBTITLE_TRACK_LOADED,{details:t,id:d||0,groupId:c||"",stats:i,networkDetails:n,deliveryDirectives:u});break}}}function Rh(r,t){let e;try{e=new Event("addtrack")}catch{e=document.createEvent("Event"),e.initEvent("addtrack",!1,!1)}e.track=r,t.dispatchEvent(e)}function _h(r,t){const e=r.mode;if(e==="disabled"&&(r.mode="hidden"),r.cues&&!r.cues.getCueById(t.id))try{if(r.addCue(t),!r.cues.getCueById(t.id))throw new Error(`addCue is failed for: ${t}`)}catch(i){L.debug(`[texttrack-utils]: ${i}`);try{const s=new self.TextTrackCue(t.startTime,t.endTime,t.text);s.id=t.id,r.addCue(s)}catch(s){L.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${s}`)}}e==="disabled"&&(r.mode=e)}function bi(r){const t=r.mode;if(t==="disabled"&&(r.mode="hidden"),r.cues)for(let e=r.cues.length;e--;)r.removeCue(r.cues[e]);t==="disabled"&&(r.mode=t)}function Wn(r,t,e,i){const s=r.mode;if(s==="disabled"&&(r.mode="hidden"),r.cues&&r.cues.length>0){const n=kg(r.cues,t,e);for(let a=0;a<n.length;a++)(!i||i(n[a]))&&r.removeCue(n[a])}s==="disabled"&&(r.mode=s)}function Ig(r,t){if(t<r[0].startTime)return 0;const e=r.length-1;if(t>r[e].endTime)return-1;let i=0,s=e;for(;i<=s;){const n=Math.floor((s+i)/2);if(t<r[n].startTime)s=n-1;else if(t>r[n].startTime&&i<e)i=n+1;else return n}return r[i].startTime-t<t-r[s].startTime?i:s}function kg(r,t,e){const i=[],s=Ig(r,t);if(s>-1)for(let n=s,a=r.length;n<a;n++){const o=r[n];if(o.startTime>=t&&o.endTime<=e)i.push(o);else if(o.startTime>e)return i}return i}var ae={audioId3:"org.id3",dateRange:"com.apple.quicktime.HLS",emsg:"https://aomedia.org/emsg/ID3"};const Cg=.25;function Yn(){if(!(typeof self>"u"))return self.WebKitDataCue||self.VTTCue||self.TextTrackCue}const hr=(()=>{const r=Yn();try{new r(0,Number.POSITIVE_INFINITY,"")}catch{return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();function zn(r,t){return r.getTime()/1e3-t}function Dg(r){return Uint8Array.from(r.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer}class xg{constructor(t){this.hls=void 0,this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=t,this._registerListeners()}destroy(){this._unregisterListeners(),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=null}_registerListeners(){const{hls:t}=this;t.on(m.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(m.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(m.MANIFEST_LOADING,this.onManifestLoading,this),t.on(m.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),t.on(m.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(m.LEVEL_UPDATED,this.onLevelUpdated,this)}_unregisterListeners(){const{hls:t}=this;t.off(m.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(m.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(m.MANIFEST_LOADING,this.onManifestLoading,this),t.off(m.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),t.off(m.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(m.LEVEL_UPDATED,this.onLevelUpdated,this)}onMediaAttached(t,e){this.media=e.media}onMediaDetaching(){this.id3Track&&(bi(this.id3Track),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={})}onManifestLoading(){this.dateRangeCuesAppended={}}createTrack(t){const e=this.getID3Track(t.textTracks);return e.mode="hidden",e}getID3Track(t){if(this.media){for(let e=0;e<t.length;e++){const i=t[e];if(i.kind==="metadata"&&i.label==="id3")return Rh(i,this.media),i}return this.media.addTextTrack("metadata","id3")}}onFragParsingMetadata(t,e){if(!this.media)return;const{hls:{config:{enableEmsgMetadataCues:i,enableID3MetadataCues:s}}}=this;if(!i&&!s)return;const{samples:n}=e;this.id3Track||(this.id3Track=this.createTrack(this.media));const a=Yn();for(let o=0;o<n.length;o++){const l=n[o].type;if(l===ae.emsg&&!i||!s)continue;const h=sh(n[o].data);if(h){const d=n[o].pts;let c=d+n[o].duration;c>hr&&(c=hr),c-d<=0&&(c=d+Cg);for(let u=0;u<h.length;u++){const f=h[u];if(!ih(f)){this.updateId3CueEnds(d,l);const p=new a(d,c,"");p.value=f,l&&(p.type=l),this.id3Track.addCue(p)}}}}}updateId3CueEnds(t,e){var i;const s=(i=this.id3Track)==null?void 0:i.cues;if(s)for(let n=s.length;n--;){const a=s[n];a.type===e&&a.startTime<t&&a.endTime===hr&&(a.endTime=t)}}onBufferFlushing(t,{startOffset:e,endOffset:i,type:s}){const{id3Track:n,hls:a}=this;if(!a)return;const{config:{enableEmsgMetadataCues:o,enableID3MetadataCues:l}}=a;if(n&&(o||l)){let h;s==="audio"?h=d=>d.type===ae.audioId3&&l:s==="video"?h=d=>d.type===ae.emsg&&o:h=d=>d.type===ae.audioId3&&l||d.type===ae.emsg&&o,Wn(n,e,i,h)}}onLevelUpdated(t,{details:e}){if(!this.media||!e.hasProgramDateTime||!this.hls.config.enableDateRangeMetadataCues)return;const{dateRangeCuesAppended:i,id3Track:s}=this,{dateRanges:n}=e,a=Object.keys(n);if(s){const d=Object.keys(i).filter(c=>!a.includes(c));for(let c=d.length;c--;){const u=d[c];Object.keys(i[u].cues).forEach(f=>{s.removeCue(i[u].cues[f])}),delete i[u]}}const o=e.fragments[e.fragments.length-1];if(a.length===0||!j(o==null?void 0:o.programDateTime))return;this.id3Track||(this.id3Track=this.createTrack(this.media));const l=o.programDateTime/1e3-o.start,h=Yn();for(let d=0;d<a.length;d++){const c=a[d],u=n[c],f=i[c],p=(f==null?void 0:f.cues)||{};let g=(f==null?void 0:f.durationKnown)||!1;const v=zn(u.startDate,l);let E=hr;const T=u.endDate;if(T)E=zn(T,l),g=!0;else if(u.endOnNext&&!g){const y=a.reduce((b,S)=>{const R=n[S];return R.class===u.class&&R.id!==S&&R.startDate>u.startDate&&b.push(R),b},[]).sort((b,S)=>b.startDate.getTime()-S.startDate.getTime())[0];y&&(E=zn(y.startDate,l),g=!0)}const A=Object.keys(u.attr);for(let y=0;y<A.length;y++){const b=A[y];if(!Up(b))continue;let S=p[b];if(S)g&&!f.durationKnown&&(S.endTime=E);else{let R=u.attr[b];S=new h(v,E,""),Bp(b)&&(R=Dg(R)),S.value={key:b,data:R},S.type=ae.dateRange,S.id=c,this.id3Track.addCue(S),p[b]=S}}i[c]={cues:p,dateRange:u,durationKnown:g}}}}class Pg{constructor(t){this.hls=void 0,this.config=void 0,this.media=null,this.levelDetails=null,this.currentTime=0,this.stallCount=0,this._latency=null,this.timeupdateHandler=()=>this.timeupdate(),this.hls=t,this.config=t.config,this.registerListeners()}get latency(){return this._latency||0}get maxLatency(){const{config:t,levelDetails:e}=this;return t.liveMaxLatencyDuration!==void 0?t.liveMaxLatencyDuration:e?t.liveMaxLatencyDurationCount*e.targetduration:0}get targetLatency(){const{levelDetails:t}=this;if(t===null)return null;const{holdBack:e,partHoldBack:i,targetduration:s}=t,{liveSyncDuration:n,liveSyncDurationCount:a,lowLatencyMode:o}=this.config,l=this.hls.userConfig;let h=o&&i||e;(l.liveSyncDuration||l.liveSyncDurationCount||h===0)&&(h=n!==void 0?n:a*s);const d=s,c=1;return h+Math.min(this.stallCount*c,d)}get liveSyncPosition(){const t=this.estimateLiveEdge(),e=this.targetLatency,i=this.levelDetails;if(t===null||e===null||i===null)return null;const s=i.edge,n=t-e-this.edgeStalled,a=s-i.totalduration,o=s-(this.config.lowLatencyMode&&i.partTarget||i.targetduration);return Math.min(Math.max(a,n),o)}get drift(){const{levelDetails:t}=this;return t===null?1:t.drift}get edgeStalled(){const{levelDetails:t}=this;if(t===null)return 0;const e=(this.config.lowLatencyMode&&t.partTarget||t.targetduration)*3;return Math.max(t.age-e,0)}get forwardBufferLength(){const{media:t,levelDetails:e}=this;if(!t||!e)return 0;const i=t.buffered.length;return(i?t.buffered.end(i-1):e.edge)-this.currentTime}destroy(){this.unregisterListeners(),this.onMediaDetaching(),this.levelDetails=null,this.hls=this.timeupdateHandler=null}registerListeners(){this.hls.on(m.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(m.MEDIA_DETACHING,this.onMediaDetaching,this),this.hls.on(m.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(m.LEVEL_UPDATED,this.onLevelUpdated,this),this.hls.on(m.ERROR,this.onError,this)}unregisterListeners(){this.hls.off(m.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(m.MEDIA_DETACHING,this.onMediaDetaching,this),this.hls.off(m.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(m.LEVEL_UPDATED,this.onLevelUpdated,this),this.hls.off(m.ERROR,this.onError,this)}onMediaAttached(t,e){this.media=e.media,this.media.addEventListener("timeupdate",this.timeupdateHandler)}onMediaDetaching(){this.media&&(this.media.removeEventListener("timeupdate",this.timeupdateHandler),this.media=null)}onManifestLoading(){this.levelDetails=null,this._latency=null,this.stallCount=0}onLevelUpdated(t,{details:e}){this.levelDetails=e,e.advanced&&this.timeupdate(),!e.live&&this.media&&this.media.removeEventListener("timeupdate",this.timeupdateHandler)}onError(t,e){var i;e.details===x.BUFFER_STALLED_ERROR&&(this.stallCount++,(i=this.levelDetails)!=null&&i.live&&L.warn("[playback-rate-controller]: Stall detected, adjusting target latency"))}timeupdate(){const{media:t,levelDetails:e}=this;if(!t||!e)return;this.currentTime=t.currentTime;const i=this.computeLatency();if(i===null)return;this._latency=i;const{lowLatencyMode:s,maxLiveSyncPlaybackRate:n}=this.config;if(!s||n===1)return;const a=this.targetLatency;if(a===null)return;const o=i-a,l=Math.min(this.maxLatency,a+e.targetduration),h=o<l;if(e.live&&h&&o>.05&&this.forwardBufferLength>1){const d=Math.min(2,Math.max(1,n)),c=Math.round(2/(1+Math.exp(-.75*o-this.edgeStalled))*20)/20;t.playbackRate=Math.min(d,Math.max(1,c))}else t.playbackRate!==1&&t.playbackRate!==0&&(t.playbackRate=1)}estimateLiveEdge(){const{levelDetails:t}=this;return t===null?null:t.edge+t.age}computeLatency(){const t=this.estimateLiveEdge();return t===null?null:t-this.currentTime}}const qn=["NONE","TYPE-0","TYPE-1",null];var fs={No:"",Yes:"YES",v2:"v2"};function Og(r,t){const{canSkipUntil:e,canSkipDateRanges:i,endSN:s}=r,n=t!==void 0?t-s:0;return e&&n<e?i?fs.v2:fs.Yes:fs.No}class Ih{constructor(t,e,i){this.msn=void 0,this.part=void 0,this.skip=void 0,this.msn=t,this.part=e,this.skip=i}addDirectives(t){const e=new self.URL(t);return this.msn!==void 0&&e.searchParams.set("_HLS_msn",this.msn.toString()),this.part!==void 0&&e.searchParams.set("_HLS_part",this.part.toString()),this.skip&&e.searchParams.set("_HLS_skip",this.skip),e.href}}class ps{constructor(t){this._attrs=void 0,this.audioCodec=void 0,this.bitrate=void 0,this.codecSet=void 0,this.height=void 0,this.id=void 0,this.name=void 0,this.videoCodec=void 0,this.width=void 0,this.unknownCodecs=void 0,this.audioGroupIds=void 0,this.details=void 0,this.fragmentError=0,this.loadError=0,this.loaded=void 0,this.realBitrate=0,this.textGroupIds=void 0,this.url=void 0,this._urlId=0,this.url=[t.url],this._attrs=[t.attrs],this.bitrate=t.bitrate,t.details&&(this.details=t.details),this.id=t.id||0,this.name=t.name,this.width=t.width||0,this.height=t.height||0,this.audioCodec=t.audioCodec,this.videoCodec=t.videoCodec,this.unknownCodecs=t.unknownCodecs,this.codecSet=[t.videoCodec,t.audioCodec].filter(e=>e).join(",").replace(/\.[^.,]+/g,"")}get maxBitrate(){return Math.max(this.realBitrate,this.bitrate)}get attrs(){return this._attrs[this._urlId]}get pathwayId(){return this.attrs["PATHWAY-ID"]||"."}get uri(){return this.url[this._urlId]||""}get urlId(){return this._urlId}set urlId(t){const e=t%this.url.length;this._urlId!==e&&(this.fragmentError=0,this.loadError=0,this.details=void 0,this._urlId=e)}get audioGroupId(){var t;return(t=this.audioGroupIds)==null?void 0:t[this.urlId]}get textGroupId(){var t;return(t=this.textGroupIds)==null?void 0:t[this.urlId]}addFallback(t){this.url.push(t.url),this._attrs.push(t.attrs)}}function Xn(r,t){const e=t.startPTS;if(j(e)){let i=0,s;t.sn>r.sn?(i=e-r.start,s=r):(i=r.start-e,s=t),s.duration!==i&&(s.duration=i)}else t.sn>r.sn?r.cc===t.cc&&r.minEndPTS?t.start=r.start+(r.minEndPTS-r.start):t.start=r.start+r.duration:t.start=Math.max(r.start-t.duration,0)}function kh(r,t,e,i,s,n){i-e<=0&&(L.warn("Fragment should have a positive duration",t),i=e+t.duration,n=s+t.duration);let a=e,o=i;const l=t.startPTS,h=t.endPTS;if(j(l)){const g=Math.abs(l-e);j(t.deltaPTS)?t.deltaPTS=Math.max(g,t.deltaPTS):t.deltaPTS=g,a=Math.max(e,l),e=Math.min(e,l),s=Math.min(s,t.startDTS),o=Math.min(i,h),i=Math.max(i,h),n=Math.max(n,t.endDTS)}const d=e-t.start;t.start!==0&&(t.start=e),t.duration=i-t.start,t.startPTS=e,t.maxStartPTS=a,t.startDTS=s,t.endPTS=i,t.minEndPTS=o,t.endDTS=n;const c=t.sn;if(!r||c<r.startSN||c>r.endSN)return 0;let u;const f=c-r.startSN,p=r.fragments;for(p[f]=t,u=f;u>0;u--)Xn(p[u],p[u-1]);for(u=f;u<p.length-1;u++)Xn(p[u],p[u+1]);return r.fragmentHint&&Xn(p[p.length-1],r.fragmentHint),r.PTSKnown=r.alignedSliding=!0,d}function Mg(r,t){let e=null;const i=r.fragments;for(let l=i.length-1;l>=0;l--){const h=i[l].initSegment;if(h){e=h;break}}r.fragmentHint&&delete r.fragmentHint.endPTS;let s=0,n;if(Ng(r,t,(l,h)=>{l.relurl&&(s=l.cc-h.cc),j(l.startPTS)&&j(l.endPTS)&&(h.start=h.startPTS=l.startPTS,h.startDTS=l.startDTS,h.maxStartPTS=l.maxStartPTS,h.endPTS=l.endPTS,h.endDTS=l.endDTS,h.minEndPTS=l.minEndPTS,h.duration=l.endPTS-l.startPTS,h.duration&&(n=h),t.PTSKnown=t.alignedSliding=!0),h.elementaryStreams=l.elementaryStreams,h.loader=l.loader,h.stats=l.stats,h.urlId=l.urlId,l.initSegment&&(h.initSegment=l.initSegment,e=l.initSegment)}),e&&(t.fragmentHint?t.fragments.concat(t.fragmentHint):t.fragments).forEach(l=>{var h;(!l.initSegment||l.initSegment.relurl===((h=e)==null?void 0:h.relurl))&&(l.initSegment=e)}),t.skippedSegments)if(t.deltaUpdateFailed=t.fragments.some(l=>!l),t.deltaUpdateFailed){L.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let l=t.skippedSegments;l--;)t.fragments.shift();t.startSN=t.fragments[0].sn,t.startCC=t.fragments[0].cc}else t.canSkipDateRanges&&(t.dateRanges=$g(r.dateRanges,t.dateRanges,t.recentlyRemovedDateranges));const a=t.fragments;if(s){L.warn("discontinuity sliding from playlist, take drift into account");for(let l=0;l<a.length;l++)a[l].cc+=s}t.skippedSegments&&(t.startCC=t.fragments[0].cc),Fg(r.partList,t.partList,(l,h)=>{h.elementaryStreams=l.elementaryStreams,h.stats=l.stats}),n?kh(t,n,n.startPTS,n.endPTS,n.startDTS,n.endDTS):Ch(r,t),a.length&&(t.totalduration=t.edge-a[0].start),t.driftStartTime=r.driftStartTime,t.driftStart=r.driftStart;const o=t.advancedDateTime;if(t.advanced&&o){const l=t.edge;t.driftStart||(t.driftStartTime=o,t.driftStart=l),t.driftEndTime=o,t.driftEnd=l}else t.driftEndTime=r.driftEndTime,t.driftEnd=r.driftEnd,t.advancedDateTime=r.advancedDateTime}function $g(r,t,e){const i=At({},r);return e&&e.forEach(s=>{delete i[s]}),Object.keys(t).forEach(s=>{const n=new zl(t[s].attr,i[s]);n.isValid?i[s]=n:L.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${JSON.stringify(t[s].attr)}"`)}),i}function Fg(r,t,e){if(r&&t){let i=0;for(let s=0,n=r.length;s<=n;s++){const a=r[s],o=t[s+i];a&&o&&a.index===o.index&&a.fragment.sn===o.fragment.sn?e(a,o):i--}}}function Ng(r,t,e){const i=t.skippedSegments,s=Math.max(r.startSN,t.startSN)-t.startSN,n=(r.fragmentHint?1:0)+(i?t.endSN:Math.min(r.endSN,t.endSN))-t.startSN,a=t.startSN-r.startSN,o=t.fragmentHint?t.fragments.concat(t.fragmentHint):t.fragments,l=r.fragmentHint?r.fragments.concat(r.fragmentHint):r.fragments;for(let h=s;h<=n;h++){const d=l[a+h];let c=o[h];i&&!c&&h<i&&(c=t.fragments[h]=d),d&&c&&e(d,c)}}function Ch(r,t){const e=t.startSN+t.skippedSegments-r.startSN,i=r.fragments;e<0||e>=i.length||Qn(t,i[e].start)}function Qn(r,t){if(t){const e=r.fragments;for(let i=r.skippedSegments;i<e.length;i++)e[i].start+=t;r.fragmentHint&&(r.fragmentHint.start+=t)}}function Ug(r,t=1/0){let e=1e3*r.targetduration;if(r.updated){const i=r.fragments,s=4;if(i.length&&e*s>t){const n=i[i.length-1].duration*1e3;n<e&&(e=n)}}else e/=2;return Math.round(e)}function Bg(r,t,e){if(!(r!=null&&r.details))return null;const i=r.details;let s=i.fragments[t-i.startSN];return s||(s=i.fragmentHint,s&&s.sn===t)?s:t<i.startSN&&e&&e.sn===t?e:null}function Dh(r,t,e){var i;return r!=null&&r.details?xh((i=r.details)==null?void 0:i.partList,t,e):null}function xh(r,t,e){if(r)for(let i=r.length;i--;){const s=r[i];if(s.index===e&&s.fragment.sn===t)return s}return null}function dr(r){switch(r.details){case x.FRAG_LOAD_TIMEOUT:case x.KEY_LOAD_TIMEOUT:case x.LEVEL_LOAD_TIMEOUT:case x.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function Ph(r,t){const e=dr(t);return r.default[`${e?"timeout":"error"}Retry`]}function Zn(r,t){const e=r.backoff==="linear"?1:Math.pow(2,t);return Math.min(e*r.retryDelayMs,r.maxRetryDelayMs)}function Oh(r){return Gt(Gt({},r),{errorRetry:null,timeoutRetry:null})}function cr(r,t,e,i){return!!r&&t<r.maxNumRetry&&(Hg(i)||!!e)}function Hg(r){return r===0&&navigator.onLine===!1||!!r&&(r<400||r>499)}const Mh={search:function(r,t){let e=0,i=r.length-1,s=null,n=null;for(;e<=i;){s=(e+i)/2|0,n=r[s];const a=t(n);if(a>0)e=s+1;else if(a<0)i=s-1;else return n}return null}};function Gg(r,t,e){if(t===null||!Array.isArray(r)||!r.length||!j(t))return null;const i=r[0].programDateTime;if(t<(i||0))return null;const s=r[r.length-1].endProgramDateTime;if(t>=(s||0))return null;e=e||0;for(let n=0;n<r.length;++n){const a=r[n];if(Vg(t,e,a))return a}return null}function gs(r,t,e=0,i=0){let s=null;if(r?s=t[r.sn-t[0].sn+1]||null:e===0&&t[0].start===0&&(s=t[0]),s&&Jn(e,i,s)===0)return s;const n=Mh.search(t,Jn.bind(null,e,i));return n&&(n!==r||!s)?n:s}function Jn(r=0,t=0,e){if(e.start<=r&&e.start+e.duration>r)return 0;const i=Math.min(t,e.duration+(e.deltaPTS?e.deltaPTS:0));return e.start+e.duration-i<=r?1:e.start-i>r&&e.start?-1:0}function Vg(r,t,e){const i=Math.min(t,e.duration+(e.deltaPTS?e.deltaPTS:0))*1e3;return(e.endProgramDateTime||0)-i>r}function Kg(r,t){return Mh.search(r,e=>e.cc<t?1:e.cc>t?-1:0)}const jg=3e5;var Ot={DoNothing:0,SendEndCallback:1,SendAlternateToPenaltyBox:2,RemoveAlternatePermanently:3,InsertDiscontinuity:4,RetryRequest:5},Jt={None:0,MoveAllAlternatesMatchingHost:1,MoveAllAlternatesMatchingHDCP:2,SwitchToSDR:4};class Wg{constructor(t){this.hls=void 0,this.playlistError=0,this.penalizedRenditions={},this.log=void 0,this.warn=void 0,this.error=void 0,this.hls=t,this.log=L.log.bind(L,"[info]:"),this.warn=L.warn.bind(L,"[warning]:"),this.error=L.error.bind(L,"[error]:"),this.registerListeners()}registerListeners(){const t=this.hls;t.on(m.ERROR,this.onError,this),t.on(m.MANIFEST_LOADING,this.onManifestLoading,this),t.on(m.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){const t=this.hls;t&&(t.off(m.ERROR,this.onError,this),t.off(m.ERROR,this.onErrorOut,this),t.off(m.MANIFEST_LOADING,this.onManifestLoading,this),t.off(m.LEVEL_UPDATED,this.onLevelUpdated,this))}destroy(){this.unregisterListeners(),this.hls=null,this.penalizedRenditions={}}startLoad(t){this.playlistError=0}stopLoad(){}getVariantLevelIndex(t){return(t==null?void 0:t.type)===Y.MAIN?t.level:this.hls.loadLevel}onManifestLoading(){this.playlistError=0,this.penalizedRenditions={}}onLevelUpdated(){this.playlistError=0}onError(t,e){var i,s;if(e.fatal)return;const n=this.hls,a=e.context;switch(e.details){case x.FRAG_LOAD_ERROR:case x.FRAG_LOAD_TIMEOUT:case x.KEY_LOAD_ERROR:case x.KEY_LOAD_TIMEOUT:e.errorAction=this.getFragRetryOrSwitchAction(e);return;case x.FRAG_PARSING_ERROR:if((i=e.frag)!=null&&i.gap){e.errorAction={action:Ot.DoNothing,flags:Jt.None};return}case x.FRAG_GAP:case x.FRAG_DECRYPT_ERROR:{e.errorAction=this.getFragRetryOrSwitchAction(e),e.errorAction.action=Ot.SendAlternateToPenaltyBox;return}case x.LEVEL_EMPTY_ERROR:case x.LEVEL_PARSING_ERROR:{var o,l;const h=e.parent===Y.MAIN?e.level:n.loadLevel;e.details===x.LEVEL_EMPTY_ERROR&&(o=e.context)!=null&&(l=o.levelDetails)!=null&&l.live?e.errorAction=this.getPlaylistRetryOrSwitchAction(e,h):(e.levelRetry=!1,e.errorAction=this.getLevelSwitchAction(e,h))}return;case x.LEVEL_LOAD_ERROR:case x.LEVEL_LOAD_TIMEOUT:typeof(a==null?void 0:a.level)=="number"&&(e.errorAction=this.getPlaylistRetryOrSwitchAction(e,a.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(a){const h=n.levels[n.loadLevel];if(h&&(a.type===rt.AUDIO_TRACK&&a.groupId===h.audioGroupId||a.type===rt.SUBTITLE_TRACK&&a.groupId===h.textGroupId)){e.errorAction=this.getPlaylistRetryOrSwitchAction(e,n.loadLevel),e.errorAction.action=Ot.SendAlternateToPenaltyBox,e.errorAction.flags=Jt.MoveAllAlternatesMatchingHost;return}}return;case x.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:{const h=n.levels[n.loadLevel],d=h==null?void 0:h.attrs["HDCP-LEVEL"];d&&(e.errorAction={action:Ot.SendAlternateToPenaltyBox,flags:Jt.MoveAllAlternatesMatchingHDCP,hdcpLevel:d})}return;case x.BUFFER_ADD_CODEC_ERROR:case x.REMUX_ALLOC_ERROR:e.errorAction=this.getLevelSwitchAction(e,(s=e.level)!=null?s:n.loadLevel);return;case x.INTERNAL_EXCEPTION:case x.BUFFER_APPENDING_ERROR:case x.BUFFER_APPEND_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:e.errorAction={action:Ot.DoNothing,flags:Jt.None};return}if(e.type===W.KEY_SYSTEM_ERROR){const h=this.getVariantLevelIndex(e.frag);e.levelRetry=!1,e.errorAction=this.getLevelSwitchAction(e,h);return}}getPlaylistRetryOrSwitchAction(t,e){var i;const s=this.hls,n=Ph(s.config.playlistLoadPolicy,t),a=this.playlistError++,o=(i=t.response)==null?void 0:i.code;if(cr(n,a,dr(t),o))return{action:Ot.RetryRequest,flags:Jt.None,retryConfig:n,retryCount:a};const l=this.getLevelSwitchAction(t,e);return n&&(l.retryConfig=n,l.retryCount=a),l}getFragRetryOrSwitchAction(t){const e=this.hls,i=this.getVariantLevelIndex(t.frag),s=e.levels[i],{fragLoadPolicy:n,keyLoadPolicy:a}=e.config,o=Ph(t.details.startsWith("key")?a:n,t),l=e.levels.reduce((c,u)=>c+u.fragmentError,0);if(s){var h;t.details!==x.FRAG_GAP&&s.fragmentError++;const c=(h=t.response)==null?void 0:h.code;if(cr(o,l,dr(t),c))return{action:Ot.RetryRequest,flags:Jt.None,retryConfig:o,retryCount:l}}const d=this.getLevelSwitchAction(t,i);return o&&(d.retryConfig=o,d.retryCount=l),d}getLevelSwitchAction(t,e){const i=this.hls;e==null&&(e=i.loadLevel);const s=this.hls.levels[e];if(s&&(s.loadError++,i.autoLevelEnabled)){var n,a;let o=-1;const{levels:l,loadLevel:h,minAutoLevel:d,maxAutoLevel:c}=i,u=(n=t.frag)==null?void 0:n.type,{type:f,groupId:p}=(a=t.context)!=null?a:{};for(let g=l.length;g--;){const v=(g+h)%l.length;if(v!==h&&v>=d&&v<=c&&l[v].loadError===0){const E=l[v];if(t.details===x.FRAG_GAP&&t.frag){const T=l[v].details;if(T){const A=gs(t.frag,T.fragments,t.frag.start);if(A!=null&&A.gap)continue}}else if(f===rt.AUDIO_TRACK&&p===E.audioGroupId||f===rt.SUBTITLE_TRACK&&p===E.textGroupId||u===Y.AUDIO&&s.audioGroupId===E.audioGroupId||u===Y.SUBTITLE&&s.textGroupId===E.textGroupId)continue;o=v;break}}if(o>-1&&i.loadLevel!==o)return t.levelRetry=!0,this.playlistError=0,{action:Ot.SendAlternateToPenaltyBox,flags:Jt.None,nextAutoLevel:o}}return{action:Ot.SendAlternateToPenaltyBox,flags:Jt.MoveAllAlternatesMatchingHost}}onErrorOut(t,e){var i;switch((i=e.errorAction)==null?void 0:i.action){case Ot.DoNothing:break;case Ot.SendAlternateToPenaltyBox:this.sendAlternateToPenaltyBox(e),!e.errorAction.resolved&&e.details!==x.FRAG_GAP&&(e.fatal=!0);break}if(e.fatal){this.hls.stopLoad();return}}sendAlternateToPenaltyBox(t){const e=this.hls,i=t.errorAction;if(!i)return;const{flags:s,hdcpLevel:n,nextAutoLevel:a}=i;switch(s){case Jt.None:this.switchLevel(t,a);break;case Jt.MoveAllAlternatesMatchingHost:i.resolved||(i.resolved=this.redundantFailover(t));break;case Jt.MoveAllAlternatesMatchingHDCP:n&&(e.maxHdcpLevel=qn[qn.indexOf(n)-1],i.resolved=!0),this.warn(`Restricting playback to HDCP-LEVEL of "${e.maxHdcpLevel}" or lower`);break}i.resolved||this.switchLevel(t,a)}switchLevel(t,e){e!==void 0&&t.errorAction&&(this.warn(`switching to level ${e} after ${t.details}`),this.hls.nextAutoLevel=e,t.errorAction.resolved=!0,this.hls.nextLoadLevel=this.hls.nextAutoLevel)}redundantFailover(t){const{hls:e,penalizedRenditions:i}=this,s=t.parent===Y.MAIN?t.level:e.loadLevel,n=e.levels[s],a=n.url.length,o=t.frag?t.frag.urlId:n.urlId;n.urlId===o&&(!t.frag||n.details)&&this.penalizeRendition(n,t);for(let l=1;l<a;l++){const h=(o+l)%a,d=i[h];if(!d||Yg(d,t,i[o]))return this.warn(`Switching to Redundant Stream ${h+1}/${a}: "${n.url[h]}" after ${t.details}`),this.playlistError=0,e.levels.forEach(c=>{c.urlId=h}),e.nextLoadLevel=s,!0}return!1}penalizeRendition(t,e){const{penalizedRenditions:i}=this,s=i[t.urlId]||{lastErrorPerfMs:0,errors:[],details:void 0};s.lastErrorPerfMs=performance.now(),s.errors.push(e),s.details=t.details,i[t.urlId]=s}}function Yg(r,t,e){if(performance.now()-r.lastErrorPerfMs>jg)return!0;const i=r.details;if(t.details===x.FRAG_GAP&&i&&t.frag){const s=t.frag.start,n=gs(null,i.fragments,s);if(n&&!n.gap)return!0}if(e&&r.errors.length<e.errors.length){const s=r.errors[r.errors.length-1];if(i&&s.frag&&t.frag&&Math.abs(s.frag.start-t.frag.start)>i.targetduration*3)return!0}return!1}class ta{constructor(t,e){this.hls=void 0,this.timer=-1,this.requestScheduled=-1,this.canLoad=!1,this.log=void 0,this.warn=void 0,this.log=L.log.bind(L,`${e}:`),this.warn=L.warn.bind(L,`${e}:`),this.hls=t}destroy(){this.clearTimer(),this.hls=this.log=this.warn=null}clearTimer(){clearTimeout(this.timer),this.timer=-1}startLoad(){this.canLoad=!0,this.requestScheduled=-1,this.loadPlaylist()}stopLoad(){this.canLoad=!1,this.clearTimer()}switchParams(t,e){const i=e==null?void 0:e.renditionReports;if(i){let s=-1;for(let n=0;n<i.length;n++){const a=i[n];let o;try{o=new self.URL(a.URI,e.url).href}catch(l){L.warn(`Could not construct new URL for Rendition Report: ${l}`),o=a.URI||""}if(o===t){s=n;break}else o===t.substring(0,o.length)&&(s=n)}if(s!==-1){const n=i[s],a=parseInt(n["LAST-MSN"])||(e==null?void 0:e.lastPartSn);let o=parseInt(n["LAST-PART"])||(e==null?void 0:e.lastPartIndex);if(this.hls.config.lowLatencyMode){const l=Math.min(e.age-e.partTarget,e.targetduration);o>=0&&l>e.partTarget&&(o+=1)}return new Ih(a,o>=0?o:void 0,fs.No)}}}loadPlaylist(t){this.requestScheduled===-1&&(this.requestScheduled=self.performance.now())}shouldLoadPlaylist(t){return this.canLoad&&!!t&&!!t.url&&(!t.details||t.details.live)}shouldReloadPlaylist(t){return this.timer===-1&&this.requestScheduled===-1&&this.shouldLoadPlaylist(t)}playlistLoaded(t,e,i){const{details:s,stats:n}=e,a=self.performance.now(),o=n.loading.first?Math.max(0,a-n.loading.first):0;if(s.advancedDateTime=Date.now()-o,s.live||i!=null&&i.live){if(s.reloaded(i),i&&this.log(`live playlist ${t} ${s.advanced?"REFRESHED "+s.lastPartSn+"-"+s.lastPartIndex:s.updated?"UPDATED":"MISSED"}`),i&&s.fragments.length>0&&Mg(i,s),!this.canLoad||!s.live)return;let l,h,d;if(s.canBlockReload&&s.endSN&&s.advanced){const v=this.hls.config.lowLatencyMode,E=s.lastPartSn,T=s.endSN,A=s.lastPartIndex,y=A!==-1,b=E===T,S=v?0:A;y?(h=b?T+1:E,d=b?S:A+1):h=T+1;const R=s.age,D=R+s.ageHeader;let _=Math.min(D-s.partTarget,s.targetduration*1.5);if(_>0){if(i&&_>i.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${i.tuneInGoal} to: ${_} with playlist age: ${s.age}`),_=0;else{const I=Math.floor(_/s.targetduration);if(h+=I,d!==void 0){const N=Math.round(_%s.targetduration/s.partTarget);d+=N}this.log(`CDN Tune-in age: ${s.ageHeader}s last advanced ${R.toFixed(2)}s goal: ${_} skip sn ${I} to part ${d}`)}s.tuneInGoal=_}if(l=this.getDeliveryDirectives(s,e.deliveryDirectives,h,d),v||!b){this.loadPlaylist(l);return}}else(s.canBlockReload||s.canSkipUntil)&&(l=this.getDeliveryDirectives(s,e.deliveryDirectives,h,d));const c=this.hls.mainForwardBufferInfo,u=c?c.end-c.len:0,f=(s.edge-u)*1e3,p=Ug(s,f);s.updated&&a>this.requestScheduled+p&&(this.requestScheduled=n.loading.start),h!==void 0&&s.canBlockReload?this.requestScheduled=n.loading.first+p-(s.partTarget*1e3||1e3):this.requestScheduled===-1||this.requestScheduled+p<a?this.requestScheduled=a:this.requestScheduled-a<=0&&(this.requestScheduled+=p);let g=this.requestScheduled-a;g=Math.max(0,g),this.log(`reload live playlist ${t} in ${Math.round(g)} ms`),this.timer=self.setTimeout(()=>this.loadPlaylist(l),g)}else this.clearTimer()}getDeliveryDirectives(t,e,i,s){let n=Og(t,i);return e!=null&&e.skip&&t.deltaUpdateFailed&&(i=e.msn,s=e.part,n=fs.No),new Ih(i,s,n)}checkRetry(t){const e=t.details,i=dr(t),s=t.errorAction,{action:n,retryCount:a=0,retryConfig:o}=s||{},l=!!s&&!!o&&(n===Ot.RetryRequest||!s.resolved&&n===Ot.SendAlternateToPenaltyBox);if(l){var h;if(this.requestScheduled=-1,a>=o.maxNumRetry)return!1;if(i&&(h=t.context)!=null&&h.deliveryDirectives)this.warn(`Retrying playlist loading ${a+1}/${o.maxNumRetry} after "${e}" without delivery-directives`),this.loadPlaylist();else{const d=Zn(o,a);this.timer=self.setTimeout(()=>this.loadPlaylist(),d),this.warn(`Retrying playlist loading ${a+1}/${o.maxNumRetry} after "${e}" in ${d}ms`)}t.levelRetry=!0,s.resolved=!0}return l}}let ea;class zg extends ta{constructor(t,e){super(t,"[level-controller]"),this._levels=[],this._firstLevel=-1,this._startLevel=void 0,this.currentLevel=null,this.currentLevelIndex=-1,this.manualLevelIndex=-1,this.steering=void 0,this.onParsedComplete=void 0,this.steering=e,this._registerListeners()}_registerListeners(){const{hls:t}=this;t.on(m.MANIFEST_LOADING,this.onManifestLoading,this),t.on(m.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(m.LEVEL_LOADED,this.onLevelLoaded,this),t.on(m.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(m.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),t.on(m.FRAG_LOADED,this.onFragLoaded,this),t.on(m.ERROR,this.onError,this)}_unregisterListeners(){const{hls:t}=this;t.off(m.MANIFEST_LOADING,this.onManifestLoading,this),t.off(m.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(m.LEVEL_LOADED,this.onLevelLoaded,this),t.off(m.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(m.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),t.off(m.FRAG_LOADED,this.onFragLoaded,this),t.off(m.ERROR,this.onError,this)}destroy(){this._unregisterListeners(),this.steering=null,this.resetLevels(),super.destroy()}startLoad(){this._levels.forEach(t=>{t.loadError=0,t.fragmentError=0}),super.startLoad()}resetLevels(){this._startLevel=void 0,this.manualLevelIndex=-1,this.currentLevelIndex=-1,this.currentLevel=null,this._levels=[]}onManifestLoading(t,e){this.resetLevels()}onManifestLoaded(t,e){const i=[],s={};let n;e.levels.forEach(a=>{var o;const l=a.attrs;((o=a.audioCodec)==null?void 0:o.indexOf("mp4a.40.34"))!==-1&&(ea||(ea=/chrome|firefox/i.test(navigator.userAgent)),ea&&(a.audioCodec=void 0));const{AUDIO:h,CODECS:d,"FRAME-RATE":c,"PATHWAY-ID":u,RESOLUTION:f,SUBTITLES:p}=l,g=`${`${u||"."}-`}${a.bitrate}-${f}-${c}-${d}`;n=s[g],n?n.addFallback(a):(n=new ps(a),s[g]=n,i.push(n)),ur(n,"audio",h),ur(n,"text",p)}),this.filterAndSortMediaOptions(i,e)}filterAndSortMediaOptions(t,e){let i=[],s=[],n=!1,a=!1,o=!1,l=t.filter(({audioCodec:f,videoCodec:p,width:g,height:v,unknownCodecs:E})=>(n||(n=!!(g&&v)),a||(a=!!p),o||(o=!!f),!(E!=null&&E.length)&&(!f||Kn(f,"audio"))&&(!p||Kn(p,"video"))));if((n||a)&&o&&(l=l.filter(({videoCodec:f,width:p,height:g})=>!!f||!!(p&&g))),l.length===0){Promise.resolve().then(()=>{if(this.hls){const f=new Error("no level with compatible codecs found in manifest");this.hls.trigger(m.ERROR,{type:W.MEDIA_ERROR,details:x.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:e.url,error:f,reason:f.message})}});return}e.audioTracks&&(i=e.audioTracks.filter(f=>!f.audioCodec||Kn(f.audioCodec,"audio")),$h(i)),e.subtitles&&(s=e.subtitles,$h(s));const h=l.slice(0);l.sort((f,p)=>f.attrs["HDCP-LEVEL"]!==p.attrs["HDCP-LEVEL"]?(f.attrs["HDCP-LEVEL"]||"")>(p.attrs["HDCP-LEVEL"]||"")?1:-1:f.bitrate!==p.bitrate?f.bitrate-p.bitrate:f.attrs["FRAME-RATE"]!==p.attrs["FRAME-RATE"]?f.attrs.decimalFloatingPoint("FRAME-RATE")-p.attrs.decimalFloatingPoint("FRAME-RATE"):f.attrs.SCORE!==p.attrs.SCORE?f.attrs.decimalFloatingPoint("SCORE")-p.attrs.decimalFloatingPoint("SCORE"):n&&f.height!==p.height?f.height-p.height:0);let d=h[0];if(this.steering&&(l=this.steering.filterParsedLevels(l),l.length!==h.length)){for(let f=0;f<h.length;f++)if(h[f].pathwayId===l[0].pathwayId){d=h[f];break}}this._levels=l;for(let f=0;f<l.length;f++)if(l[f]===d){this._firstLevel=f,this.log(`manifest loaded, ${l.length} level(s) found, first bitrate: ${d.bitrate}`);break}const c=o&&!a,u={levels:l,audioTracks:i,subtitleTracks:s,sessionData:e.sessionData,sessionKeys:e.sessionKeys,firstLevel:this._firstLevel,stats:e.stats,audio:o,video:a,altAudio:!c&&i.some(f=>!!f.url)};this.hls.trigger(m.MANIFEST_PARSED,u),(this.hls.config.autoStartLoad||this.hls.forceStartLoad)&&this.hls.startLoad(this.hls.config.startPosition)}get levels(){return this._levels.length===0?null:this._levels}get level(){return this.currentLevelIndex}set level(t){const e=this._levels;if(e.length===0)return;if(t<0||t>=e.length){const d=new Error("invalid level idx"),c=t<0;if(this.hls.trigger(m.ERROR,{type:W.OTHER_ERROR,details:x.LEVEL_SWITCH_ERROR,level:t,fatal:c,error:d,reason:d.message}),c)return;t=Math.min(t,e.length-1)}const i=this.currentLevelIndex,s=this.currentLevel,n=s?s.attrs["PATHWAY-ID"]:void 0,a=e[t],o=a.attrs["PATHWAY-ID"];if(this.currentLevelIndex=t,this.currentLevel=a,i===t&&a.details&&s&&n===o)return;this.log(`Switching to level ${t}${o?" with Pathway "+o:""} from level ${i}${n?" with Pathway "+n:""}`);const l=At({},a,{level:t,maxBitrate:a.maxBitrate,attrs:a.attrs,uri:a.uri,urlId:a.urlId});delete l._attrs,delete l._urlId,this.hls.trigger(m.LEVEL_SWITCHING,l);const h=a.details;if(!h||h.live){const d=this.switchParams(a.uri,s==null?void 0:s.details);this.loadPlaylist(d)}}get manualLevel(){return this.manualLevelIndex}set manualLevel(t){this.manualLevelIndex=t,this._startLevel===void 0&&(this._startLevel=t),t!==-1&&(this.level=t)}get firstLevel(){return this._firstLevel}set firstLevel(t){this._firstLevel=t}get startLevel(){if(this._startLevel===void 0){const t=this.hls.config.startLevel;return t!==void 0?t:this._firstLevel}else return this._startLevel}set startLevel(t){this._startLevel=t}onError(t,e){e.fatal||!e.context||e.context.type===rt.LEVEL&&e.context.level===this.level&&this.checkRetry(e)}onFragLoaded(t,{frag:e}){if(e!==void 0&&e.type===Y.MAIN){const i=this._levels[e.level];i!==void 0&&(i.loadError=0)}}onLevelLoaded(t,e){var i;const{level:s,details:n}=e,a=this._levels[s];if(!a){var o;this.warn(`Invalid level index ${s}`),(o=e.deliveryDirectives)!=null&&o.skip&&(n.deltaUpdateFailed=!0);return}s===this.currentLevelIndex?(a.fragmentError===0&&(a.loadError=0),this.playlistLoaded(s,e,a.details)):(i=e.deliveryDirectives)!=null&&i.skip&&(n.deltaUpdateFailed=!0)}onAudioTrackSwitched(t,e){const i=this.currentLevel;if(!i)return;const s=this.hls.audioTracks[e.id].groupId;if(i.audioGroupIds&&i.audioGroupId!==s){let n=-1;for(let a=0;a<i.audioGroupIds.length;a++)if(i.audioGroupIds[a]===s){n=a;break}n!==-1&&n!==i.urlId&&(i.urlId=n,this.canLoad&&this.startLoad())}}loadPlaylist(t){super.loadPlaylist();const e=this.currentLevelIndex,i=this.currentLevel;if(i&&this.shouldLoadPlaylist(i)){const s=i.urlId;let n=i.uri;if(t)try{n=t.addDirectives(n)}catch(o){this.warn(`Could not construct new URL with HLS Delivery Directives: ${o}`)}const a=i.attrs["PATHWAY-ID"];this.log(`Loading level index ${e}${(t==null?void 0:t.msn)!==void 0?" at sn "+t.msn+" part "+t.part:""} with${a?" Pathway "+a:""} URI ${s+1}/${i.url.length} ${n}`),this.clearTimer(),this.hls.trigger(m.LEVEL_LOADING,{url:n,level:e,id:s,deliveryDirectives:t||null})}}get nextLoadLevel(){return this.manualLevelIndex!==-1?this.manualLevelIndex:this.hls.nextAutoLevel}set nextLoadLevel(t){this.level=t,this.manualLevelIndex===-1&&(this.hls.nextAutoLevel=t)}removeLevel(t,e){const i=(n,a)=>a!==e,s=this._levels.filter((n,a)=>a!==t?!0:n.url.length>1&&e!==void 0?(n.url=n.url.filter(i),n.audioGroupIds&&(n.audioGroupIds=n.audioGroupIds.filter(i)),n.textGroupIds&&(n.textGroupIds=n.textGroupIds.filter(i)),n.urlId=0,!0):(this.steering&&this.steering.removeLevel(n),!1));this.hls.trigger(m.LEVELS_UPDATED,{levels:s})}onLevelsUpdated(t,{levels:e}){e.forEach((i,s)=>{const{details:n}=i;n!=null&&n.fragments&&n.fragments.forEach(a=>{a.level=s})}),this._levels=e}}function ur(r,t,e){e&&(t==="audio"?(r.audioGroupIds||(r.audioGroupIds=[]),r.audioGroupIds[r.url.length-1]=e):t==="text"&&(r.textGroupIds||(r.textGroupIds=[]),r.textGroupIds[r.url.length-1]=e))}function $h(r){const t={};r.forEach(e=>{const i=e.groupId||"";e.id=t[i]=t[i]||0,t[i]++})}var Lt={NOT_LOADED:"NOT_LOADED",APPENDING:"APPENDING",PARTIAL:"PARTIAL",OK:"OK"};class qg{constructor(t){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=!1,this.hls=t,this._registerListeners()}_registerListeners(){const{hls:t}=this;t.on(m.BUFFER_APPENDED,this.onBufferAppended,this),t.on(m.FRAG_BUFFERED,this.onFragBuffered,this),t.on(m.FRAG_LOADED,this.onFragLoaded,this)}_unregisterListeners(){const{hls:t}=this;t.off(m.BUFFER_APPENDED,this.onBufferAppended,this),t.off(m.FRAG_BUFFERED,this.onFragBuffered,this),t.off(m.FRAG_LOADED,this.onFragLoaded,this)}destroy(){this._unregisterListeners(),this.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null}getAppendedFrag(t,e){const i=this.activePartLists[e];if(i)for(let s=i.length;s--;){const n=i[s];if(!n)break;const a=n.end;if(n.start<=t&&a!==null&&t<=a)return n}return this.getBufferedFrag(t,e)}getBufferedFrag(t,e){const{fragments:i}=this,s=Object.keys(i);for(let n=s.length;n--;){const a=i[s[n]];if((a==null?void 0:a.body.type)===e&&a.buffered){const o=a.body;if(o.start<=t&&t<=o.end)return o}}return null}detectEvictedFragments(t,e,i,s){this.timeRanges&&(this.timeRanges[t]=e);const n=(s==null?void 0:s.fragment.sn)||-1;Object.keys(this.fragments).forEach(a=>{const o=this.fragments[a];if(!o||n>=o.body.sn)return;if(!o.buffered&&!o.loaded){o.body.type===i&&this.removeFragment(o.body);return}const l=o.range[t];l&&l.time.some(h=>{const d=!this.isTimeBuffered(h.startPTS,h.endPTS,e);return d&&this.removeFragment(o.body),d})})}detectPartialFragments(t){const e=this.timeRanges,{frag:i,part:s}=t;if(!e||i.sn==="initSegment")return;const n=Ai(i),a=this.fragments[n];if(!a||a.buffered&&i.gap)return;const o=!i.relurl;Object.keys(e).forEach(l=>{const h=i.elementaryStreams[l];if(!h)return;const d=e[l],c=o||h.partial===!0;a.range[l]=this.getBufferedTimes(i,s,c,d)}),a.loaded=null,Object.keys(a.range).length?(a.buffered=!0,(a.body.endList=i.endList||a.body.endList)&&(this.endListFragments[a.body.type]=a),fr(a)||this.removeParts(i.sn-1,i.type)):this.removeFragment(a.body)}removeParts(t,e){const i=this.activePartLists[e];i&&(this.activePartLists[e]=i.filter(s=>s.fragment.sn>=t))}fragBuffered(t,e){const i=Ai(t);let s=this.fragments[i];!s&&e&&(s=this.fragments[i]={body:t,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},t.gap&&(this.hasGaps=!0)),s&&(s.loaded=null,s.buffered=!0)}getBufferedTimes(t,e,i,s){const n={time:[],partial:i},a=t.start,o=t.end,l=t.minEndPTS||o,h=t.maxStartPTS||a;for(let d=0;d<s.length;d++){const c=s.start(d)-this.bufferPadding,u=s.end(d)+this.bufferPadding;if(h>=c&&l<=u){n.time.push({startPTS:Math.max(a,s.start(d)),endPTS:Math.min(o,s.end(d))});break}else if(a<u&&o>c)n.partial=!0,n.time.push({startPTS:Math.max(a,s.start(d)),endPTS:Math.min(o,s.end(d))});else if(o<=c)break}return n}getPartialFragment(t){let e=null,i,s,n,a=0;const{bufferPadding:o,fragments:l}=this;return Object.keys(l).forEach(h=>{const d=l[h];d&&fr(d)&&(s=d.body.start-o,n=d.body.end+o,t>=s&&t<=n&&(i=Math.min(t-s,n-t),a<=i&&(e=d.body,a=i)))}),e}isEndListAppended(t){const e=this.endListFragments[t];return e!==void 0&&(e.buffered||fr(e))}getState(t){const e=Ai(t),i=this.fragments[e];return i?i.buffered?fr(i)?Lt.PARTIAL:Lt.OK:Lt.APPENDING:Lt.NOT_LOADED}isTimeBuffered(t,e,i){let s,n;for(let a=0;a<i.length;a++){if(s=i.start(a)-this.bufferPadding,n=i.end(a)+this.bufferPadding,t>=s&&e<=n)return!0;if(e<=s)return!1}return!1}onFragLoaded(t,e){const{frag:i,part:s}=e;if(i.sn==="initSegment"||i.bitrateTest)return;const n=s?null:e,a=Ai(i);this.fragments[a]={body:i,appendedPTS:null,loaded:n,buffered:!1,range:Object.create(null)}}onBufferAppended(t,e){const{frag:i,part:s,timeRanges:n}=e;if(i.sn==="initSegment")return;const a=i.type;if(s){let o=this.activePartLists[a];o||(this.activePartLists[a]=o=[]),o.push(s)}this.timeRanges=n,Object.keys(n).forEach(o=>{const l=n[o];this.detectEvictedFragments(o,l,a,s)})}onFragBuffered(t,e){this.detectPartialFragments(e)}hasFragment(t){const e=Ai(t);return!!this.fragments[e]}hasParts(t){var e;return!!((e=this.activePartLists[t])!=null&&e.length)}removeFragmentsInRange(t,e,i,s,n){s&&!this.hasGaps||Object.keys(this.fragments).forEach(a=>{const o=this.fragments[a];if(!o)return;const l=o.body;l.type!==i||s&&!l.gap||l.start<e&&l.end>t&&(o.buffered||n)&&this.removeFragment(l)})}removeFragment(t){const e=Ai(t);t.stats.loaded=0,t.clearElementaryStreamInfo();const i=this.activePartLists[t.type];if(i){const s=t.sn;this.activePartLists[t.type]=i.filter(n=>n.fragment.sn!==s)}delete this.fragments[e],t.endList&&delete this.endListFragments[t.type]}removeAllFragments(){this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=!1}}function fr(r){var t,e,i;return r.buffered&&(r.body.gap||((t=r.range.video)==null?void 0:t.partial)||((e=r.range.audio)==null?void 0:e.partial)||((i=r.range.audiovideo)==null?void 0:i.partial))}function Ai(r){return`${r.type}_${r.level}_${r.urlId}_${r.sn}`}const Fh=Math.pow(2,17);class Xg{constructor(t){this.config=void 0,this.loader=null,this.partLoadTimeout=-1,this.config=t}destroy(){this.loader&&(this.loader.destroy(),this.loader=null)}abort(){this.loader&&this.loader.abort()}load(t,e){const i=t.url;if(!i)return Promise.reject(new Le({type:W.NETWORK_ERROR,details:x.FRAG_LOAD_ERROR,fatal:!1,frag:t,error:new Error(`Fragment does not have a ${i?"part list":"url"}`),networkDetails:null}));this.abort();const s=this.config,n=s.fLoader,a=s.loader;return new Promise((o,l)=>{if(this.loader&&this.loader.destroy(),t.gap)if(t.tagList.some(f=>f[0]==="GAP")){l(Uh(t));return}else t.gap=!1;const h=this.loader=t.loader=n?new n(s):new a(s),d=Nh(t),c=Oh(s.fragLoadPolicy.default),u={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:t.sn==="initSegment"?1/0:Fh};t.stats=h.stats,h.load(d,u,{onSuccess:(f,p,g,v)=>{this.resetLoader(t,h);let E=f.data;g.resetIV&&t.decryptdata&&(t.decryptdata.iv=new Uint8Array(E.slice(0,16)),E=E.slice(16)),o({frag:t,part:null,payload:E,networkDetails:v})},onError:(f,p,g,v)=>{this.resetLoader(t,h),l(new Le({type:W.NETWORK_ERROR,details:x.FRAG_LOAD_ERROR,fatal:!1,frag:t,response:Gt({url:i,data:void 0},f),error:new Error(`HTTP Error ${f.code} ${f.text}`),networkDetails:g,stats:v}))},onAbort:(f,p,g)=>{this.resetLoader(t,h),l(new Le({type:W.NETWORK_ERROR,details:x.INTERNAL_ABORTED,fatal:!1,frag:t,error:new Error("Aborted"),networkDetails:g,stats:f}))},onTimeout:(f,p,g)=>{this.resetLoader(t,h),l(new Le({type:W.NETWORK_ERROR,details:x.FRAG_LOAD_TIMEOUT,fatal:!1,frag:t,error:new Error(`Timeout after ${u.timeout}ms`),networkDetails:g,stats:f}))},onProgress:(f,p,g,v)=>{e&&e({frag:t,part:null,payload:g,networkDetails:v})}})})}loadPart(t,e,i){this.abort();const s=this.config,n=s.fLoader,a=s.loader;return new Promise((o,l)=>{if(this.loader&&this.loader.destroy(),t.gap||e.gap){l(Uh(t,e));return}const h=this.loader=t.loader=n?new n(s):new a(s),d=Nh(t,e),c=Oh(s.fragLoadPolicy.default),u={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:Fh};e.stats=h.stats,h.load(d,u,{onSuccess:(f,p,g,v)=>{this.resetLoader(t,h),this.updateStatsFromPart(t,e);const E={frag:t,part:e,payload:f.data,networkDetails:v};i(E),o(E)},onError:(f,p,g,v)=>{this.resetLoader(t,h),l(new Le({type:W.NETWORK_ERROR,details:x.FRAG_LOAD_ERROR,fatal:!1,frag:t,part:e,response:Gt({url:d.url,data:void 0},f),error:new Error(`HTTP Error ${f.code} ${f.text}`),networkDetails:g,stats:v}))},onAbort:(f,p,g)=>{t.stats.aborted=e.stats.aborted,this.resetLoader(t,h),l(new Le({type:W.NETWORK_ERROR,details:x.INTERNAL_ABORTED,fatal:!1,frag:t,part:e,error:new Error("Aborted"),networkDetails:g,stats:f}))},onTimeout:(f,p,g)=>{this.resetLoader(t,h),l(new Le({type:W.NETWORK_ERROR,details:x.FRAG_LOAD_TIMEOUT,fatal:!1,frag:t,part:e,error:new Error(`Timeout after ${u.timeout}ms`),networkDetails:g,stats:f}))}})})}updateStatsFromPart(t,e){const i=t.stats,s=e.stats,n=s.total;if(i.loaded+=s.loaded,n){const l=Math.round(t.duration/e.duration),h=Math.min(Math.round(i.loaded/n),l),d=(l-h)*Math.round(i.loaded/h);i.total=i.loaded+d}else i.total=Math.max(i.loaded,i.total);const a=i.loading,o=s.loading;a.start?a.first+=o.first-o.start:(a.start=o.start,a.first=o.first),a.end=o.end}resetLoader(t,e){t.loader=null,this.loader===e&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),e.destroy()}}function Nh(r,t=null){const e=t||r,i={frag:r,part:t,responseType:"arraybuffer",url:e.url,headers:{},rangeStart:0,rangeEnd:0},s=e.byteRangeStartOffset,n=e.byteRangeEndOffset;if(j(s)&&j(n)){var a;let o=s,l=n;if(r.sn==="initSegment"&&((a=r.decryptdata)==null?void 0:a.method)==="AES-128"){const h=n-s;h%16&&(l=n+(16-h%16)),s!==0&&(i.resetIV=!0,o=s-16)}i.rangeStart=o,i.rangeEnd=l}return i}function Uh(r,t){const e=new Error(`GAP ${r.gap?"tag":"attribute"} found`),i={type:W.MEDIA_ERROR,details:x.FRAG_GAP,fatal:!1,frag:r,error:e,networkDetails:null};return t&&(i.part=t),(t||r).stats.aborted=!0,new Le(i)}class Le extends Error{constructor(t){super(t.error.message),this.data=void 0,this.data=t}}class Qg{constructor(t){this.config=void 0,this.keyUriToKeyInfo={},this.emeController=null,this.config=t}abort(t){for(const e in this.keyUriToKeyInfo){const i=this.keyUriToKeyInfo[e].loader;if(i){if(t&&t!==i.context.frag.type)return;i.abort()}}}detach(){for(const t in this.keyUriToKeyInfo){const e=this.keyUriToKeyInfo[t];(e.mediaKeySessionContext||e.decryptdata.isCommonEncryption)&&delete this.keyUriToKeyInfo[t]}}destroy(){this.detach();for(const t in this.keyUriToKeyInfo){const e=this.keyUriToKeyInfo[t].loader;e&&e.destroy()}this.keyUriToKeyInfo={}}createKeyLoadError(t,e=x.KEY_LOAD_ERROR,i,s,n){return new Le({type:W.NETWORK_ERROR,details:e,fatal:!1,frag:t,response:n,error:i,networkDetails:s})}loadClear(t,e){if(this.emeController&&this.config.emeEnabled){const{sn:i,cc:s}=t;for(let n=0;n<e.length;n++){const a=e[n];if(s<=a.cc&&(i==="initSegment"||a.sn==="initSegment"||i<a.sn)){this.emeController.selectKeySystemFormat(a).then(o=>{a.setKeyFormat(o)});break}}}}load(t){return!t.decryptdata&&t.encrypted&&this.emeController?this.emeController.selectKeySystemFormat(t).then(e=>this.loadInternal(t,e)):this.loadInternal(t)}loadInternal(t,e){var i,s;e&&t.setKeyFormat(e);const n=t.decryptdata;if(!n){const h=new Error(e?`Expected frag.decryptdata to be defined after setting format ${e}`:"Missing decryption data on fragment in onKeyLoading");return Promise.reject(this.createKeyLoadError(t,x.KEY_LOAD_ERROR,h))}const a=n.uri;if(!a)return Promise.reject(this.createKeyLoadError(t,x.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${a}"`)));let o=this.keyUriToKeyInfo[a];if((i=o)!=null&&i.decryptdata.key)return n.key=o.decryptdata.key,Promise.resolve({frag:t,keyInfo:o});if((s=o)!=null&&s.keyLoadPromise){var l;switch((l=o.mediaKeySessionContext)==null?void 0:l.keyStatus){case void 0:case"status-pending":case"usable":case"usable-in-future":return o.keyLoadPromise.then(h=>(n.key=h.keyInfo.decryptdata.key,{frag:t,keyInfo:o}))}}switch(o=this.keyUriToKeyInfo[a]={decryptdata:n,keyLoadPromise:null,loader:null,mediaKeySessionContext:null},n.method){case"ISO-23001-7":case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return n.keyFormat==="identity"?this.loadKeyHTTP(o,t):this.loadKeyEME(o,t);case"AES-128":return this.loadKeyHTTP(o,t);default:return Promise.reject(this.createKeyLoadError(t,x.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${n.method}"`)))}}loadKeyEME(t,e){const i={frag:e,keyInfo:t};if(this.emeController&&this.config.emeEnabled){const s=this.emeController.loadKey(i);if(s)return(t.keyLoadPromise=s.then(n=>(t.mediaKeySessionContext=n,i))).catch(n=>{throw t.keyLoadPromise=null,n})}return Promise.resolve(i)}loadKeyHTTP(t,e){const i=this.config,s=i.loader,n=new s(i);return e.keyLoader=t.loader=n,t.keyLoadPromise=new Promise((a,o)=>{const l={keyInfo:t,frag:e,responseType:"arraybuffer",url:t.decryptdata.uri},h=i.keyLoadPolicy.default,d={loadPolicy:h,timeout:h.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},c={onSuccess:(u,f,p,g)=>{const{frag:v,keyInfo:E,url:T}=p;if(!v.decryptdata||E!==this.keyUriToKeyInfo[T])return o(this.createKeyLoadError(v,x.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),g));E.decryptdata.key=v.decryptdata.key=new Uint8Array(u.data),v.keyLoader=null,E.loader=null,a({frag:v,keyInfo:E})},onError:(u,f,p,g)=>{this.resetLoader(f),o(this.createKeyLoadError(e,x.KEY_LOAD_ERROR,new Error(`HTTP Error ${u.code} loading key ${u.text}`),p,Gt({url:l.url,data:void 0},u)))},onTimeout:(u,f,p)=>{this.resetLoader(f),o(this.createKeyLoadError(e,x.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),p))},onAbort:(u,f,p)=>{this.resetLoader(f),o(this.createKeyLoadError(e,x.INTERNAL_ABORTED,new Error("key loading aborted"),p))}};n.load(l,d,c)})}resetLoader(t){const{frag:e,keyInfo:i,url:s}=t,n=i.loader;e.keyLoader===n&&(e.keyLoader=null,i.loader=null),delete this.keyUriToKeyInfo[s],n&&n.destroy()}}class Zg{constructor(){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(t){return this._tickInterval?!1:(this._tickCallCount=0,this._tickInterval=self.setInterval(this._boundTick,t),!0)}clearInterval(){return this._tickInterval?(self.clearInterval(this._tickInterval),this._tickInterval=null,!0):!1}clearNextTick(){return this._tickTimer?(self.clearTimeout(this._tickTimer),this._tickTimer=null,!0):!1}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(){}}const Jg={length:0,start:()=>0,end:()=>0};class lt{static isBuffered(t,e){try{if(t){const i=lt.getBuffered(t);for(let s=0;s<i.length;s++)if(e>=i.start(s)&&e<=i.end(s))return!0}}catch{}return!1}static bufferInfo(t,e,i){try{if(t){const s=lt.getBuffered(t),n=[];let a;for(a=0;a<s.length;a++)n.push({start:s.start(a),end:s.end(a)});return this.bufferedInfo(n,e,i)}}catch{}return{len:0,start:e,end:e,nextStart:void 0}}static bufferedInfo(t,e,i){e=Math.max(0,e),t.sort(function(h,d){return h.start-d.start||d.end-h.end});let s=[];if(i)for(let h=0;h<t.length;h++){const d=s.length;if(d){const c=s[d-1].end;t[h].start-c<i?t[h].end>c&&(s[d-1].end=t[h].end):s.push(t[h])}else s.push(t[h])}else s=t;let n=0,a,o=e,l=e;for(let h=0;h<s.length;h++){const d=s[h].start,c=s[h].end;if(e+i>=d&&e<c)o=d,l=c,n=l-e;else if(e+i<d){a=d;break}}return{len:n,start:o||0,end:l||0,nextStart:a}}static getBuffered(t){try{return t.buffered}catch(e){return L.log("failed to get media.buffered",e),Jg}}}class ia{constructor(t,e,i,s=0,n=-1,a=!1){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=pr(),this.buffering={audio:pr(),video:pr(),audiovideo:pr()},this.level=t,this.sn=e,this.id=i,this.size=s,this.part=n,this.partial=a}}function pr(){return{start:0,executeStart:0,executeEnd:0,end:0}}function Bh(r,t){let e=null;for(let i=0,s=r.length;i<s;i++){const n=r[i];if(n&&n.cc===t){e=n;break}}return e}function tm(r,t,e){return!!(t.details&&(e.endCC>e.startCC||r&&r.cc<e.startCC))}function em(r,t,e=0){const i=r.fragments,s=t.fragments;if(!s.length||!i.length){L.log("No fragments to align");return}const n=Bh(i,s[0].cc);if(!n||n&&!n.startPTS){L.log("No frag in previous level to align on");return}return n}function Hh(r,t){if(r){const e=r.start+t;r.start=r.startPTS=e,r.endPTS=e+r.duration}}function sa(r,t){const e=t.fragments;for(let i=0,s=e.length;i<s;i++)Hh(e[i],r);t.fragmentHint&&Hh(t.fragmentHint,r),t.alignedSliding=!0}function im(r,t,e){t&&(sm(r,e,t),!e.alignedSliding&&t.details&&rm(e,t.details),!e.alignedSliding&&t.details&&!e.skippedSegments&&Ch(t.details,e))}function sm(r,t,e){if(tm(r,e,t)){const i=em(e.details,t);i&&j(i.start)&&(L.log(`Adjusting PTS using last level due to CC increase within current level ${t.url}`),sa(i.start,t))}}function rm(r,t){if(!t.fragments.length||!r.hasProgramDateTime||!t.hasProgramDateTime)return;const e=t.fragments[0].programDateTime,i=r.fragments[0].programDateTime,s=(i-e)/1e3+t.fragments[0].start;s&&j(s)&&(L.log(`Adjusting PTS using programDateTime delta ${i-e}ms, sliding:${s.toFixed(3)} ${r.url} `),sa(s,r))}function Gh(r,t){if(!r.hasProgramDateTime||!t.hasProgramDateTime)return;const e=r.fragments,i=t.fragments;if(!e.length||!i.length)return;const s=Math.round(i.length/2)-1,n=i[s],a=Bh(e,n.cc)||e[Math.round(e.length/2)-1],o=n.programDateTime,l=a.programDateTime;if(o===null||l===null)return;const h=(l-o)/1e3-(a.start-n.start);sa(h,r)}class nm{constructor(t,e){this.subtle=void 0,this.aesIV=void 0,this.subtle=t,this.aesIV=e}decrypt(t,e){return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},e,t)}}class am{constructor(t,e){this.subtle=void 0,this.key=void 0,this.subtle=t,this.key=e}expandKey(){return this.subtle.importKey("raw",this.key,{name:"AES-CBC"},!1,["encrypt","decrypt"])}}function om(r){const t=r.byteLength,e=t&&new DataView(r.buffer).getUint8(t-1);return e?ii(r,0,t-e):r}class lm{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_(t){const e=new DataView(t),i=new Uint32Array(4);for(let s=0;s<4;s++)i[s]=e.getUint32(s*4);return i}initTable(){const t=this.sBox,e=this.invSBox,i=this.subMix,s=i[0],n=i[1],a=i[2],o=i[3],l=this.invSubMix,h=l[0],d=l[1],c=l[2],u=l[3],f=new Uint32Array(256);let p=0,g=0,v=0;for(v=0;v<256;v++)v<128?f[v]=v<<1:f[v]=v<<1^283;for(v=0;v<256;v++){let E=g^g<<1^g<<2^g<<3^g<<4;E=E>>>8^E&255^99,t[p]=E,e[E]=p;const T=f[p],A=f[T],y=f[A];let b=f[E]*257^E*16843008;s[p]=b<<24|b>>>8,n[p]=b<<16|b>>>16,a[p]=b<<8|b>>>24,o[p]=b,b=y*16843009^A*65537^T*257^p*16843008,h[E]=b<<24|b>>>8,d[E]=b<<16|b>>>16,c[E]=b<<8|b>>>24,u[E]=b,p?(p=T^f[f[f[y^T]]],g^=f[f[g]]):p=g=1}}expandKey(t){const e=this.uint8ArrayToUint32Array_(t);let i=!0,s=0;for(;s<e.length&&i;)i=e[s]===this.key[s],s++;if(i)return;this.key=e;const n=this.keySize=e.length;if(n!==4&&n!==6&&n!==8)throw new Error("Invalid aes key size="+n);const a=this.ksRows=(n+6+1)*4;let o,l;const h=this.keySchedule=new Uint32Array(a),d=this.invKeySchedule=new Uint32Array(a),c=this.sBox,u=this.rcon,f=this.invSubMix,p=f[0],g=f[1],v=f[2],E=f[3];let T,A;for(o=0;o<a;o++){if(o<n){T=h[o]=e[o];continue}A=T,o%n===0?(A=A<<8|A>>>24,A=c[A>>>24]<<24|c[A>>>16&255]<<16|c[A>>>8&255]<<8|c[A&255],A^=u[o/n|0]<<24):n>6&&o%n===4&&(A=c[A>>>24]<<24|c[A>>>16&255]<<16|c[A>>>8&255]<<8|c[A&255]),h[o]=T=(h[o-n]^A)>>>0}for(l=0;l<a;l++)o=a-l,l&3?A=h[o]:A=h[o-4],l<4||o<=4?d[l]=A:d[l]=p[c[A>>>24]]^g[c[A>>>16&255]]^v[c[A>>>8&255]]^E[c[A&255]],d[l]=d[l]>>>0}networkToHostOrderSwap(t){return t<<24|(t&65280)<<8|(t&16711680)>>8|t>>>24}decrypt(t,e,i){const s=this.keySize+6,n=this.invKeySchedule,a=this.invSBox,o=this.invSubMix,l=o[0],h=o[1],d=o[2],c=o[3],u=this.uint8ArrayToUint32Array_(i);let f=u[0],p=u[1],g=u[2],v=u[3];const E=new Int32Array(t),T=new Int32Array(E.length);let A,y,b,S,R,D,_,I,N,P,F,K,w,C;const U=this.networkToHostOrderSwap;for(;e<E.length;){for(N=U(E[e]),P=U(E[e+1]),F=U(E[e+2]),K=U(E[e+3]),R=N^n[0],D=K^n[1],_=F^n[2],I=P^n[3],w=4,C=1;C<s;C++)A=l[R>>>24]^h[D>>16&255]^d[_>>8&255]^c[I&255]^n[w],y=l[D>>>24]^h[_>>16&255]^d[I>>8&255]^c[R&255]^n[w+1],b=l[_>>>24]^h[I>>16&255]^d[R>>8&255]^c[D&255]^n[w+2],S=l[I>>>24]^h[R>>16&255]^d[D>>8&255]^c[_&255]^n[w+3],R=A,D=y,_=b,I=S,w=w+4;A=a[R>>>24]<<24^a[D>>16&255]<<16^a[_>>8&255]<<8^a[I&255]^n[w],y=a[D>>>24]<<24^a[_>>16&255]<<16^a[I>>8&255]<<8^a[R&255]^n[w+1],b=a[_>>>24]<<24^a[I>>16&255]<<16^a[R>>8&255]<<8^a[D&255]^n[w+2],S=a[I>>>24]<<24^a[R>>16&255]<<16^a[D>>8&255]<<8^a[_&255]^n[w+3],T[e]=U(A^f),T[e+1]=U(S^p),T[e+2]=U(b^g),T[e+3]=U(y^v),f=N,p=P,g=F,v=K,e=e+4}return T.buffer}}const hm=16;class ra{constructor(t,{removePKCS7Padding:e=!0}={}){if(this.logEnabled=!0,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.useSoftware=t.enableSoftwareAES,this.removePKCS7Padding=e,e)try{const i=self.crypto;i&&(this.subtle=i.subtle||i.webkitSubtle)}catch{}this.subtle===null&&(this.useSoftware=!0)}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(){const{currentResult:t,remainderData:e}=this;if(!t||e)return this.reset(),null;const i=new Uint8Array(t);return this.reset(),this.removePKCS7Padding?om(i):i}reset(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&(this.softwareDecrypter=null)}decrypt(t,e,i){return this.useSoftware?new Promise((s,n)=>{this.softwareDecrypt(new Uint8Array(t),e,i);const a=this.flush();a?s(a.buffer):n(new Error("[softwareDecrypt] Failed to decrypt data"))}):this.webCryptoDecrypt(new Uint8Array(t),e,i)}softwareDecrypt(t,e,i){const{currentIV:s,currentResult:n,remainderData:a}=this;this.logOnce("JS AES decrypt"),a&&(t=si(a,t),this.remainderData=null);const o=this.getValidChunk(t);if(!o.length)return null;s&&(i=s);let l=this.softwareDecrypter;l||(l=this.softwareDecrypter=new lm),l.expandKey(e);const h=n;return this.currentResult=l.decrypt(o.buffer,0,i),this.currentIV=ii(o,-16).buffer,h||null}webCryptoDecrypt(t,e,i){const s=this.subtle;return(this.key!==e||!this.fastAesKey)&&(this.key=e,this.fastAesKey=new am(s,e)),this.fastAesKey.expandKey().then(n=>s?(this.logOnce("WebCrypto AES decrypt"),new nm(s,new Uint8Array(i)).decrypt(t.buffer,n)):Promise.reject(new Error("web crypto not initialized"))).catch(n=>(L.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${n.name}: ${n.message}`),this.onWebCryptoError(t,e,i)))}onWebCryptoError(t,e,i){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(t,e,i);const s=this.flush();if(s)return s.buffer;throw new Error("WebCrypto and softwareDecrypt: failed to decrypt data")}getValidChunk(t){let e=t;const i=t.length-t.length%hm;return i!==t.length&&(e=ii(t,0,i),this.remainderData=ii(t,i)),e}logOnce(t){this.logEnabled&&(L.log(`[decrypter]: ${t}`),this.logEnabled=!1)}}const dm={toString:function(r){let t="";const e=r.length;for(let i=0;i<e;i++)t+=`[${r.start(i).toFixed(3)}-${r.end(i).toFixed(3)}]`;return t}},$={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"};class na extends Zg{constructor(t,e,i,s,n){super(),this.hls=void 0,this.fragPrevious=null,this.fragCurrent=null,this.fragmentTracker=void 0,this.transmuxer=null,this._state=$.STOPPED,this.playlistType=void 0,this.media=null,this.mediaBuffer=null,this.config=void 0,this.bitrateTest=!1,this.lastCurrentTime=0,this.nextLoadPosition=0,this.startPosition=0,this.startTimeOffset=null,this.loadedmetadata=!1,this.retryDate=0,this.levels=null,this.fragmentLoader=void 0,this.keyLoader=void 0,this.levelLastLoaded=null,this.startFragRequested=!1,this.decrypter=void 0,this.initPTS=[],this.onvseeking=null,this.onvended=null,this.logPrefix="",this.log=void 0,this.warn=void 0,this.playlistType=n,this.logPrefix=s,this.log=L.log.bind(L,`${s}:`),this.warn=L.warn.bind(L,`${s}:`),this.hls=t,this.fragmentLoader=new Xg(t.config),this.keyLoader=i,this.fragmentTracker=e,this.config=t.config,this.decrypter=new ra(t.config),t.on(m.MANIFEST_LOADED,this.onManifestLoaded,this)}doTick(){this.onTickEnd()}onTickEnd(){}startLoad(t){}stopLoad(){this.fragmentLoader.abort(),this.keyLoader.abort(this.playlistType);const t=this.fragCurrent;t!=null&&t.loader&&(t.abortRequests(),this.fragmentTracker.removeFragment(t)),this.resetTransmuxer(),this.fragCurrent=null,this.fragPrevious=null,this.clearInterval(),this.clearNextTick(),this.state=$.STOPPED}_streamEnded(t,e){if(e.live||t.nextStart||!t.end||!this.media)return!1;const i=e.partList;if(i!=null&&i.length){const n=i[i.length-1];return lt.isBuffered(this.media,n.start+n.duration/2)}const s=e.fragments[e.fragments.length-1].type;return this.fragmentTracker.isEndListAppended(s)}getLevelDetails(){if(this.levels&&this.levelLastLoaded!==null){var t;return(t=this.levels[this.levelLastLoaded])==null?void 0:t.details}}onMediaAttached(t,e){const i=this.media=this.mediaBuffer=e.media;this.onvseeking=this.onMediaSeeking.bind(this),this.onvended=this.onMediaEnded.bind(this),i.addEventListener("seeking",this.onvseeking),i.addEventListener("ended",this.onvended);const s=this.config;this.levels&&s.autoStartLoad&&this.state===$.STOPPED&&this.startLoad(s.startPosition)}onMediaDetaching(){const t=this.media;t!=null&&t.ended&&(this.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0),t&&this.onvseeking&&this.onvended&&(t.removeEventListener("seeking",this.onvseeking),t.removeEventListener("ended",this.onvended),this.onvseeking=this.onvended=null),this.keyLoader&&this.keyLoader.detach(),this.media=this.mediaBuffer=null,this.loadedmetadata=!1,this.fragmentTracker.removeAllFragments(),this.stopLoad()}onMediaSeeking(){const{config:t,fragCurrent:e,media:i,mediaBuffer:s,state:n}=this,a=i?i.currentTime:0,o=lt.bufferInfo(s||i,a,t.maxBufferHole);if(this.log(`media seeking to ${j(a)?a.toFixed(3):a}, state: ${n}`),this.state===$.ENDED)this.resetLoadingState();else if(e){const l=t.maxFragLookUpTolerance,h=e.start-l,d=e.start+e.duration+l;if(!o.len||d<o.start||h>o.end){const c=a>d;(a<h||c)&&(c&&e.loader&&(this.log("seeking outside of buffer while fragment load in progress, cancel fragment load"),e.abortRequests(),this.resetLoadingState()),this.fragPrevious=null)}}i&&(this.fragmentTracker.removeFragmentsInRange(a,1/0,this.playlistType,!0),this.lastCurrentTime=a),!this.loadedmetadata&&!o.len&&(this.nextLoadPosition=this.startPosition=a),this.tickImmediate()}onMediaEnded(){this.startPosition=this.lastCurrentTime=0}onManifestLoaded(t,e){this.startTimeOffset=e.startTimeOffset,this.initPTS=[]}onHandlerDestroying(){this.stopLoad(),super.onHandlerDestroying()}onHandlerDestroyed(){this.state=$.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(t,e,i){this._loadFragForPlayback(t,e,i)}_loadFragForPlayback(t,e,i){const s=n=>{if(this.fragContextChanged(t)){this.warn(`Fragment ${t.sn}${n.part?" p: "+n.part.index:""} of level ${t.level} was dropped during download.`),this.fragmentTracker.removeFragment(t);return}t.stats.chunkCount++,this._handleFragmentLoadProgress(n)};this._doFragLoad(t,e,i,s).then(n=>{if(!n)return;const a=this.state;if(this.fragContextChanged(t)){(a===$.FRAG_LOADING||!this.fragCurrent&&a===$.PARSING)&&(this.fragmentTracker.removeFragment(t),this.state=$.IDLE);return}"payload"in n&&(this.log(`Loaded fragment ${t.sn} of level ${t.level}`),this.hls.trigger(m.FRAG_LOADED,n)),this._handleFragmentLoadComplete(n)}).catch(n=>{this.state===$.STOPPED||this.state===$.ERROR||(this.warn(n),this.resetFragmentLoading(t))})}clearTrackerIfNeeded(t){var e;const{fragmentTracker:i}=this;if(i.getState(t)===Lt.APPENDING){const s=t.type,n=this.getFwdBufferInfo(this.mediaBuffer,s),a=Math.max(t.duration,n?n.len:this.config.maxBufferLength);this.reduceMaxBufferLength(a)&&i.removeFragment(t)}else((e=this.mediaBuffer)==null?void 0:e.buffered.length)===0?i.removeAllFragments():i.hasParts(t.type)&&(i.detectPartialFragments({frag:t,part:null,stats:t.stats,id:t.type}),i.getState(t)===Lt.PARTIAL&&i.removeFragment(t))}checkLiveUpdate(t){if(t.updated&&!t.live){const e=t.fragments[t.fragments.length-1];this.fragmentTracker.detectPartialFragments({frag:e,part:null,stats:e.stats,id:e.type})}t.fragments[0]||(t.deltaUpdateFailed=!0)}flushMainBuffer(t,e,i=null){if(!(t-e))return;const s={startOffset:t,endOffset:e,type:i};this.hls.trigger(m.BUFFER_FLUSHING,s)}_loadInitSegment(t,e){this._doFragLoad(t,e).then(i=>{if(!i||this.fragContextChanged(t)||!this.levels)throw new Error("init load aborted");return i}).then(i=>{const{hls:s}=this,{payload:n}=i,a=t.decryptdata;if(n&&n.byteLength>0&&a&&a.key&&a.iv&&a.method==="AES-128"){const o=self.performance.now();return this.decrypter.decrypt(new Uint8Array(n),a.key.buffer,a.iv.buffer).catch(l=>{throw s.trigger(m.ERROR,{type:W.MEDIA_ERROR,details:x.FRAG_DECRYPT_ERROR,fatal:!1,error:l,reason:l.message,frag:t}),l}).then(l=>{const h=self.performance.now();return s.trigger(m.FRAG_DECRYPTED,{frag:t,payload:l,stats:{tstart:o,tdecrypt:h}}),i.payload=l,i})}return i}).then(i=>{const{fragCurrent:s,hls:n,levels:a}=this;if(!a)throw new Error("init load aborted, missing levels");const o=t.stats;this.state=$.IDLE,e.fragmentError=0,t.data=new Uint8Array(i.payload),o.parsing.start=o.buffering.start=self.performance.now(),o.parsing.end=o.buffering.end=self.performance.now(),i.frag===s&&n.trigger(m.FRAG_BUFFERED,{stats:o,frag:s,part:null,id:t.type}),this.tick()}).catch(i=>{this.state===$.STOPPED||this.state===$.ERROR||(this.warn(i),this.resetFragmentLoading(t))})}fragContextChanged(t){const{fragCurrent:e}=this;return!t||!e||t.level!==e.level||t.sn!==e.sn||t.urlId!==e.urlId}fragBufferedComplete(t,e){var i,s,n,a;const o=this.mediaBuffer?this.mediaBuffer:this.media;this.log(`Buffered ${t.type} sn: ${t.sn}${e?" part: "+e.index:""} of ${this.playlistType===Y.MAIN?"level":"track"} ${t.level} (frag:[${((i=t.startPTS)!=null?i:NaN).toFixed(3)}-${((s=t.endPTS)!=null?s:NaN).toFixed(3)}] > buffer:${o?dm.toString(lt.getBuffered(o)):"(detached)"})`),this.state=$.IDLE,o&&(!this.loadedmetadata&&t.type==Y.MAIN&&o.buffered.length&&((n=this.fragCurrent)==null?void 0:n.sn)===((a=this.fragPrevious)==null?void 0:a.sn)&&(this.loadedmetadata=!0,this.seekToStartPos()),this.tick())}seekToStartPos(){}_handleFragmentLoadComplete(t){const{transmuxer:e}=this;if(!e)return;const{frag:i,part:s,partsLoaded:n}=t,a=!n||n.length===0||n.some(l=>!l),o=new ia(i.level,i.sn,i.stats.chunkCount+1,0,s?s.index:-1,!a);e.flush(o)}_handleFragmentLoadProgress(t){}_doFragLoad(t,e,i=null,s){var n;const a=e==null?void 0:e.details;if(!this.levels||!a)throw new Error(`frag load aborted, missing level${a?"":" detail"}s`);let o=null;if(t.encrypted&&!((n=t.decryptdata)!=null&&n.key)?(this.log(`Loading key for ${t.sn} of [${a.startSN}-${a.endSN}], ${this.logPrefix==="[stream-controller]"?"level":"track"} ${t.level}`),this.state=$.KEY_LOADING,this.fragCurrent=t,o=this.keyLoader.load(t).then(d=>{if(!this.fragContextChanged(d.frag))return this.hls.trigger(m.KEY_LOADED,d),this.state===$.KEY_LOADING&&(this.state=$.IDLE),d}),this.hls.trigger(m.KEY_LOADING,{frag:t}),this.fragCurrent===null&&(o=Promise.reject(new Error("frag load aborted, context changed in KEY_LOADING")))):!t.encrypted&&a.encryptedFragments.length&&this.keyLoader.loadClear(t,a.encryptedFragments),i=Math.max(t.start,i||0),this.config.lowLatencyMode&&t.sn!=="initSegment"){const d=a.partList;if(d&&s){i>t.end&&a.fragmentHint&&(t=a.fragmentHint);const c=this.getNextPart(d,t,i);if(c>-1){const u=d[c];this.log(`Loading part sn: ${t.sn} p: ${u.index} cc: ${t.cc} of playlist [${a.startSN}-${a.endSN}] parts [0-${c}-${d.length-1}] ${this.logPrefix==="[stream-controller]"?"level":"track"}: ${t.level}, target: ${parseFloat(i.toFixed(3))}`),this.nextLoadPosition=u.start+u.duration,this.state=$.FRAG_LOADING;let f;return o?f=o.then(p=>!p||this.fragContextChanged(p.frag)?null:this.doFragPartsLoad(t,u,e,s)).catch(p=>this.handleFragLoadError(p)):f=this.doFragPartsLoad(t,u,e,s).catch(p=>this.handleFragLoadError(p)),this.hls.trigger(m.FRAG_LOADING,{frag:t,part:u,targetBufferTime:i}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):f}else if(!t.url||this.loadedEndOfParts(d,i))return Promise.resolve(null)}}this.log(`Loading fragment ${t.sn} cc: ${t.cc} ${a?"of ["+a.startSN+"-"+a.endSN+"] ":""}${this.logPrefix==="[stream-controller]"?"level":"track"}: ${t.level}, target: ${parseFloat(i.toFixed(3))}`),j(t.sn)&&!this.bitrateTest&&(this.nextLoadPosition=t.start+t.duration),this.state=$.FRAG_LOADING;const l=this.config.progressive;let h;return l&&o?h=o.then(d=>!d||this.fragContextChanged(d==null?void 0:d.frag)?null:this.fragmentLoader.load(t,s)).catch(d=>this.handleFragLoadError(d)):h=Promise.all([this.fragmentLoader.load(t,l?s:void 0),o]).then(([d])=>(!l&&d&&s&&s(d),d)).catch(d=>this.handleFragLoadError(d)),this.hls.trigger(m.FRAG_LOADING,{frag:t,targetBufferTime:i}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):h}doFragPartsLoad(t,e,i,s){return new Promise((n,a)=>{var o;const l=[],h=(o=i.details)==null?void 0:o.partList,d=c=>{this.fragmentLoader.loadPart(t,c,s).then(u=>{l[c.index]=u;const f=u.part;this.hls.trigger(m.FRAG_LOADED,u);const p=Dh(i,t.sn,c.index+1)||xh(h,t.sn,c.index+1);if(p)d(p);else return n({frag:t,part:f,partsLoaded:l})}).catch(a)};d(e)})}handleFragLoadError(t){if("data"in t){const e=t.data;t.data&&e.details===x.INTERNAL_ABORTED?this.handleFragLoadAborted(e.frag,e.part):this.hls.trigger(m.ERROR,e)}else this.hls.trigger(m.ERROR,{type:W.OTHER_ERROR,details:x.INTERNAL_EXCEPTION,err:t,error:t,fatal:!0});return null}_handleTransmuxerFlush(t){const e=this.getCurrentContext(t);if(!e||this.state!==$.PARSING){!this.fragCurrent&&this.state!==$.STOPPED&&this.state!==$.ERROR&&(this.state=$.IDLE);return}const{frag:i,part:s,level:n}=e,a=self.performance.now();i.stats.parsing.end=a,s&&(s.stats.parsing.end=a),this.updateLevelTiming(i,s,n,t.partial)}getCurrentContext(t){const{levels:e,fragCurrent:i}=this,{level:s,sn:n,part:a}=t;if(!(e!=null&&e[s]))return this.warn(`Levels object was unset while buffering fragment ${n} of level ${s}. The current chunk will not be buffered.`),null;const o=e[s],l=a>-1?Dh(o,n,a):null,h=l?l.fragment:Bg(o,n,i);return h?(i&&i!==h&&(h.stats=i.stats),{frag:h,part:l,level:o}):null}bufferFragmentData(t,e,i,s,n){var a;if(!t||this.state!==$.PARSING)return;const{data1:o,data2:l}=t;let h=o;if(o&&l&&(h=si(o,l)),!((a=h)!=null&&a.length))return;const d={type:t.type,frag:e,part:i,chunkMeta:s,parent:e.type,data:h};if(this.hls.trigger(m.BUFFER_APPENDING,d),t.dropped&&t.independent&&!i){if(n)return;this.flushBufferGap(e)}}flushBufferGap(t){const e=this.media;if(!e)return;if(!lt.isBuffered(e,e.currentTime)){this.flushMainBuffer(0,t.start);return}const i=e.currentTime,s=lt.bufferInfo(e,i,0),n=t.duration,a=Math.min(this.config.maxFragLookUpTolerance*2,n*.25),o=Math.max(Math.min(t.start-a,s.end-a),i+a);t.start-o>a&&this.flushMainBuffer(o,t.start)}getFwdBufferInfo(t,e){const i=this.getLoadPosition();return j(i)?this.getFwdBufferInfoAtPos(t,i,e):null}getFwdBufferInfoAtPos(t,e,i){const{config:{maxBufferHole:s}}=this,n=lt.bufferInfo(t,e,s);if(n.len===0&&n.nextStart!==void 0){const a=this.fragmentTracker.getBufferedFrag(e,i);if(a&&n.nextStart<a.end)return lt.bufferInfo(t,e,Math.max(n.nextStart,s))}return n}getMaxBufferLength(t){const{config:e}=this;let i;return t?i=Math.max(8*e.maxBufferSize/t,e.maxBufferLength):i=e.maxBufferLength,Math.min(i,e.maxMaxBufferLength)}reduceMaxBufferLength(t){const e=this.config,i=t||e.maxBufferLength;return e.maxMaxBufferLength>=i?(e.maxMaxBufferLength/=2,this.warn(`Reduce max buffer length to ${e.maxMaxBufferLength}s`),!0):!1}getAppendedFrag(t,e=Y.MAIN){const i=this.fragmentTracker.getAppendedFrag(t,Y.MAIN);return i&&"fragment"in i?i.fragment:i}getNextFragment(t,e){const i=e.fragments,s=i.length;if(!s)return null;const{config:n}=this,a=i[0].start;let o;if(e.live){const l=n.initialLiveManifestSize;if(s<l)return this.warn(`Not enough fragments to start playback (have: ${s}, need: ${l})`),null;!e.PTSKnown&&!this.startFragRequested&&this.startPosition===-1&&(o=this.getInitialLiveFragment(e,i),this.startPosition=o?this.hls.liveSyncPosition||o.start:t)}else t<=a&&(o=i[0]);if(!o){const l=n.lowLatencyMode?e.partEnd:e.fragmentEnd;o=this.getFragmentAtPosition(t,l,e)}return this.mapToInitFragWhenRequired(o)}isLoopLoading(t,e){const i=this.fragmentTracker.getState(t);return(i===Lt.OK||i===Lt.PARTIAL&&!!t.gap)&&this.nextLoadPosition>e}getNextFragmentLoopLoading(t,e,i,s,n){const a=t.gap,o=this.getNextFragment(this.nextLoadPosition,e);if(o===null)return o;if(t=o,a&&t&&!t.gap&&i.nextStart){const l=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,i.nextStart,s);if(l!==null&&i.len+l.len>=n)return this.log(`buffer full after gaps in "${s}" playlist starting at sn: ${t.sn}`),null}return t}mapToInitFragWhenRequired(t){return t!=null&&t.initSegment&&!(t!=null&&t.initSegment.data)&&!this.bitrateTest?t.initSegment:t}getNextPart(t,e,i){let s=-1,n=!1,a=!0;for(let o=0,l=t.length;o<l;o++){const h=t[o];if(a=a&&!h.independent,s>-1&&i<h.start)break;const d=h.loaded;d?s=-1:(n||h.independent||a)&&h.fragment===e&&(s=o),n=d}return s}loadedEndOfParts(t,e){const i=t[t.length-1];return i&&e>i.start&&i.loaded}getInitialLiveFragment(t,e){const i=this.fragPrevious;let s=null;if(i){if(t.hasProgramDateTime&&(this.log(`Live playlist, switching playlist, load frag with same PDT: ${i.programDateTime}`),s=Gg(e,i.endProgramDateTime,this.config.maxFragLookUpTolerance)),!s){const n=i.sn+1;if(n>=t.startSN&&n<=t.endSN){const a=e[n-t.startSN];i.cc===a.cc&&(s=a,this.log(`Live playlist, switching playlist, load frag with next SN: ${s.sn}`))}s||(s=Kg(e,i.cc),s&&this.log(`Live playlist, switching playlist, load frag with same CC: ${s.sn}`))}}else{const n=this.hls.liveSyncPosition;n!==null&&(s=this.getFragmentAtPosition(n,this.bitrateTest?t.fragmentEnd:t.edge,t))}return s}getFragmentAtPosition(t,e,i){const{config:s}=this;let{fragPrevious:n}=this,{fragments:a,endSN:o}=i;const{fragmentHint:l}=i,h=s.maxFragLookUpTolerance,d=i.partList,c=!!(s.lowLatencyMode&&d!=null&&d.length&&l);c&&l&&!this.bitrateTest&&(a=a.concat(l),o=l.sn);let u;if(t<e){const f=t>e-h?0:h;u=gs(n,a,t,f)}else u=a[a.length-1];if(u){const f=u.sn-i.startSN,p=this.fragmentTracker.getState(u);if((p===Lt.OK||p===Lt.PARTIAL&&u.gap)&&(n=u),n&&u.sn===n.sn&&(!c||d[0].fragment.sn>u.sn)&&n&&u.level===n.level){const g=a[f+1];u.sn<o&&this.fragmentTracker.getState(g)!==Lt.OK?u=g:u=null}}return u}synchronizeToLiveEdge(t){const{config:e,media:i}=this;if(!i)return;const s=this.hls.liveSyncPosition,n=i.currentTime,a=t.fragments[0].start,o=t.edge,l=n>=a-e.maxFragLookUpTolerance&&n<=o;if(s!==null&&i.duration>s&&(n<s||!l)){const h=e.liveMaxLatencyDuration!==void 0?e.liveMaxLatencyDuration:e.liveMaxLatencyDurationCount*t.targetduration;(!l&&i.readyState<4||n<o-h)&&(this.loadedmetadata||(this.nextLoadPosition=s),i.readyState&&(this.warn(`Playback: ${n.toFixed(3)} is located too far from the end of live sliding playlist: ${o}, reset currentTime to : ${s.toFixed(3)}`),i.currentTime=s))}}alignPlaylists(t,e){const{levels:i,levelLastLoaded:s,fragPrevious:n}=this,a=s!==null?i[s]:null,o=t.fragments.length;if(!o)return this.warn("No fragments in live playlist"),0;const l=t.fragments[0].start,h=!e,d=t.alignedSliding&&j(l);if(h||!d&&!l){im(n,a,t);const c=t.fragments[0].start;return this.log(`Live playlist sliding: ${c.toFixed(2)} start-sn: ${e?e.startSN:"na"}->${t.startSN} prev-sn: ${n?n.sn:"na"} fragments: ${o}`),c}return l}waitForCdnTuneIn(t){return t.live&&t.canBlockReload&&t.partTarget&&t.tuneInGoal>Math.max(t.partHoldBack,t.partTarget*3)}setStartPosition(t,e){let i=this.startPosition;if(i<e&&(i=-1),i===-1||this.lastCurrentTime===-1){const s=this.startTimeOffset!==null,n=s?this.startTimeOffset:t.startTimeOffset;n!==null&&j(n)?(i=e+n,n<0&&(i+=t.totalduration),i=Math.min(Math.max(e,i),e+t.totalduration),this.log(`Start time offset ${n} found in ${s?"multivariant":"media"} playlist, adjust startPosition to ${i}`),this.startPosition=i):t.live?i=this.hls.liveSyncPosition||e:this.startPosition=i=0,this.lastCurrentTime=i}this.nextLoadPosition=i}getLoadPosition(){const{media:t}=this;let e=0;return this.loadedmetadata&&t?e=t.currentTime:this.nextLoadPosition&&(e=this.nextLoadPosition),e}handleFragLoadAborted(t,e){this.transmuxer&&t.sn!=="initSegment"&&t.stats.aborted&&(this.warn(`Fragment ${t.sn}${e?" part "+e.index:""} of level ${t.level} was aborted`),this.resetFragmentLoading(t))}resetFragmentLoading(t){(!this.fragCurrent||!this.fragContextChanged(t)&&this.state!==$.FRAG_LOADING_WAITING_RETRY)&&(this.state=$.IDLE)}onFragmentOrKeyLoadError(t,e){if(e.chunkMeta&&!e.frag){const c=this.getCurrentContext(e.chunkMeta);c&&(e.frag=c.frag)}const i=e.frag;if(!i||i.type!==t||!this.levels)return;if(this.fragContextChanged(i)){var s;this.warn(`Frag load error must match current frag to retry ${i.url} > ${(s=this.fragCurrent)==null?void 0:s.url}`);return}const n=e.details===x.FRAG_GAP;n&&this.fragmentTracker.fragBuffered(i,!0);const a=e.errorAction,{action:o,retryCount:l=0,retryConfig:h}=a||{};if(a&&o===Ot.RetryRequest&&h){var d;this.resetStartWhenNotLoaded((d=this.levelLastLoaded)!=null?d:i.level);const c=Zn(h,l);this.warn(`Fragment ${i.sn} of ${t} ${i.level} errored with ${e.details}, retrying loading ${l+1}/${h.maxNumRetry} in ${c}ms`),a.resolved=!0,this.retryDate=self.performance.now()+c,this.state=$.FRAG_LOADING_WAITING_RETRY}else h&&a?(this.resetFragmentErrors(t),l<h.maxNumRetry?n||(a.resolved=!0):L.warn(`${e.details} reached or exceeded max retry (${l})`)):(a==null?void 0:a.action)===Ot.SendAlternateToPenaltyBox?this.state=$.WAITING_LEVEL:this.state=$.ERROR;this.tickImmediate()}reduceLengthAndFlushBuffer(t){if(this.state===$.PARSING||this.state===$.PARSED){const e=t.parent,i=this.getFwdBufferInfo(this.mediaBuffer,e),s=i&&i.len>.5;s&&this.reduceMaxBufferLength(i.len);const n=!s;return n&&this.warn(`Buffer full error while media.currentTime is not buffered, flush ${e} buffer`),t.frag&&(this.fragmentTracker.removeFragment(t.frag),this.nextLoadPosition=t.frag.start),this.resetLoadingState(),n}return!1}resetFragmentErrors(t){t===Y.AUDIO&&(this.fragCurrent=null),this.loadedmetadata||(this.startFragRequested=!1),this.state!==$.STOPPED&&(this.state=$.IDLE)}afterBufferFlushed(t,e,i){if(!t)return;const s=lt.getBuffered(t);this.fragmentTracker.detectEvictedFragments(e,s,i),this.state===$.ENDED&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state=$.IDLE}resetStartWhenNotLoaded(t){if(!this.loadedmetadata){this.startFragRequested=!1;const e=this.levels?this.levels[t].details:null;e!=null&&e.live?(this.startPosition=-1,this.setStartPosition(e,0),this.resetLoadingState()):this.nextLoadPosition=this.startPosition}}resetWhenMissingContext(t){var e;this.warn(`The loading context changed while buffering fragment ${t.sn} of level ${t.level}. This chunk will not be buffered.`),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded((e=this.levelLastLoaded)!=null?e:t.level),this.resetLoadingState()}removeUnbufferedFrags(t=0){this.fragmentTracker.removeFragmentsInRange(t,1/0,this.playlistType,!1,!0)}updateLevelTiming(t,e,i,s){var n;const a=i.details;if(!a){this.warn("level.details undefined");return}if(Object.keys(t.elementaryStreams).reduce((o,l)=>{const h=t.elementaryStreams[l];if(h){const d=h.endPTS-h.startPTS;if(d<=0)return this.warn(`Could not parse fragment ${t.sn} ${l} duration reliably (${d})`),o||!1;const c=s?0:kh(a,t,h.startPTS,h.endPTS,h.startDTS,h.endDTS);return this.hls.trigger(m.LEVEL_PTS_UPDATED,{details:a,level:i,drift:c,type:l,frag:t,start:h.startPTS,end:h.endPTS}),!0}return o},!1))i.fragmentError=0;else if(((n=this.transmuxer)==null?void 0:n.error)===null){const o=new Error(`Found no media in fragment ${t.sn} of level ${t.level} resetting transmuxer to fallback to playlist timing`);if(i.fragmentError===0&&(i.fragmentError++,t.gap=!0,this.fragmentTracker.removeFragment(t),this.fragmentTracker.fragBuffered(t,!0)),this.warn(o.message),this.hls.trigger(m.ERROR,{type:W.MEDIA_ERROR,details:x.FRAG_PARSING_ERROR,fatal:!1,error:o,frag:t,reason:`Found no media in msn ${t.sn} of level "${i.url}"`}),!this.hls)return;this.resetTransmuxer()}this.state=$.PARSED,this.hls.trigger(m.FRAG_PARSED,{frag:t,part:e})}resetTransmuxer(){this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null)}recoverWorkerError(t){if(t.event==="demuxerWorker"){var e,i,s;this.fragmentTracker.removeAllFragments(),this.resetTransmuxer(),this.resetStartWhenNotLoaded((e=(i=this.levelLastLoaded)!=null?i:(s=this.fragCurrent)==null?void 0:s.level)!=null?e:0),this.resetLoadingState()}}set state(t){const e=this._state;e!==t&&(this._state=t,this.log(`${e}->${t}`))}get state(){return this._state}}function Vh(){return self.SourceBuffer||self.WebKitSourceBuffer}function cm(){const r=lr();if(!r)return!1;const t=Vh(),e=r&&typeof r.isTypeSupported=="function"&&r.isTypeSupported('video/mp4; codecs="avc1.42E01E,mp4a.40.2"'),i=!t||t.prototype&&typeof t.prototype.appendBuffer=="function"&&typeof t.prototype.remove=="function";return!!e&&!!i}function um(){var r;const t=Vh();return typeof(t==null||(r=t.prototype)==null?void 0:r.changeType)=="function"}function fm(){return typeof __HLS_WORKER_BUNDLE__=="function"}function pm(){const r=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(r);return{worker:new self.Worker(t),objectURL:t}}function gm(r){const t=new self.URL(r,self.location.href).href;return{worker:new self.Worker(t),scriptURL:t}}function ve(r="",t=9e4){return{type:r,id:-1,pid:-1,inputTimeScale:t,sequenceNumber:-1,samples:[],dropped:0}}class Kh{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(t,e,i,s){this._id3Track={type:"id3",id:3,pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0}}resetTimeStamp(t){this.initPTS=t,this.resetContiguity()}resetContiguity(){this.basePTS=null,this.lastPTS=null,this.frameIndex=0}canParse(t,e){return!1}appendFrame(t,e,i){}demux(t,e){this.cachedData&&(t=si(this.cachedData,t),this.cachedData=null);let i=rr(t,0),s=i?i.length:0,n;const a=this._audioTrack,o=this._id3Track,l=i?Qp(i):void 0,h=t.length;for((this.basePTS===null||this.frameIndex===0&&j(l))&&(this.basePTS=mm(l,e,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:ae.audioId3,duration:Number.POSITIVE_INFINITY});s<h;){if(this.canParse(t,s)){const d=this.appendFrame(a,t,s);d?(this.frameIndex++,this.lastPTS=d.sample.pts,s+=d.length,n=s):s=h}else Xp(t,s)?(i=rr(t,s),o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:i,type:ae.audioId3,duration:Number.POSITIVE_INFINITY}),s+=i.length,n=s):s++;if(s===h&&n!==h){const d=ii(t,n);this.cachedData?this.cachedData=si(this.cachedData,d):this.cachedData=d}}return{audioTrack:a,videoTrack:ve(),id3Track:o,textTrack:ve()}}demuxSampleAes(t,e,i){return Promise.reject(new Error(`[${this}] This demuxer does not support Sample-AES decryption`))}flush(t){const e=this.cachedData;return e&&(this.cachedData=null,this.demux(e,0)),{audioTrack:this._audioTrack,videoTrack:ve(),id3Track:this._id3Track,textTrack:ve()}}destroy(){}}const mm=(r,t,e)=>{if(j(r))return r*90;const i=e?e.baseTime*9e4/e.timescale:0;return t*9e4+i};function vm(r,t,e,i){let s,n,a,o;const l=navigator.userAgent.toLowerCase(),h=i,d=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350];s=((t[e+2]&192)>>>6)+1;const c=(t[e+2]&60)>>>2;if(c>d.length-1){r.trigger(m.ERROR,{type:W.MEDIA_ERROR,details:x.FRAG_PARSING_ERROR,fatal:!0,reason:`invalid ADTS sampling index:${c}`});return}return a=(t[e+2]&1)<<2,a|=(t[e+3]&192)>>>6,L.log(`manifest codec:${i}, ADTS type:${s}, samplingIndex:${c}`),/firefox/i.test(l)?c>=6?(s=5,o=new Array(4),n=c-3):(s=2,o=new Array(2),n=c):l.indexOf("android")!==-1?(s=2,o=new Array(2),n=c):(s=5,o=new Array(4),i&&(i.indexOf("mp4a.40.29")!==-1||i.indexOf("mp4a.40.5")!==-1)||!i&&c>=6?n=c-3:((i&&i.indexOf("mp4a.40.2")!==-1&&(c>=6&&a===1||/vivaldi/i.test(l))||!i&&a===1)&&(s=2,o=new Array(2)),n=c)),o[0]=s<<3,o[0]|=(c&14)>>1,o[1]|=(c&1)<<7,o[1]|=a<<3,s===5&&(o[1]|=(n&14)>>1,o[2]=(n&1)<<7,o[2]|=8,o[3]=0),{config:o,samplerate:d[c],channelCount:a,codec:"mp4a.40."+s,manifestCodec:h}}function jh(r,t){return r[t]===255&&(r[t+1]&246)===240}function Wh(r,t){return r[t+1]&1?7:9}function aa(r,t){return(r[t+3]&3)<<11|r[t+4]<<3|(r[t+5]&224)>>>5}function ym(r,t){return t+5<r.length}function gr(r,t){return t+1<r.length&&jh(r,t)}function Em(r,t){return ym(r,t)&&jh(r,t)&&aa(r,t)<=r.length-t}function Tm(r,t){if(gr(r,t)){const e=Wh(r,t);if(t+e>=r.length)return!1;const i=aa(r,t);if(i<=e)return!1;const s=t+i;return s===r.length||gr(r,s)}return!1}function Yh(r,t,e,i,s){if(!r.samplerate){const n=vm(t,e,i,s);if(!n)return;r.config=n.config,r.samplerate=n.samplerate,r.channelCount=n.channelCount,r.codec=n.codec,r.manifestCodec=n.manifestCodec,L.log(`parsed codec:${r.codec}, rate:${n.samplerate}, channels:${n.channelCount}`)}}function zh(r){return 9216e4/r}function bm(r,t){const e=Wh(r,t);if(t+e<=r.length){const i=aa(r,t)-e;if(i>0)return{headerLength:e,frameLength:i}}}function qh(r,t,e,i,s){const n=zh(r.samplerate),a=i+s*n,o=bm(t,e);let l;if(o){const{frameLength:d,headerLength:c}=o,u=c+d,f=Math.max(0,e+u-t.length);f?(l=new Uint8Array(u-c),l.set(t.subarray(e+c,t.length),0)):l=t.subarray(e+c,e+u);const p={unit:l,pts:a};return f||r.samples.push(p),{sample:p,length:u,missing:f}}const h=t.length-e;return l=new Uint8Array(h),l.set(t.subarray(e,t.length),0),{sample:{unit:l,pts:a},length:h,missing:-1}}class Am extends Kh{constructor(t,e){super(),this.observer=void 0,this.config=void 0,this.observer=t,this.config=e}resetInitSegment(t,e,i,s){super.resetInitSegment(t,e,i,s),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:e,duration:s,inputTimeScale:9e4,dropped:0}}static probe(t){if(!t)return!1;let e=(rr(t,0)||[]).length;for(let i=t.length;e<i;e++)if(Tm(t,e))return L.log("ADTS sync word found !"),!0;return!1}canParse(t,e){return Em(t,e)}appendFrame(t,e,i){Yh(t,this.observer,e,i,t.manifestCodec);const s=qh(t,e,i,this.basePTS,this.frameIndex);if(s&&s.missing===0)return s}}const wm=/\/emsg[-/]ID3/i;class Sm{constructor(t,e){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=e}resetTimeStamp(){}resetInitSegment(t,e,i,s){const n=this.videoTrack=ve("video",1),a=this.audioTrack=ve("audio",1),o=this.txtTrack=ve("text",1);if(this.id3Track=ve("id3",1),this.timeOffset=0,!(t!=null&&t.byteLength))return;const l=oh(t);if(l.video){const{id:h,timescale:d,codec:c}=l.video;n.id=h,n.timescale=o.timescale=d,n.codec=c}if(l.audio){const{id:h,timescale:d,codec:c}=l.audio;a.id=h,a.timescale=d,a.codec=c}o.id=rh.text,n.sampleDuration=0,n.duration=a.duration=s}resetContiguity(){this.remainderData=null}static probe(t){return t=t.length>16384?t.subarray(0,16384):t,et(t,["moof"]).length>0}demux(t,e){this.timeOffset=e;let i=t;const s=this.videoTrack,n=this.txtTrack;if(this.config.progressive){this.remainderData&&(i=si(this.remainderData,t));const o=ug(i);this.remainderData=o.remainder,s.samples=o.valid||new Uint8Array}else s.samples=i;const a=this.extractID3Track(s,e);return n.samples=hh(e,s),{videoTrack:s,audioTrack:this.audioTrack,id3Track:a,textTrack:this.txtTrack}}flush(){const t=this.timeOffset,e=this.videoTrack,i=this.txtTrack;e.samples=this.remainderData||new Uint8Array,this.remainderData=null;const s=this.extractID3Track(e,this.timeOffset);return i.samples=hh(t,e),{videoTrack:e,audioTrack:ve(),id3Track:s,textTrack:ve()}}extractID3Track(t,e){const i=this.id3Track;if(t.samples.length){const s=et(t.samples,["emsg"]);s&&s.forEach(n=>{const a=gg(n);if(wm.test(a.schemeIdUri)){const o=j(a.presentationTime)?a.presentationTime/a.timeScale:e+a.presentationTimeDelta/a.timeScale;let l=a.eventDuration===4294967295?Number.POSITIVE_INFINITY:a.eventDuration/a.timeScale;l<=.001&&(l=Number.POSITIVE_INFINITY);const h=a.payload;i.samples.push({data:h,len:h.byteLength,dts:o,pts:o,type:ae.emsg,duration:l})}})}return i}demuxSampleAes(t,e,i){return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"))}destroy(){}}let mr=null;const Lm=[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],Rm=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],_m=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],Im=[0,1,1,4];function Xh(r,t,e,i,s){if(e+24>t.length)return;const n=Qh(t,e);if(n&&e+n.frameLength<=t.length){const a=n.samplesPerFrame*9e4/n.sampleRate,o=i+s*a,l={unit:t.subarray(e,e+n.frameLength),pts:o,dts:o};return r.config=[],r.channelCount=n.channelCount,r.samplerate=n.sampleRate,r.samples.push(l),{sample:l,length:n.frameLength,missing:0}}}function Qh(r,t){const e=r[t+1]>>3&3,i=r[t+1]>>1&3,s=r[t+2]>>4&15,n=r[t+2]>>2&3;if(e!==1&&s!==0&&s!==15&&n!==3){const a=r[t+2]>>1&1,o=r[t+3]>>6,l=e===3?3-i:i===3?3:4,h=Lm[l*14+s-1]*1e3,d=Rm[(e===3?0:e===2?1:2)*3+n],c=o===3?1:2,u=_m[e][i],f=Im[i],p=u*8*f,g=Math.floor(u*h/d+a)*f;if(mr===null){const v=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);mr=v?parseInt(v[1]):0}return mr&&mr<=87&&i===2&&h>=224e3&&o===0&&(r[t+3]=r[t+3]|128),{sampleRate:d,channelCount:c,frameLength:g,samplesPerFrame:p}}}function oa(r,t){return r[t]===255&&(r[t+1]&224)===224&&(r[t+1]&6)!==0}function Zh(r,t){return t+1<r.length&&oa(r,t)}function km(r,t){return oa(r,t)&&4<=r.length-t}function Cm(r,t){if(t+1<r.length&&oa(r,t)){const e=Qh(r,t);let i=4;e!=null&&e.frameLength&&(i=e.frameLength);const s=t+i;return s===r.length||Zh(r,s)}return!1}class Jh{constructor(t){this.data=void 0,this.bytesAvailable=void 0,this.word=void 0,this.bitsAvailable=void 0,this.data=t,this.bytesAvailable=t.byteLength,this.word=0,this.bitsAvailable=0}loadWord(){const t=this.data,e=this.bytesAvailable,i=t.byteLength-e,s=new Uint8Array(4),n=Math.min(4,e);if(n===0)throw new Error("no bytes available");s.set(t.subarray(i,i+n)),this.word=new DataView(s.buffer).getUint32(0),this.bitsAvailable=n*8,this.bytesAvailable-=n}skipBits(t){let e;t=Math.min(t,this.bytesAvailable*8+this.bitsAvailable),this.bitsAvailable>t?(this.word<<=t,this.bitsAvailable-=t):(t-=this.bitsAvailable,e=t>>3,t-=e<<3,this.bytesAvailable-=e,this.loadWord(),this.word<<=t,this.bitsAvailable-=t)}readBits(t){let e=Math.min(this.bitsAvailable,t);const i=this.word>>>32-e;if(t>32&&L.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=e,this.bitsAvailable>0)this.word<<=e;else if(this.bytesAvailable>0)this.loadWord();else throw new Error("no bits available");return e=t-e,e>0&&this.bitsAvailable?i<<e|this.readBits(e):i}skipLZ(){let t;for(t=0;t<this.bitsAvailable;++t)if(this.word&2147483648>>>t)return this.word<<=t,this.bitsAvailable-=t,t;return this.loadWord(),t+this.skipLZ()}skipUEG(){this.skipBits(1+this.skipLZ())}skipEG(){this.skipBits(1+this.skipLZ())}readUEG(){const t=this.skipLZ();return this.readBits(t+1)-1}readEG(){const t=this.readUEG();return 1&t?1+t>>>1:-1*(t>>>1)}readBoolean(){return this.readBits(1)===1}readUByte(){return this.readBits(8)}readUShort(){return this.readBits(16)}readUInt(){return this.readBits(32)}skipScalingList(t){let e=8,i=8,s;for(let n=0;n<t;n++)i!==0&&(s=this.readEG(),i=(e+s+256)%256),e=i===0?e:i}readSPS(){let t=0,e=0,i=0,s=0,n,a,o;const l=this.readUByte.bind(this),h=this.readBits.bind(this),d=this.readUEG.bind(this),c=this.readBoolean.bind(this),u=this.skipBits.bind(this),f=this.skipEG.bind(this),p=this.skipUEG.bind(this),g=this.skipScalingList.bind(this);l();const v=l();if(h(5),u(3),l(),p(),v===100||v===110||v===122||v===244||v===44||v===83||v===86||v===118||v===128){const S=d();if(S===3&&u(1),p(),p(),u(1),c())for(a=S!==3?8:12,o=0;o<a;o++)c()&&(o<6?g(16):g(64))}p();const E=d();if(E===0)d();else if(E===1)for(u(1),f(),f(),n=d(),o=0;o<n;o++)f();p(),u(1);const T=d(),A=d(),y=h(1);y===0&&u(1),u(1),c()&&(t=d(),e=d(),i=d(),s=d());let b=[1,1];if(c()&&c())switch(l()){case 1:b=[1,1];break;case 2:b=[12,11];break;case 3:b=[10,11];break;case 4:b=[16,11];break;case 5:b=[40,33];break;case 6:b=[24,11];break;case 7:b=[20,11];break;case 8:b=[32,11];break;case 9:b=[80,33];break;case 10:b=[18,11];break;case 11:b=[15,11];break;case 12:b=[64,33];break;case 13:b=[160,99];break;case 14:b=[4,3];break;case 15:b=[3,2];break;case 16:b=[2,1];break;case 255:{b=[l()<<8|l(),l()<<8|l()];break}}return{width:Math.ceil((T+1)*16-t*2-e*2),height:(2-y)*(A+1)*16-(y?2:4)*(i+s),pixelRatio:b}}readSliceType(){return this.readUByte(),this.readUEG(),this.readUEG()}}class Dm{constructor(t,e,i){this.keyData=void 0,this.decrypter=void 0,this.keyData=i,this.decrypter=new ra(e,{removePKCS7Padding:!1})}decryptBuffer(t){return this.decrypter.decrypt(t,this.keyData.key.buffer,this.keyData.iv.buffer)}decryptAacSample(t,e,i){const s=t[e].unit;if(s.length<=16)return;const n=s.subarray(16,s.length-s.length%16),a=n.buffer.slice(n.byteOffset,n.byteOffset+n.length);this.decryptBuffer(a).then(o=>{const l=new Uint8Array(o);s.set(l,16),this.decrypter.isSync()||this.decryptAacSamples(t,e+1,i)})}decryptAacSamples(t,e,i){for(;;e++){if(e>=t.length){i();return}if(!(t[e].unit.length<32)&&(this.decryptAacSample(t,e,i),!this.decrypter.isSync()))return}}getAvcEncryptedData(t){const e=Math.floor((t.length-48)/160)*16+16,i=new Int8Array(e);let s=0;for(let n=32;n<t.length-16;n+=160,s+=16)i.set(t.subarray(n,n+16),s);return i}getAvcDecryptedUnit(t,e){const i=new Uint8Array(e);let s=0;for(let n=32;n<t.length-16;n+=160,s+=16)t.set(i.subarray(s,s+16),n);return t}decryptAvcSample(t,e,i,s,n){const a=ch(n.data),o=this.getAvcEncryptedData(a);this.decryptBuffer(o.buffer).then(l=>{n.data=this.getAvcDecryptedUnit(a,l),this.decrypter.isSync()||this.decryptAvcSamples(t,e,i+1,s)})}decryptAvcSamples(t,e,i,s){if(t instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;e++,i=0){if(e>=t.length){s();return}const n=t[e].units;for(;!(i>=n.length);i++){const a=n[i];if(!(a.data.length<=48||a.type!==1&&a.type!==5)&&(this.decryptAvcSample(t,e,i,s,a),!this.decrypter.isSync()))return}}}}const Mt=188;class Oe{constructor(t,e,i){this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.sampleAes=null,this.pmtParsed=!1,this.audioCodec=void 0,this.videoCodec=void 0,this._duration=0,this._pmtId=-1,this._avcTrack=void 0,this._audioTrack=void 0,this._id3Track=void 0,this._txtTrack=void 0,this.aacOverFlow=null,this.avcSample=null,this.remainderData=null,this.observer=t,this.config=e,this.typeSupported=i}static probe(t){const e=Oe.syncOffset(t);return e>0&&L.warn(`MPEG2-TS detected but first sync word found @ offset ${e}`),e!==-1}static syncOffset(t){const e=t.length;let i=Math.min(Mt*5,t.length-Mt)+1,s=0;for(;s<i;){let n=!1,a=-1,o=0;for(let l=s;l<e;l+=Mt)if(t[l]===71){if(o++,a===-1&&(a=l,a!==0&&(i=Math.min(a+Mt*99,t.length-Mt)+1)),n||(n=la(t,l)===0),n&&o>1&&(a===0&&o>2||l+Mt>i))return a}else{if(o)return-1;break}s++}return-1}static createTrack(t,e){return{container:t==="video"||t==="audio"?"video/mp2t":void 0,type:t,id:rh[t],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:t==="audio"?e:void 0}}resetInitSegment(t,e,i,s){this.pmtParsed=!1,this._pmtId=-1,this._avcTrack=Oe.createTrack("video"),this._audioTrack=Oe.createTrack("audio",s),this._id3Track=Oe.createTrack("id3"),this._txtTrack=Oe.createTrack("text"),this._audioTrack.segmentCodec="aac",this.aacOverFlow=null,this.avcSample=null,this.remainderData=null,this.audioCodec=e,this.videoCodec=i,this._duration=s}resetTimeStamp(){}resetContiguity(){const{_audioTrack:t,_avcTrack:e,_id3Track:i}=this;t&&(t.pesData=null),e&&(e.pesData=null),i&&(i.pesData=null),this.aacOverFlow=null,this.avcSample=null,this.remainderData=null}demux(t,e,i=!1,s=!1){i||(this.sampleAes=null);let n;const a=this._avcTrack,o=this._audioTrack,l=this._id3Track,h=this._txtTrack;let d=a.pid,c=a.pesData,u=o.pid,f=l.pid,p=o.pesData,g=l.pesData,v=null,E=this.pmtParsed,T=this._pmtId,A=t.length;if(this.remainderData&&(t=si(this.remainderData,t),A=t.length,this.remainderData=null),A<Mt&&!s)return this.remainderData=t,{audioTrack:o,videoTrack:a,id3Track:l,textTrack:h};const y=Math.max(0,Oe.syncOffset(t));A-=(A-y)%Mt,A<t.byteLength&&!s&&(this.remainderData=new Uint8Array(t.buffer,A,t.buffer.byteLength-A));let b=0;for(let R=y;R<A;R+=Mt)if(t[R]===71){const D=!!(t[R+1]&64),_=la(t,R),I=(t[R+3]&48)>>4;let N;if(I>1){if(N=R+5+t[R+4],N===R+Mt)continue}else N=R+4;switch(_){case d:D&&(c&&(n=wi(c))&&this.parseAVCPES(a,h,n,!1),c={data:[],size:0}),c&&(c.data.push(t.subarray(N,R+Mt)),c.size+=R+Mt-N);break;case u:if(D){if(p&&(n=wi(p)))switch(o.segmentCodec){case"aac":this.parseAACPES(o,n);break;case"mp3":this.parseMPEGPES(o,n);break}p={data:[],size:0}}p&&(p.data.push(t.subarray(N,R+Mt)),p.size+=R+Mt-N);break;case f:D&&(g&&(n=wi(g))&&this.parseID3PES(l,n),g={data:[],size:0}),g&&(g.data.push(t.subarray(N,R+Mt)),g.size+=R+Mt-N);break;case 0:D&&(N+=t[N]+1),T=this._pmtId=xm(t,N);break;case T:{D&&(N+=t[N]+1);const P=Pm(t,N,this.typeSupported,i);d=P.avc,d>0&&(a.pid=d),u=P.audio,u>0&&(o.pid=u,o.segmentCodec=P.segmentCodec),f=P.id3,f>0&&(l.pid=f),v!==null&&!E&&(L.warn(`MPEG-TS PMT found at ${R} after unknown PID '${v}'. Backtracking to sync byte @${y} to parse all TS packets.`),v=null,R=y-188),E=this.pmtParsed=!0;break}case 17:case 8191:break;default:v=_;break}}else b++;if(b>0){const R=new Error(`Found ${b} TS packet/s that do not start with 0x47`);this.observer.emit(m.ERROR,m.ERROR,{type:W.MEDIA_ERROR,details:x.FRAG_PARSING_ERROR,fatal:!1,error:R,reason:R.message})}a.pesData=c,o.pesData=p,l.pesData=g;const S={audioTrack:o,videoTrack:a,id3Track:l,textTrack:h};return s&&this.extractRemainingSamples(S),S}flush(){const{remainderData:t}=this;this.remainderData=null;let e;return t?e=this.demux(t,-1,!1,!0):e={videoTrack:this._avcTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(e),this.sampleAes?this.decrypt(e,this.sampleAes):e}extractRemainingSamples(t){const{audioTrack:e,videoTrack:i,id3Track:s,textTrack:n}=t,a=i.pesData,o=e.pesData,l=s.pesData;let h;if(a&&(h=wi(a))?(this.parseAVCPES(i,n,h,!0),i.pesData=null):i.pesData=a,o&&(h=wi(o))){switch(e.segmentCodec){case"aac":this.parseAACPES(e,h);break;case"mp3":this.parseMPEGPES(e,h);break}e.pesData=null}else o!=null&&o.size&&L.log("last AAC PES packet truncated,might overlap between fragments"),e.pesData=o;l&&(h=wi(l))?(this.parseID3PES(s,h),s.pesData=null):s.pesData=l}demuxSampleAes(t,e,i){const s=this.demux(t,i,!0,!this.config.progressive),n=this.sampleAes=new Dm(this.observer,this.config,e);return this.decrypt(s,n)}decrypt(t,e){return new Promise(i=>{const{audioTrack:s,videoTrack:n}=t;s.samples&&s.segmentCodec==="aac"?e.decryptAacSamples(s.samples,0,()=>{n.samples?e.decryptAvcSamples(n.samples,0,0,()=>{i(t)}):i(t)}):n.samples&&e.decryptAvcSamples(n.samples,0,0,()=>{i(t)})})}destroy(){this._duration=0}parseAVCPES(t,e,i,s){const n=this.parseAVCNALu(t,i.data);let a=this.avcSample,o,l=!1;i.data=null,a&&n.length&&!t.audFound&&(ms(a,t),a=this.avcSample=vr(!1,i.pts,i.dts,"")),n.forEach(h=>{var d;switch(h.type){case 1:{let u=!1;o=!0;const f=h.data;if(l&&f.length>4){const p=new Jh(f).readSliceType();(p===2||p===4||p===7||p===9)&&(u=!0)}if(u){var c;(c=a)!=null&&c.frame&&!a.key&&(ms(a,t),a=this.avcSample=null)}a||(a=this.avcSample=vr(!0,i.pts,i.dts,"")),a.frame=!0,a.key=u;break}case 5:o=!0,(d=a)!=null&&d.frame&&!a.key&&(ms(a,t),a=this.avcSample=null),a||(a=this.avcSample=vr(!0,i.pts,i.dts,"")),a.key=!0,a.frame=!0;break;case 6:{o=!0,dh(h.data,1,i.pts,e.samples);break}case 7:if(o=!0,l=!0,!t.sps){const u=h.data,f=new Jh(u).readSPS();t.width=f.width,t.height=f.height,t.pixelRatio=f.pixelRatio,t.sps=[u],t.duration=this._duration;const p=u.subarray(1,4);let g="avc1.";for(let v=0;v<3;v++){let E=p[v].toString(16);E.length<2&&(E="0"+E),g+=E}t.codec=g}break;case 8:o=!0,t.pps||(t.pps=[h.data]);break;case 9:o=!1,t.audFound=!0,a&&ms(a,t),a=this.avcSample=vr(!1,i.pts,i.dts,"");break;case 12:o=!0;break;default:o=!1,a&&(a.debug+="unknown NAL "+h.type+" ");break}a&&o&&a.units.push(h)}),s&&a&&(ms(a,t),this.avcSample=null)}getLastNalUnit(t){var e;let i=this.avcSample,s;if((!i||i.units.length===0)&&(i=t[t.length-1]),(e=i)!=null&&e.units){const n=i.units;s=n[n.length-1]}return s}parseAVCNALu(t,e){const i=e.byteLength;let s=t.naluState||0;const n=s,a=[];let o=0,l,h,d,c=-1,u=0;for(s===-1&&(c=0,u=e[0]&31,s=0,o=1);o<i;){if(l=e[o++],!s){s=l?0:1;continue}if(s===1){s=l?0:2;continue}if(!l)s=3;else if(l===1){if(c>=0){const f={data:e.subarray(c,o-s-1),type:u};a.push(f)}else{const f=this.getLastNalUnit(t.samples);if(f&&(n&&o<=4-n&&f.state&&(f.data=f.data.subarray(0,f.data.byteLength-n)),h=o-s-1,h>0)){const p=new Uint8Array(f.data.byteLength+h);p.set(f.data,0),p.set(e.subarray(0,h),f.data.byteLength),f.data=p,f.state=0}}o<i?(d=e[o]&31,c=o,u=d,s=0):s=-1}else s=0}if(c>=0&&s>=0){const f={data:e.subarray(c,i),type:u,state:s};a.push(f)}if(a.length===0){const f=this.getLastNalUnit(t.samples);if(f){const p=new Uint8Array(f.data.byteLength+e.byteLength);p.set(f.data,0),p.set(e,f.data.byteLength),f.data=p}}return t.naluState=s,a}parseAACPES(t,e){let i=0;const s=this.aacOverFlow;let n=e.data;if(s){this.aacOverFlow=null;const c=s.missing,u=s.sample.unit.byteLength;if(c===-1){const f=new Uint8Array(u+n.byteLength);f.set(s.sample.unit,0),f.set(n,u),n=f}else{const f=u-c;s.sample.unit.set(n.subarray(0,c),f),t.samples.push(s.sample),i=s.missing}}let a,o;for(a=i,o=n.length;a<o-1&&!gr(n,a);a++);if(a!==i){let c;const u=a<o-1;u?c=`AAC PES did not start with ADTS header,offset:${a}`:c="No ADTS header found in AAC PES";const f=new Error(c);if(L.warn(`parsing error: ${c}`),this.observer.emit(m.ERROR,m.ERROR,{type:W.MEDIA_ERROR,details:x.FRAG_PARSING_ERROR,fatal:!1,levelRetry:u,error:f,reason:c}),!u)return}Yh(t,this.observer,n,a,this.audioCodec);let l;if(e.pts!==void 0)l=e.pts;else if(s){const c=zh(t.samplerate);l=s.sample.pts+c}else{L.warn("[tsdemuxer]: AAC PES unknown PTS");return}let h=0,d;for(;a<o;)if(d=qh(t,n,a,l,h),a+=d.length,d.missing){this.aacOverFlow=d;break}else for(h++;a<o-1&&!gr(n,a);a++);}parseMPEGPES(t,e){const i=e.data,s=i.length;let n=0,a=0;const o=e.pts;if(o===void 0){L.warn("[tsdemuxer]: MPEG PES unknown PTS");return}for(;a<s;)if(Zh(i,a)){const l=Xh(t,i,a,o,n);if(l)a+=l.length,n++;else break}else a++}parseID3PES(t,e){if(e.pts===void 0){L.warn("[tsdemuxer]: ID3 PES unknown PTS");return}const i=At({},e,{type:this._avcTrack?ae.emsg:ae.audioId3,duration:Number.POSITIVE_INFINITY});t.samples.push(i)}}function vr(r,t,e,i){return{key:r,frame:!1,pts:t,dts:e,units:[],debug:i,length:0}}function la(r,t){return((r[t+1]&31)<<8)+r[t+2]}function xm(r,t){return(r[t+10]&31)<<8|r[t+11]}function Pm(r,t,e,i){const s={audio:-1,avc:-1,id3:-1,segmentCodec:"aac"},n=(r[t+1]&15)<<8|r[t+2],a=t+3+n-4,o=(r[t+10]&15)<<8|r[t+11];for(t+=12+o;t<a;){const l=la(r,t);switch(r[t]){case 207:if(!i){L.log("ADTS AAC with AES-128-CBC frame encryption found in unencrypted stream");break}case 15:s.audio===-1&&(s.audio=l);break;case 21:s.id3===-1&&(s.id3=l);break;case 219:if(!i){L.log("H.264 with AES-128-CBC slice encryption found in unencrypted stream");break}case 27:s.avc===-1&&(s.avc=l);break;case 3:case 4:e.mpeg!==!0&&e.mp3!==!0?L.log("MPEG audio found, not supported in this browser"):s.audio===-1&&(s.audio=l,s.segmentCodec="mp3");break;case 36:L.warn("Unsupported HEVC stream type found");break}t+=((r[t+3]&15)<<8|r[t+4])+5}return s}function wi(r){let t=0,e,i,s,n,a;const o=r.data;if(!r||r.size===0)return null;for(;o[0].length<19&&o.length>1;){const l=new Uint8Array(o[0].length+o[1].length);l.set(o[0]),l.set(o[1],o[0].length),o[0]=l,o.splice(1,1)}if(e=o[0],(e[0]<<16)+(e[1]<<8)+e[2]===1){if(i=(e[4]<<8)+e[5],i&&i>r.size-6)return null;const l=e[7];l&192&&(n=(e[9]&14)*536870912+(e[10]&255)*4194304+(e[11]&254)*16384+(e[12]&255)*128+(e[13]&254)/2,l&64?(a=(e[14]&14)*536870912+(e[15]&255)*4194304+(e[16]&254)*16384+(e[17]&255)*128+(e[18]&254)/2,n-a>54e5&&(L.warn(`${Math.round((n-a)/9e4)}s delta between PTS and DTS, align them`),n=a)):a=n),s=e[8];let h=s+9;if(r.size<=h)return null;r.size-=h;const d=new Uint8Array(r.size);for(let c=0,u=o.length;c<u;c++){e=o[c];let f=e.byteLength;if(h)if(h>f){h-=f;continue}else e=e.subarray(h),f-=h,h=0;d.set(e,t),t+=f}return i&&(i-=s+3),{data:d,pts:n,dts:a,len:i}}return null}function ms(r,t){if(r.units.length&&r.frame){if(r.pts===void 0){const e=t.samples,i=e.length;if(i){const s=e[i-1];r.pts=s.pts,r.dts=s.dts}else{t.dropped++;return}}t.samples.push(r)}r.debug.length&&L.log(r.pts+"/"+r.dts+":"+r.debug)}class Om extends Kh{resetInitSegment(t,e,i,s){super.resetInitSegment(t,e,i,s),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:e,duration:s,inputTimeScale:9e4,dropped:0}}static probe(t){if(!t)return!1;let e=(rr(t,0)||[]).length;for(let i=t.length;e<i;e++)if(Cm(t,e))return L.log("MPEG Audio sync word found !"),!0;return!1}canParse(t,e){return km(t,e)}appendFrame(t,e,i){if(this.basePTS!==null)return Xh(t,e,i,this.basePTS,this.frameIndex)}}class td{static getSilentFrame(t,e){switch(t){case"mp4a.40.2":if(e===1)return new Uint8Array([0,200,0,128,35,128]);if(e===2)return new Uint8Array([33,0,73,144,2,25,0,35,128]);if(e===3)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,142]);if(e===4)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,128,44,128,8,2,56]);if(e===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(e===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(e===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(e===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(e===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}}}const Me=Math.pow(2,32)-1;class k{static init(){k.types={avc1:[],avcC:[],btrt:[],dinf:[],dref:[],esds:[],ftyp:[],hdlr:[],mdat:[],mdhd:[],mdia:[],mfhd:[],minf:[],moof:[],moov:[],mp4a:[],".mp3":[],mvex:[],mvhd:[],pasp:[],sdtp:[],stbl:[],stco:[],stsc:[],stsd:[],stsz:[],stts:[],tfdt:[],tfhd:[],traf:[],trak:[],trun:[],trex:[],tkhd:[],vmhd:[],smhd:[]};let t;for(t in k.types)k.types.hasOwnProperty(t)&&(k.types[t]=[t.charCodeAt(0),t.charCodeAt(1),t.charCodeAt(2),t.charCodeAt(3)]);const e=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]);k.HDLR_TYPES={video:e,audio:i};const s=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]);k.STTS=k.STSC=k.STCO=n,k.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),k.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),k.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),k.STSD=new Uint8Array([0,0,0,0,0,0,0,1]);const a=new Uint8Array([105,115,111,109]),o=new Uint8Array([97,118,99,49]),l=new Uint8Array([0,0,0,1]);k.FTYP=k.box(k.types.ftyp,a,l,a,o),k.DINF=k.box(k.types.dinf,k.box(k.types.dref,s))}static box(t,...e){let i=8,s=e.length;const n=s;for(;s--;)i+=e[s].byteLength;const 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(t,4),s=0,i=8;s<n;s++)a.set(e[s],i),i+=e[s].byteLength;return a}static hdlr(t){return k.box(k.types.hdlr,k.HDLR_TYPES[t])}static mdat(t){return k.box(k.types.mdat,t)}static mdhd(t,e){e*=t;const i=Math.floor(e/(Me+1)),s=Math.floor(e%(Me+1));return k.box(k.types.mdhd,new Uint8Array([1,0,0,0,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,i>>24,i>>16&255,i>>8&255,i&255,s>>24,s>>16&255,s>>8&255,s&255,85,196,0,0]))}static mdia(t){return k.box(k.types.mdia,k.mdhd(t.timescale,t.duration),k.hdlr(t.type),k.minf(t))}static mfhd(t){return k.box(k.types.mfhd,new Uint8Array([0,0,0,0,t>>24,t>>16&255,t>>8&255,t&255]))}static minf(t){return t.type==="audio"?k.box(k.types.minf,k.box(k.types.smhd,k.SMHD),k.DINF,k.stbl(t)):k.box(k.types.minf,k.box(k.types.vmhd,k.VMHD),k.DINF,k.stbl(t))}static moof(t,e,i){return k.box(k.types.moof,k.mfhd(t),k.traf(i,e))}static moov(t){let e=t.length;const i=[];for(;e--;)i[e]=k.trak(t[e]);return k.box.apply(null,[k.types.moov,k.mvhd(t[0].timescale,t[0].duration)].concat(i).concat(k.mvex(t)))}static mvex(t){let e=t.length;const i=[];for(;e--;)i[e]=k.trex(t[e]);return k.box.apply(null,[k.types.mvex,...i])}static mvhd(t,e){e*=t;const i=Math.floor(e/(Me+1)),s=Math.floor(e%(Me+1)),n=new Uint8Array([1,0,0,0,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,i>>24,i>>16&255,i>>8&255,i&255,s>>24,s>>16&255,s>>8&255,s&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 k.box(k.types.mvhd,n)}static sdtp(t){const e=t.samples||[],i=new Uint8Array(4+e.length);let s,n;for(s=0;s<e.length;s++)n=e[s].flags,i[s+4]=n.dependsOn<<4|n.isDependedOn<<2|n.hasRedundancy;return k.box(k.types.sdtp,i)}static stbl(t){return k.box(k.types.stbl,k.stsd(t),k.box(k.types.stts,k.STTS),k.box(k.types.stsc,k.STSC),k.box(k.types.stsz,k.STSZ),k.box(k.types.stco,k.STCO))}static avc1(t){let e=[],i=[],s,n,a;for(s=0;s<t.sps.length;s++)n=t.sps[s],a=n.byteLength,e.push(a>>>8&255),e.push(a&255),e=e.concat(Array.prototype.slice.call(n));for(s=0;s<t.pps.length;s++)n=t.pps[s],a=n.byteLength,i.push(a>>>8&255),i.push(a&255),i=i.concat(Array.prototype.slice.call(n));const o=k.box(k.types.avcC,new Uint8Array([1,e[3],e[4],e[5],255,224|t.sps.length].concat(e).concat([t.pps.length]).concat(i))),l=t.width,h=t.height,d=t.pixelRatio[0],c=t.pixelRatio[1];return k.box(k.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,h>>8&255,h&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,k.box(k.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),k.box(k.types.pasp,new Uint8Array([d>>24,d>>16&255,d>>8&255,d&255,c>>24,c>>16&255,c>>8&255,c&255])))}static esds(t){const e=t.config.length;return new Uint8Array([0,0,0,0,3,23+e,0,1,0,4,15+e,64,21,0,0,0,0,0,0,0,0,0,0,0,5].concat([e]).concat(t.config).concat([6,1,2]))}static mp4a(t){const e=t.samplerate;return k.box(k.types.mp4a,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,t.channelCount,0,16,0,0,0,0,e>>8&255,e&255,0,0]),k.box(k.types.esds,k.esds(t)))}static mp3(t){const e=t.samplerate;return k.box(k.types[".mp3"],new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,t.channelCount,0,16,0,0,0,0,e>>8&255,e&255,0,0]))}static stsd(t){return t.type==="audio"?t.segmentCodec==="mp3"&&t.codec==="mp3"?k.box(k.types.stsd,k.STSD,k.mp3(t)):k.box(k.types.stsd,k.STSD,k.mp4a(t)):k.box(k.types.stsd,k.STSD,k.avc1(t))}static tkhd(t){const e=t.id,i=t.duration*t.timescale,s=t.width,n=t.height,a=Math.floor(i/(Me+1)),o=Math.floor(i%(Me+1));return k.box(k.types.tkhd,new Uint8Array([1,0,0,7,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,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,s>>8&255,s&255,0,0,n>>8&255,n&255,0,0]))}static traf(t,e){const i=k.sdtp(t),s=t.id,n=Math.floor(e/(Me+1)),a=Math.floor(e%(Me+1));return k.box(k.types.traf,k.box(k.types.tfhd,new Uint8Array([0,0,0,0,s>>24,s>>16&255,s>>8&255,s&255])),k.box(k.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])),k.trun(t,i.length+16+20+8+16+8+8),i)}static trak(t){return t.duration=t.duration||4294967295,k.box(k.types.trak,k.tkhd(t),k.mdia(t))}static trex(t){const e=t.id;return k.box(k.types.trex,new Uint8Array([0,0,0,0,e>>24,e>>16&255,e>>8&255,e&255,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))}static trun(t,e){const i=t.samples||[],s=i.length,n=12+16*s,a=new Uint8Array(n);let o,l,h,d,c,u;for(e+=8+n,a.set([t.type==="video"?1:0,0,15,1,s>>>24&255,s>>>16&255,s>>>8&255,s&255,e>>>24&255,e>>>16&255,e>>>8&255,e&255],0),o=0;o<s;o++)l=i[o],h=l.duration,d=l.size,c=l.flags,u=l.cts,a.set([h>>>24&255,h>>>16&255,h>>>8&255,h&255,d>>>24&255,d>>>16&255,d>>>8&255,d&255,c.isLeading<<2|c.dependsOn,c.isDependedOn<<6|c.hasRedundancy<<4|c.paddingValue<<1|c.isNonSync,c.degradPrio&61440,c.degradPrio&15,u>>>24&255,u>>>16&255,u>>>8&255,u&255],12+16*o);return k.box(k.types.trun,a)}static initSegment(t){k.types||k.init();const e=k.moov(t),i=new Uint8Array(k.FTYP.byteLength+e.byteLength);return i.set(k.FTYP),i.set(e,k.FTYP.byteLength),i}}k.types=void 0,k.HDLR_TYPES=void 0,k.STTS=void 0,k.STSC=void 0,k.STCO=void 0,k.STSZ=void 0,k.VMHD=void 0,k.SMHD=void 0,k.STSD=void 0,k.FTYP=void 0,k.DINF=void 0;const ed=9e4;function ha(r,t,e=1,i=!1){const s=r*t*e;return i?Math.round(s):s}function Mm(r,t,e=1,i=!1){return ha(r,t,1/e,i)}function vs(r,t=!1){return ha(r,1e3,1/ed,t)}function $m(r,t=1){return ha(r,ed,1/t)}const Fm=10*1e3,id=1024,Nm=1152;let yr=null,da=null;class ca{constructor(t,e,i,s=""){if(this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.ISGenerated=!1,this._initPTS=null,this._initDTS=null,this.nextAvcDts=null,this.nextAudioPts=null,this.videoSampleDuration=null,this.isAudioContiguous=!1,this.isVideoContiguous=!1,this.observer=t,this.config=e,this.typeSupported=i,this.ISGenerated=!1,yr===null){const n=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);yr=n?parseInt(n[1]):0}if(da===null){const n=navigator.userAgent.match(/Safari\/(\d+)/i);da=n?parseInt(n[1]):0}}destroy(){}resetTimeStamp(t){L.log("[mp4-remuxer]: initPTS & initDTS reset"),this._initPTS=this._initDTS=t}resetNextTimestamp(){L.log("[mp4-remuxer]: reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1}resetInitSegment(){L.log("[mp4-remuxer]: ISGenerated flag reset"),this.ISGenerated=!1}getVideoStartPts(t){let e=!1;const i=t.reduce((s,n)=>{const a=n.pts-s;return a<-4294967296?(e=!0,te(s,n.pts)):a>0?s:n.pts},t[0].pts);return e&&L.debug("PTS rollover detected"),i}remux(t,e,i,s,n,a,o,l){let h,d,c,u,f,p,g=n,v=n;const E=t.pid>-1,T=e.pid>-1,A=e.samples.length,y=t.samples.length>0,b=o&&A>0||A>1;if((!E||y)&&(!T||b)||this.ISGenerated||o){this.ISGenerated||(c=this.generateIS(t,e,n,a));const S=this.isVideoContiguous;let R=-1,D;if(b&&(R=Um(e.samples),!S&&this.config.forceKeyFrameOnDiscontinuity))if(p=!0,R>0){L.warn(`[mp4-remuxer]: Dropped ${R} out of ${A} video samples due to a missing keyframe`);const _=this.getVideoStartPts(e.samples);e.samples=e.samples.slice(R),e.dropped+=R,v+=(e.samples[0].pts-_)/e.inputTimeScale,D=v}else R===-1&&(L.warn(`[mp4-remuxer]: No keyframe found out of ${A} video samples`),p=!1);if(this.ISGenerated){if(y&&b){const _=this.getVideoStartPts(e.samples),I=(te(t.samples[0].pts,_)-_)/e.inputTimeScale;g+=Math.max(0,I),v+=Math.max(0,-I)}if(y){if(t.samplerate||(L.warn("[mp4-remuxer]: regenerate InitSegment as audio detected"),c=this.generateIS(t,e,n,a)),d=this.remuxAudio(t,g,this.isAudioContiguous,a,T||b||l===Y.AUDIO?v:void 0),b){const _=d?d.endPTS-d.startPTS:0;e.inputTimeScale||(L.warn("[mp4-remuxer]: regenerate InitSegment as video detected"),c=this.generateIS(t,e,n,a)),h=this.remuxVideo(e,v,S,_)}}else b&&(h=this.remuxVideo(e,v,S,0));h&&(h.firstKeyFrame=R,h.independent=R!==-1,h.firstKeyFramePTS=D)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(i.samples.length&&(f=sd(i,n,this._initPTS,this._initDTS)),s.samples.length&&(u=rd(s,n,this._initPTS))),{audio:d,video:h,initSegment:c,independent:p,text:u,id3:f}}generateIS(t,e,i,s){const n=t.samples,a=e.samples,o=this.typeSupported,l={},h=this._initPTS;let d=!h||s,c="audio/mp4",u,f,p;if(d&&(u=f=1/0),t.config&&n.length){switch(t.timescale=t.samplerate,t.segmentCodec){case"mp3":o.mpeg?(c="audio/mpeg",t.codec=""):o.mp3&&(t.codec="mp3");break}l.audio={id:"audio",container:c,codec:t.codec,initSegment:t.segmentCodec==="mp3"&&o.mpeg?new Uint8Array(0):k.initSegment([t]),metadata:{channelCount:t.channelCount}},d&&(p=t.inputTimeScale,!h||p!==h.timescale?u=f=n[0].pts-Math.round(p*i):d=!1)}if(e.sps&&e.pps&&a.length&&(e.timescale=e.inputTimeScale,l.video={id:"main",container:"video/mp4",codec:e.codec,initSegment:k.initSegment([e]),metadata:{width:e.width,height:e.height}},d))if(p=e.inputTimeScale,!h||p!==h.timescale){const g=this.getVideoStartPts(a),v=Math.round(p*i);f=Math.min(f,te(a[0].dts,g)-v),u=Math.min(u,g-v)}else d=!1;if(Object.keys(l).length)return this.ISGenerated=!0,d?(this._initPTS={baseTime:u,timescale:p},this._initDTS={baseTime:f,timescale:p}):u=p=void 0,{tracks:l,initPTS:u,timescale:p}}remuxVideo(t,e,i,s){const n=t.inputTimeScale,a=t.samples,o=[],l=a.length,h=this._initPTS;let d=this.nextAvcDts,c=8,u=this.videoSampleDuration,f,p,g=Number.POSITIVE_INFINITY,v=Number.NEGATIVE_INFINITY,E=!1;if(!i||d===null){const M=e*n,B=a[0].pts-te(a[0].dts,a[0].pts);d=M-B}const T=h.baseTime*n/h.timescale;for(let M=0;M<l;M++){const B=a[M];B.pts=te(B.pts-T,d),B.dts=te(B.dts-T,d),B.dts<a[M>0?M-1:M].dts&&(E=!0)}E&&a.sort(function(M,B){const H=M.dts-B.dts,z=M.pts-B.pts;return H||z}),f=a[0].dts,p=a[a.length-1].dts;const A=p-f,y=A?Math.round(A/(l-1)):u||t.inputTimeScale/30;if(i){const M=f-d,B=M>y,H=M<-1;if((B||H)&&(B?L.warn(`AVC: ${vs(M,!0)} ms (${M}dts) hole between fragments detected, filling it`):L.warn(`AVC: ${vs(-M,!0)} ms (${M}dts) overlapping between fragments detected`),!H||d>=a[0].pts)){f=d;const z=a[0].pts-M;a[0].dts=f,a[0].pts=z,L.log(`Video: First PTS/DTS adjusted: ${vs(z,!0)}/${vs(f,!0)}, delta: ${vs(M,!0)} ms`)}}f=Math.max(0,f);let b=0,S=0;for(let M=0;M<l;M++){const B=a[M],H=B.units,z=H.length;let Z=0;for(let Q=0;Q<z;Q++)Z+=H[Q].data.length;S+=Z,b+=z,B.length=Z,B.dts=Math.max(B.dts,f),g=Math.min(B.pts,g),v=Math.max(B.pts,v)}p=a[l-1].dts;const R=S+4*b+8;let D;try{D=new Uint8Array(R)}catch(M){this.observer.emit(m.ERROR,m.ERROR,{type:W.MUX_ERROR,details:x.REMUX_ALLOC_ERROR,fatal:!1,error:M,bytes:R,reason:`fail allocating video mdat ${R}`});return}const _=new DataView(D.buffer);_.setUint32(0,R),D.set(k.types.mdat,4);let I=!1,N=Number.POSITIVE_INFINITY,P=Number.POSITIVE_INFINITY,F=Number.NEGATIVE_INFINITY,K=Number.NEGATIVE_INFINITY;for(let M=0;M<l;M++){const B=a[M],H=B.units;let z=0;for(let it=0,tt=H.length;it<tt;it++){const xt=H[it],St=xt.data,yt=xt.data.byteLength;_.setUint32(c,yt),c+=4,D.set(St,c),c+=yt,z+=4+yt}let Z;if(M<l-1)u=a[M+1].dts-B.dts,Z=a[M+1].pts-B.pts;else{const it=this.config,tt=M>0?B.dts-a[M-1].dts:y;if(Z=M>0?B.pts-a[M-1].pts:y,it.stretchShortVideoTrack&&this.nextAudioPts!==null){const xt=Math.floor(it.maxBufferHole*n),St=(s?g+s*n:this.nextAudioPts)-B.pts;St>xt?(u=St-tt,u<0?u=tt:I=!0,L.log(`[mp4-remuxer]: It is approximately ${St/90} ms to the next segment; using duration ${u/90} ms for the last video frame.`)):u=tt}else u=tt}const Q=Math.round(B.pts-B.dts);N=Math.min(N,u),F=Math.max(F,u),P=Math.min(P,Z),K=Math.max(K,Z),o.push(new nd(B.key,u,z,Q))}if(o.length){if(yr){if(yr<70){const M=o[0].flags;M.dependsOn=2,M.isNonSync=0}}else if(da&&K-P<F-N&&y/F<.025&&o[0].cts===0){L.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");let M=f;for(let B=0,H=o.length;B<H;B++){const z=M+o[B].duration,Z=M+o[B].cts;if(B<H-1){const Q=z+o[B+1].cts;o[B].duration=Q-Z}else o[B].duration=B?o[B-1].duration:y;o[B].cts=0,M=z}}}u=I||!u?y:u,this.nextAvcDts=d=p+u,this.videoSampleDuration=u,this.isVideoContiguous=!0;const w=k.moof(t.sequenceNumber++,f,At({},t,{samples:o})),C="video",U={data1:w,data2:D,startPTS:g/n,endPTS:(v+u)/n,startDTS:f/n,endDTS:d/n,type:C,hasAudio:!1,hasVideo:!0,nb:o.length,dropped:t.dropped};return t.samples=[],t.dropped=0,U}remuxAudio(t,e,i,s,n){const a=t.inputTimeScale,o=t.samplerate?t.samplerate:a,l=a/o,h=t.segmentCodec==="aac"?id:Nm,d=h*l,c=this._initPTS,u=t.segmentCodec==="mp3"&&this.typeSupported.mpeg,f=[],p=n!==void 0;let g=t.samples,v=u?0:8,E=this.nextAudioPts||-1;const T=e*a,A=c.baseTime*a/c.timescale;if(this.isAudioContiguous=i=i||g.length&&E>0&&(s&&Math.abs(T-E)<9e3||Math.abs(te(g[0].pts-A,T)-E)<20*d),g.forEach(function(w){w.pts=te(w.pts-A,T)}),!i||E<0){if(g=g.filter(w=>w.pts>=0),!g.length)return;n===0?E=0:s&&!p?E=Math.max(0,T):E=g[0].pts}if(t.segmentCodec==="aac"){const w=this.config.maxAudioFramesDrift;for(let C=0,U=E;C<g.length;C++){const M=g[C],B=M.pts,H=B-U,z=Math.abs(1e3*H/a);if(H<=-w*d&&p)C===0&&(L.warn(`Audio frame @ ${(B/a).toFixed(3)}s overlaps nextAudioPts by ${Math.round(1e3*H/a)} ms.`),this.nextAudioPts=E=U=B);else if(H>=w*d&&z<Fm&&p){let Z=Math.round(H/d);U=B-Z*d,U<0&&(Z--,U+=d),C===0&&(this.nextAudioPts=E=U),L.warn(`[mp4-remuxer]: Injecting ${Z} audio frame @ ${(U/a).toFixed(3)}s due to ${Math.round(1e3*H/a)} ms gap.`);for(let Q=0;Q<Z;Q++){const it=Math.max(U,0);let tt=td.getSilentFrame(t.manifestCodec||t.codec,t.channelCount);tt||(L.log("[mp4-remuxer]: Unable to get silent frame for given audio codec; duplicating last frame instead."),tt=M.unit.subarray()),g.splice(C,0,{unit:tt,pts:it}),U+=d,C++}}M.pts=U,U+=d}}let y=null,b=null,S,R=0,D=g.length;for(;D--;)R+=g[D].unit.byteLength;for(let w=0,C=g.length;w<C;w++){const U=g[w],M=U.unit;let B=U.pts;if(b!==null){const z=f[w-1];z.duration=Math.round((B-b)/l)}else if(i&&t.segmentCodec==="aac"&&(B=E),y=B,R>0){R+=v;try{S=new Uint8Array(R)}catch(z){this.observer.emit(m.ERROR,m.ERROR,{type:W.MUX_ERROR,details:x.REMUX_ALLOC_ERROR,fatal:!1,error:z,bytes:R,reason:`fail allocating audio mdat ${R}`});return}u||(new DataView(S.buffer).setUint32(0,R),S.set(k.types.mdat,4))}else return;S.set(M,v);const H=M.byteLength;v+=H,f.push(new nd(!0,h,H,0)),b=B}const _=f.length;if(!_)return;const I=f[f.length-1];this.nextAudioPts=E=b+l*I.duration;const N=u?new Uint8Array(0):k.moof(t.sequenceNumber++,y/l,At({},t,{samples:f}));t.samples=[];const P=y/a,F=E/a,K={data1:N,data2:S,startPTS:P,endPTS:F,startDTS:P,endDTS:F,type:"audio",hasAudio:!0,hasVideo:!1,nb:_};return this.isAudioContiguous=!0,K}remuxEmptyAudio(t,e,i,s){const n=t.inputTimeScale,a=t.samplerate?t.samplerate:n,o=n/a,l=this.nextAudioPts,h=this._initDTS,d=h.baseTime*9e4/h.timescale,c=(l!==null?l:s.startDTS*n)+d,u=s.endDTS*n+d,f=o*id,p=Math.ceil((u-c)/f),g=td.getSilentFrame(t.manifestCodec||t.codec,t.channelCount);if(L.warn("[mp4-remuxer]: remux empty Audio"),!g){L.trace("[mp4-remuxer]: Unable to remuxEmptyAudio since we were unable to get a silent frame for given audio codec");return}const v=[];for(let E=0;E<p;E++){const T=c+E*f;v.push({unit:g,pts:T,dts:T})}return t.samples=v,this.remuxAudio(t,e,i,!1)}}function te(r,t){let e;if(t===null)return r;for(t<r?e=-8589934592:e=8589934592;Math.abs(r-t)>4294967296;)r+=e;return r}function Um(r){for(let t=0;t<r.length;t++)if(r[t].key)return t;return-1}function sd(r,t,e,i){const s=r.samples.length;if(!s)return;const n=r.inputTimeScale;for(let o=0;o<s;o++){const l=r.samples[o];l.pts=te(l.pts-e.baseTime*n/e.timescale,t*n)/n,l.dts=te(l.dts-i.baseTime*n/i.timescale,t*n)/n}const a=r.samples;return r.samples=[],{samples:a}}function rd(r,t,e){const i=r.samples.length;if(!i)return;const s=r.inputTimeScale;for(let a=0;a<i;a++){const o=r.samples[a];o.pts=te(o.pts-e.baseTime*s/e.timescale,t*s)/s}r.samples.sort((a,o)=>a.pts-o.pts);const n=r.samples;return r.samples=[],{samples:n}}class nd{constructor(t,e,i,s){this.size=void 0,this.duration=void 0,this.cts=void 0,this.flags=void 0,this.duration=e,this.size=i,this.cts=s,this.flags=new Bm(t)}}class Bm{constructor(t){this.isLeading=0,this.isDependedOn=0,this.hasRedundancy=0,this.degradPrio=0,this.dependsOn=1,this.isNonSync=1,this.dependsOn=t?2:1,this.isNonSync=t?0:1}}class Hm{constructor(){this.emitInitSegment=!1,this.audioCodec=void 0,this.videoCodec=void 0,this.initData=void 0,this.initPTS=null,this.initTracks=void 0,this.lastEndTime=null}destroy(){}resetTimeStamp(t){this.initPTS=t,this.lastEndTime=null}resetNextTimestamp(){this.lastEndTime=null}resetInitSegment(t,e,i,s){this.audioCodec=e,this.videoCodec=i,this.generateInitSegment(og(t,s)),this.emitInitSegment=!0}generateInitSegment(t){let{audioCodec:e,videoCodec:i}=this;if(!(t!=null&&t.byteLength)){this.initTracks=void 0,this.initData=void 0;return}const s=this.initData=oh(t);e||(e=ad(s.audio,at.AUDIO)),i||(i=ad(s.video,at.VIDEO));const n={};s.audio&&s.video?n.audiovideo={container:"video/mp4",codec:e+","+i,initSegment:t,id:"main"}:s.audio?n.audio={container:"audio/mp4",codec:e,initSegment:t,id:"audio"}:s.video?n.video={container:"video/mp4",codec:i,initSegment:t,id:"main"}:L.warn("[passthrough-remuxer.ts]: initSegment does not contain moov or trak boxes."),this.initTracks=n}remux(t,e,i,s,n,a){var o,l;let{initPTS:h,lastEndTime:d}=this;const c={audio:void 0,video:void 0,text:s,id3:i,initSegment:void 0};j(d)||(d=this.lastEndTime=n||0);const u=e.samples;if(!(u!=null&&u.length))return c;const f={initPTS:void 0,timescale:1};let p=this.initData;if((o=p)!=null&&o.length||(this.generateInitSegment(u),p=this.initData),!((l=p)!=null&&l.length))return L.warn("[passthrough-remuxer.ts]: Failed to generate initSegment."),c;this.emitInitSegment&&(f.tracks=this.initTracks,this.emitInitSegment=!1);const g=hg(u,p),v=lg(p,u),E=v===null?n:v;(Gm(h,E,n,g)||f.timescale!==h.timescale&&a)&&(f.initPTS=E-n,h&&h.timescale===1&&L.warn(`Adjusting initPTS by ${f.initPTS-h.baseTime}`),this.initPTS=h={baseTime:f.initPTS,timescale:1});const T=t?E-h.baseTime/h.timescale:d,A=T+g;cg(p,u,h.baseTime/h.timescale),g>0?this.lastEndTime=A:(L.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const y=!!p.audio,b=!!p.video;let S="";y&&(S+="audio"),b&&(S+="video");const R={data1:u,startPTS:T,startDTS:T,endPTS:A,endDTS:A,type:S,hasAudio:y,hasVideo:b,nb:1,dropped:0};return c.audio=R.type==="audio"?R:void 0,c.video=R.type!=="audio"?R:void 0,c.initSegment=f,c.id3=sd(i,n,h,h),s.samples.length&&(c.text=rd(s,n,h)),c}}function Gm(r,t,e,i){if(r===null)return!0;const s=Math.max(i,1),n=t-r.baseTime/r.timescale;return Math.abs(n-e)>s}function ad(r,t){const e=r==null?void 0:r.codec;return e&&e.length>4?e:e==="hvc1"||e==="hev1"?"hvc1.1.6.L120.90":e==="av01"?"av01.0.04M.08":e==="avc1"||t===at.VIDEO?"avc1.42e01e":"mp4a.40.5"}let Re;try{Re=self.performance.now.bind(self.performance)}catch{L.debug("Unable to use Performance API on this environment"),Re=typeof self<"u"&&self.Date.now}const ua=[{demux:Sm,remux:Hm},{demux:Oe,remux:ca},{demux:Am,remux:ca},{demux:Om,remux:ca}];class od{constructor(t,e,i,s,n){this.async=!1,this.observer=void 0,this.typeSupported=void 0,this.config=void 0,this.vendor=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=t,this.typeSupported=e,this.config=i,this.vendor=s,this.id=n}configure(t){this.transmuxConfig=t,this.decrypter&&this.decrypter.reset()}push(t,e,i,s){const n=i.transmuxing;n.executeStart=Re();let a=new Uint8Array(t);const{currentTransmuxState:o,transmuxConfig:l}=this;s&&(this.currentTransmuxState=s);const{contiguous:h,discontinuity:d,trackSwitch:c,accurateTimeOffset:u,timeOffset:f,initSegmentChange:p}=s||o,{audioCodec:g,videoCodec:v,defaultInitPts:E,duration:T,initSegmentData:A}=l,y=Vm(a,e);if(y&&y.method==="AES-128"){const D=this.getDecrypter();if(D.isSync()){let _=D.softwareDecrypt(a,y.key.buffer,y.iv.buffer);if(i.part>-1&&(_=D.flush()),!_)return n.executeEnd=Re(),fa(i);a=new Uint8Array(_)}else return this.decryptionPromise=D.webCryptoDecrypt(a,y.key.buffer,y.iv.buffer).then(_=>{const I=this.push(_,null,i);return this.decryptionPromise=null,I}),this.decryptionPromise}const b=this.needsProbing(d,c);if(b){const D=this.configureTransmuxer(a);if(D)return L.warn(`[transmuxer] ${D.message}`),this.observer.emit(m.ERROR,m.ERROR,{type:W.MEDIA_ERROR,details:x.FRAG_PARSING_ERROR,fatal:!1,error:D,reason:D.message}),n.executeEnd=Re(),fa(i)}(d||c||p||b)&&this.resetInitSegment(A,g,v,T,e),(d||p||b)&&this.resetInitialTimestamp(E),h||this.resetContiguity();const S=this.transmux(a,y,f,u,i),R=this.currentTransmuxState;return R.contiguous=!0,R.discontinuity=!1,R.trackSwitch=!1,n.executeEnd=Re(),S}flush(t){const e=t.transmuxing;e.executeStart=Re();const{decrypter:i,currentTransmuxState:s,decryptionPromise:n}=this;if(n)return n.then(()=>this.flush(t));const a=[],{timeOffset:o}=s;if(i){const c=i.flush();c&&a.push(this.push(c,null,t))}const{demuxer:l,remuxer:h}=this;if(!l||!h)return e.executeEnd=Re(),[fa(t)];const d=l.flush(o);return Er(d)?d.then(c=>(this.flushRemux(a,c,t),a)):(this.flushRemux(a,d,t),a)}flushRemux(t,e,i){const{audioTrack:s,videoTrack:n,id3Track:a,textTrack:o}=e,{accurateTimeOffset:l,timeOffset:h}=this.currentTransmuxState;L.log(`[transmuxer.ts]: Flushed fragment ${i.sn}${i.part>-1?" p: "+i.part:""} of level ${i.level}`);const d=this.remuxer.remux(s,n,a,o,h,l,!0,this.id);t.push({remuxResult:d,chunkMeta:i}),i.transmuxing.executeEnd=Re()}resetInitialTimestamp(t){const{demuxer:e,remuxer:i}=this;!e||!i||(e.resetTimeStamp(t),i.resetTimeStamp(t))}resetContiguity(){const{demuxer:t,remuxer:e}=this;!t||!e||(t.resetContiguity(),e.resetNextTimestamp())}resetInitSegment(t,e,i,s,n){const{demuxer:a,remuxer:o}=this;!a||!o||(a.resetInitSegment(t,e,i,s),o.resetInitSegment(t,e,i,n))}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)}transmux(t,e,i,s,n){let a;return e&&e.method==="SAMPLE-AES"?a=this.transmuxSampleAes(t,e,i,s,n):a=this.transmuxUnencrypted(t,i,s,n),a}transmuxUnencrypted(t,e,i,s){const{audioTrack:n,videoTrack:a,id3Track:o,textTrack:l}=this.demuxer.demux(t,e,!1,!this.config.progressive);return{remuxResult:this.remuxer.remux(n,a,o,l,e,i,!1,this.id),chunkMeta:s}}transmuxSampleAes(t,e,i,s,n){return this.demuxer.demuxSampleAes(t,e,i).then(a=>({remuxResult:this.remuxer.remux(a.audioTrack,a.videoTrack,a.id3Track,a.textTrack,i,s,!1,this.id),chunkMeta:n}))}configureTransmuxer(t){const{config:e,observer:i,typeSupported:s,vendor:n}=this;let a;for(let c=0,u=ua.length;c<u;c++)if(ua[c].demux.probe(t)){a=ua[c];break}if(!a)return new Error("Failed to find demuxer by probing fragment data");const o=this.demuxer,l=this.remuxer,h=a.remux,d=a.demux;(!l||!(l instanceof h))&&(this.remuxer=new h(i,e,s,n)),(!o||!(o instanceof d))&&(this.demuxer=new d(i,e,s),this.probe=d.probe)}needsProbing(t,e){return!this.demuxer||!this.remuxer||t||e}getDecrypter(){let t=this.decrypter;return t||(t=this.decrypter=new ra(this.config)),t}}function Vm(r,t){let e=null;return r.byteLength>0&&t!=null&&t.key!=null&&t.iv!==null&&t.method!=null&&(e=t),e}const fa=r=>({remuxResult:{},chunkMeta:r});function Er(r){return"then"in r&&r.then instanceof Function}class Km{constructor(t,e,i,s,n){this.audioCodec=void 0,this.videoCodec=void 0,this.initSegmentData=void 0,this.duration=void 0,this.defaultInitPts=void 0,this.audioCodec=t,this.videoCodec=e,this.initSegmentData=i,this.duration=s,this.defaultInitPts=n||null}}class jm{constructor(t,e,i,s,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=t,this.contiguous=e,this.accurateTimeOffset=i,this.trackSwitch=s,this.timeOffset=n,this.initSegmentChange=a}}var ld={exports:{}};(function(r){var t=Object.prototype.hasOwnProperty,e="~";function i(){}Object.create&&(i.prototype=Object.create(null),new i().__proto__||(e=!1));function s(l,h,d){this.fn=l,this.context=h,this.once=d||!1}function n(l,h,d,c,u){if(typeof d!="function")throw new TypeError("The listener must be a function");var f=new s(d,c||l,u),p=e?e+h:h;return l._events[p]?l._events[p].fn?l._events[p]=[l._events[p],f]:l._events[p].push(f):(l._events[p]=f,l._eventsCount++),l}function a(l,h){--l._eventsCount===0?l._events=new i:delete l._events[h]}function o(){this._events=new i,this._eventsCount=0}o.prototype.eventNames=function(){var l=[],h,d;if(this._eventsCount===0)return l;for(d in h=this._events)t.call(h,d)&&l.push(e?d.slice(1):d);return Object.getOwnPropertySymbols?l.concat(Object.getOwnPropertySymbols(h)):l},o.prototype.listeners=function(l){var h=e?e+l:l,d=this._events[h];if(!d)return[];if(d.fn)return[d.fn];for(var c=0,u=d.length,f=new Array(u);c<u;c++)f[c]=d[c].fn;return f},o.prototype.listenerCount=function(l){var h=e?e+l:l,d=this._events[h];return d?d.fn?1:d.length:0},o.prototype.emit=function(l,h,d,c,u,f){var p=e?e+l:l;if(!this._events[p])return!1;var g=this._events[p],v=arguments.length,E,T;if(g.fn){switch(g.once&&this.removeListener(l,g.fn,void 0,!0),v){case 1:return g.fn.call(g.context),!0;case 2:return g.fn.call(g.context,h),!0;case 3:return g.fn.call(g.context,h,d),!0;case 4:return g.fn.call(g.context,h,d,c),!0;case 5:return g.fn.call(g.context,h,d,c,u),!0;case 6:return g.fn.call(g.context,h,d,c,u,f),!0}for(T=1,E=new Array(v-1);T<v;T++)E[T-1]=arguments[T];g.fn.apply(g.context,E)}else{var A=g.length,y;for(T=0;T<A;T++)switch(g[T].once&&this.removeListener(l,g[T].fn,void 0,!0),v){case 1:g[T].fn.call(g[T].context);break;case 2:g[T].fn.call(g[T].context,h);break;case 3:g[T].fn.call(g[T].context,h,d);break;case 4:g[T].fn.call(g[T].context,h,d,c);break;default:if(!E)for(y=1,E=new Array(v-1);y<v;y++)E[y-1]=arguments[y];g[T].fn.apply(g[T].context,E)}}return!0},o.prototype.on=function(l,h,d){return n(this,l,h,d,!1)},o.prototype.once=function(l,h,d){return n(this,l,h,d,!0)},o.prototype.removeListener=function(l,h,d,c){var u=e?e+l:l;if(!this._events[u])return this;if(!h)return a(this,u),this;var f=this._events[u];if(f.fn)f.fn===h&&(!c||f.once)&&(!d||f.context===d)&&a(this,u);else{for(var p=0,g=[],v=f.length;p<v;p++)(f[p].fn!==h||c&&!f[p].once||d&&f[p].context!==d)&&g.push(f[p]);g.length?this._events[u]=g.length===1?g[0]:g:a(this,u)}return this},o.prototype.removeAllListeners=function(l){var h;return l?(h=e?e+l:l,this._events[h]&&a(this,h)):(this._events=new i,this._eventsCount=0),this},o.prototype.off=o.prototype.removeListener,o.prototype.addListener=o.prototype.on,o.prefixed=e,o.EventEmitter=o,r.exports=o})(ld);var Wm=ld.exports,pa=Dp(Wm);const ga=lr()||{isTypeSupported:()=>!1};class hd{constructor(t,e,i,s){this.error=null,this.hls=void 0,this.id=void 0,this.observer=void 0,this.frag=null,this.part=null,this.useWorker=void 0,this.workerContext=null,this.onwmsg=void 0,this.transmuxer=null,this.onTransmuxComplete=void 0,this.onFlush=void 0;const n=t.config;this.hls=t,this.id=e,this.useWorker=!!n.enableWorker,this.onTransmuxComplete=i,this.onFlush=s;const a=(h,d)=>{d=d||{},d.frag=this.frag,d.id=this.id,h===m.ERROR&&(this.error=d.error),this.hls.trigger(h,d)};this.observer=new pa,this.observer.on(m.FRAG_DECRYPTED,a),this.observer.on(m.ERROR,a);const o={mp4:ga.isTypeSupported("video/mp4"),mpeg:ga.isTypeSupported("audio/mpeg"),mp3:ga.isTypeSupported('audio/mp4; codecs="mp3"')},l=navigator.vendor;if(this.useWorker&&typeof Worker<"u"&&(n.workerPath||fm())){try{n.workerPath?(L.log(`loading Web Worker ${n.workerPath} for "${e}"`),this.workerContext=gm(n.workerPath)):(L.log(`injecting Web Worker for "${e}"`),this.workerContext=pm()),this.onwmsg=d=>this.onWorkerMessage(d);const{worker:h}=this.workerContext;h.addEventListener("message",this.onwmsg),h.onerror=d=>{const c=new Error(`${d.message} (${d.filename}:${d.lineno})`);n.enableWorker=!1,L.warn(`Error in "${e}" Web Worker, fallback to inline`),this.hls.trigger(m.ERROR,{type:W.OTHER_ERROR,details:x.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:c})},h.postMessage({cmd:"init",typeSupported:o,vendor:l,id:e,config:JSON.stringify(n)})}catch(h){L.warn(`Error setting up "${e}" Web Worker, fallback to inline`,h),this.resetWorker(),this.error=null,this.transmuxer=new od(this.observer,o,n,l,e)}return}this.transmuxer=new od(this.observer,o,n,l,e)}resetWorker(){if(this.workerContext){const{worker:t,objectURL:e}=this.workerContext;e&&self.URL.revokeObjectURL(e),t.removeEventListener("message",this.onwmsg),t.onerror=null,t.terminate(),this.workerContext=null}}destroy(){if(this.workerContext)this.resetWorker(),this.onwmsg=void 0;else{const e=this.transmuxer;e&&(e.destroy(),this.transmuxer=null)}const t=this.observer;t&&t.removeAllListeners(),this.frag=null,this.observer=null,this.hls=null}push(t,e,i,s,n,a,o,l,h,d){var c,u;h.transmuxing.start=self.performance.now();const{transmuxer:f}=this,p=a?a.start:n.start,g=n.decryptdata,v=this.frag,E=!(v&&n.cc===v.cc),T=!(v&&h.level===v.level),A=v?h.sn-v.sn:-1,y=this.part?h.part-this.part.index:-1,b=A===0&&h.id>1&&h.id===(v==null?void 0:v.stats.chunkCount),S=!T&&(A===1||A===0&&(y===1||b&&y<=0)),R=self.performance.now();(T||A||n.stats.parsing.start===0)&&(n.stats.parsing.start=R),a&&(y||!S)&&(a.stats.parsing.start=R);const D=!(v&&((c=n.initSegment)==null?void 0:c.url)===((u=v.initSegment)==null?void 0:u.url)),_=new jm(E,S,l,T,p,D);if(!S||E||D){L.log(`[transmuxer-interface, ${n.type}]: Starting new transmux session for sn: ${h.sn} p: ${h.part} level: ${h.level} id: ${h.id}
148
+ */const Uo=(r,t,e)=>{const i=new Map;for(let s=t;s<=e;s++)i.set(r[s],s);return i},Bo=is(class extends Fs{constructor(r){if(super(r),r.type!==es.CHILD)throw Error("repeat() can only be used in text expressions")}ht(r,t,e){let i;e===void 0?e=t:t!==void 0&&(i=t);const s=[],n=[];let a=0;for(const o of r)s[a]=i?i(o,a):a,n[a]=e(o,a),a++;return{values:n,keys:s}}render(r,t,e){return this.ht(r,t,e).values}update(r,[t,e,i]){const s=yd(r),{values:n,keys:a}=this.ht(t,e,i);if(!Array.isArray(s))return this.dt=a,n;const o=this.dt??(this.dt=[]),l=[];let h,c,d=0,u=s.length-1,f=0,p=n.length-1;for(;d<=u&&f<=p;)if(s[d]===null)d++;else if(s[u]===null)u--;else if(o[d]===a[f])l[f]=ni(s[d],n[f]),d++,f++;else if(o[u]===a[p])l[p]=ni(s[u],n[p]),u--,p--;else if(o[d]===a[p])l[p]=ni(s[d],n[p]),ts(r,l[p+1],s[d]),d++,p--;else if(o[u]===a[f])l[f]=ni(s[u],n[f]),ts(r,s[d],s[u]),u--,f++;else if(h===void 0&&(h=Uo(a,f,p),c=Uo(o,d,u)),h.has(o[d]))if(h.has(o[u])){const g=c.get(a[f]),v=g!==void 0?s[g]:null;if(v===null){const E=ts(r,s[d]);ni(E,n[f]),l[f]=E}else l[f]=ni(v,n[f]),ts(r,s[d],v),s[g]=null;f++}else Yr(s[u]),u--;else Yr(s[d]),d++;for(;f<=p;){const g=ts(r,l[p+1]);ni(g,n[f]),l[f++]=g}for(;d<=u;){const g=s[d++];g!==null&&Yr(g)}return this.dt=a,vd(r,l),Ze}});var qt="top",le="bottom",he="right",Xt="left",an="auto",cs=[qt,le,he,Xt],wi="start",ds="end",Lu="clippingParents",Ho="viewport",us="popper",Ru="reference",Go=cs.reduce(function(r,t){return r.concat([t+"-"+wi,t+"-"+ds])},[]),Vo=[].concat(cs,[an]).reduce(function(r,t){return r.concat([t,t+"-"+wi,t+"-"+ds])},[]),_u="beforeRead",ku="read",Iu="afterRead",Cu="beforeMain",Du="main",xu="afterMain",Pu="beforeWrite",Ou="write",$u="afterWrite",Mu=[_u,ku,Iu,Cu,Du,xu,Pu,Ou,$u];function Te(r){return r?(r.nodeName||"").toLowerCase():null}function ie(r){if(r==null)return window;if(r.toString()!=="[object Window]"){var t=r.ownerDocument;return t&&t.defaultView||window}return r}function oi(r){var t=ie(r).Element;return r instanceof t||r instanceof Element}function ce(r){var t=ie(r).HTMLElement;return r instanceof t||r instanceof HTMLElement}function on(r){if(typeof ShadowRoot>"u")return!1;var t=ie(r).ShadowRoot;return r instanceof t||r instanceof ShadowRoot}function Fu(r){var t=r.state;Object.keys(t.elements).forEach(function(e){var i=t.styles[e]||{},s=t.attributes[e]||{},n=t.elements[e];!ce(n)||!Te(n)||(Object.assign(n.style,i),Object.keys(s).forEach(function(a){var o=s[a];o===!1?n.removeAttribute(a):n.setAttribute(a,o===!0?"":o)}))})}function Nu(r){var t=r.state,e={popper:{position:t.options.strategy,left:"0",top:"0",margin:"0"},arrow:{position:"absolute"},reference:{}};return Object.assign(t.elements.popper.style,e.popper),t.styles=e,t.elements.arrow&&Object.assign(t.elements.arrow.style,e.arrow),function(){Object.keys(t.elements).forEach(function(i){var s=t.elements[i],n=t.attributes[i]||{},a=Object.keys(t.styles.hasOwnProperty(i)?t.styles[i]:e[i]),o=a.reduce(function(l,h){return l[h]="",l},{});!ce(s)||!Te(s)||(Object.assign(s.style,o),Object.keys(n).forEach(function(l){s.removeAttribute(l)}))})}}const Ko={name:"applyStyles",enabled:!0,phase:"write",fn:Fu,effect:Nu,requires:["computeStyles"]};function Ae(r){return r.split("-")[0]}var li=Math.max,Xs=Math.min,Si=Math.round;function ln(){var r=navigator.userAgentData;return r!=null&&r.brands&&Array.isArray(r.brands)?r.brands.map(function(t){return t.brand+"/"+t.version}).join(" "):navigator.userAgent}function jo(){return!/^((?!chrome|android).)*safari/i.test(ln())}function Li(r,t,e){t===void 0&&(t=!1),e===void 0&&(e=!1);var i=r.getBoundingClientRect(),s=1,n=1;t&&ce(r)&&(s=r.offsetWidth>0&&Si(i.width)/r.offsetWidth||1,n=r.offsetHeight>0&&Si(i.height)/r.offsetHeight||1);var a=oi(r)?ie(r):window,o=a.visualViewport,l=!jo()&&e,h=(i.left+(l&&o?o.offsetLeft:0))/s,c=(i.top+(l&&o?o.offsetTop:0))/n,d=i.width/s,u=i.height/n;return{width:d,height:u,top:c,right:h+d,bottom:c+u,left:h,x:h,y:c}}function hn(r){var t=Li(r),e=r.offsetWidth,i=r.offsetHeight;return Math.abs(t.width-e)<=1&&(e=t.width),Math.abs(t.height-i)<=1&&(i=t.height),{x:r.offsetLeft,y:r.offsetTop,width:e,height:i}}function Wo(r,t){var e=t.getRootNode&&t.getRootNode();if(r.contains(t))return!0;if(e&&on(e)){var i=t;do{if(i&&r.isSameNode(i))return!0;i=i.parentNode||i.host}while(i)}return!1}function Oe(r){return ie(r).getComputedStyle(r)}function Uu(r){return["table","td","th"].indexOf(Te(r))>=0}function Ke(r){return((oi(r)?r.ownerDocument:r.document)||window.document).documentElement}function Qs(r){return Te(r)==="html"?r:r.assignedSlot||r.parentNode||(on(r)?r.host:null)||Ke(r)}function Yo(r){return!ce(r)||Oe(r).position==="fixed"?null:r.offsetParent}function Bu(r){var t=/firefox/i.test(ln()),e=/Trident/i.test(ln());if(e&&ce(r)){var i=Oe(r);if(i.position==="fixed")return null}var s=Qs(r);for(on(s)&&(s=s.host);ce(s)&&["html","body"].indexOf(Te(s))<0;){var n=Oe(s);if(n.transform!=="none"||n.perspective!=="none"||n.contain==="paint"||["transform","perspective"].indexOf(n.willChange)!==-1||t&&n.willChange==="filter"||t&&n.filter&&n.filter!=="none")return s;s=s.parentNode}return null}function fs(r){for(var t=ie(r),e=Yo(r);e&&Uu(e)&&Oe(e).position==="static";)e=Yo(e);return e&&(Te(e)==="html"||Te(e)==="body"&&Oe(e).position==="static")?t:e||Bu(r)||t}function cn(r){return["top","bottom"].indexOf(r)>=0?"x":"y"}function ps(r,t,e){return li(r,Xs(t,e))}function Hu(r,t,e){var i=ps(r,t,e);return i>e?e:i}function zo(){return{top:0,right:0,bottom:0,left:0}}function qo(r){return Object.assign({},zo(),r)}function Xo(r,t){return t.reduce(function(e,i){return e[i]=r,e},{})}var Gu=function(t,e){return t=typeof t=="function"?t(Object.assign({},e.rects,{placement:e.placement})):t,qo(typeof t!="number"?t:Xo(t,cs))};function Vu(r){var t,e=r.state,i=r.name,s=r.options,n=e.elements.arrow,a=e.modifiersData.popperOffsets,o=Ae(e.placement),l=cn(o),h=[Xt,he].indexOf(o)>=0,c=h?"height":"width";if(!(!n||!a)){var d=Gu(s.padding,e),u=hn(n),f=l==="y"?qt:Xt,p=l==="y"?le:he,g=e.rects.reference[c]+e.rects.reference[l]-a[l]-e.rects.popper[c],v=a[l]-e.rects.reference[l],E=fs(n),A=E?l==="y"?E.clientHeight||0:E.clientWidth||0:0,L=g/2-v/2,y=d[f],S=A-u[c]-d[p],R=A/2-u[c]/2+L,C=ps(y,R,S),M=l;e.modifiersData[i]=(t={},t[M]=C,t.centerOffset=C-R,t)}}function Ku(r){var t=r.state,e=r.options,i=e.element,s=i===void 0?"[data-popper-arrow]":i;s!=null&&(typeof s=="string"&&(s=t.elements.popper.querySelector(s),!s)||Wo(t.elements.popper,s)&&(t.elements.arrow=s))}const ju={name:"arrow",enabled:!0,phase:"main",fn:Vu,effect:Ku,requires:["popperOffsets"],requiresIfExists:["preventOverflow"]};function Ri(r){return r.split("-")[1]}var Wu={top:"auto",right:"auto",bottom:"auto",left:"auto"};function Yu(r,t){var e=r.x,i=r.y,s=t.devicePixelRatio||1;return{x:Si(e*s)/s||0,y:Si(i*s)/s||0}}function Qo(r){var t,e=r.popper,i=r.popperRect,s=r.placement,n=r.variation,a=r.offsets,o=r.position,l=r.gpuAcceleration,h=r.adaptive,c=r.roundOffsets,d=r.isFixed,u=a.x,f=u===void 0?0:u,p=a.y,g=p===void 0?0:p,v=typeof c=="function"?c({x:f,y:g}):{x:f,y:g};f=v.x,g=v.y;var E=a.hasOwnProperty("x"),A=a.hasOwnProperty("y"),L=Xt,y=qt,S=window;if(h){var R=fs(e),C="clientHeight",M="clientWidth";if(R===ie(e)&&(R=Ke(e),Oe(R).position!=="static"&&o==="absolute"&&(C="scrollHeight",M="scrollWidth")),R=R,s===qt||(s===Xt||s===he)&&n===ds){y=le;var D=d&&R===S&&S.visualViewport?S.visualViewport.height:R[C];g-=D-i.height,g*=l?1:-1}if(s===Xt||(s===qt||s===le)&&n===ds){L=he;var I=d&&R===S&&S.visualViewport?S.visualViewport.width:R[M];f-=I-i.width,f*=l?1:-1}}var G=Object.assign({position:o},h&&Wu),F=c===!0?Yu({x:f,y:g},ie(e)):{x:f,y:g};if(f=F.x,g=F.y,l){var V;return Object.assign({},G,(V={},V[y]=A?"0":"",V[L]=E?"0":"",V.transform=(S.devicePixelRatio||1)<=1?"translate("+f+"px, "+g+"px)":"translate3d("+f+"px, "+g+"px, 0)",V))}return Object.assign({},G,(t={},t[y]=A?g+"px":"",t[L]=E?f+"px":"",t.transform="",t))}function zu(r){var t=r.state,e=r.options,i=e.gpuAcceleration,s=i===void 0?!0:i,n=e.adaptive,a=n===void 0?!0:n,o=e.roundOffsets,l=o===void 0?!0:o,h={placement:Ae(t.placement),variation:Ri(t.placement),popper:t.elements.popper,popperRect:t.rects.popper,gpuAcceleration:s,isFixed:t.options.strategy==="fixed"};t.modifiersData.popperOffsets!=null&&(t.styles.popper=Object.assign({},t.styles.popper,Qo(Object.assign({},h,{offsets:t.modifiersData.popperOffsets,position:t.options.strategy,adaptive:a,roundOffsets:l})))),t.modifiersData.arrow!=null&&(t.styles.arrow=Object.assign({},t.styles.arrow,Qo(Object.assign({},h,{offsets:t.modifiersData.arrow,position:"absolute",adaptive:!1,roundOffsets:l})))),t.attributes.popper=Object.assign({},t.attributes.popper,{"data-popper-placement":t.placement})}const qu={name:"computeStyles",enabled:!0,phase:"beforeWrite",fn:zu,data:{}};var Zs={passive:!0};function Xu(r){var t=r.state,e=r.instance,i=r.options,s=i.scroll,n=s===void 0?!0:s,a=i.resize,o=a===void 0?!0:a,l=ie(t.elements.popper),h=[].concat(t.scrollParents.reference,t.scrollParents.popper);return n&&h.forEach(function(c){c.addEventListener("scroll",e.update,Zs)}),o&&l.addEventListener("resize",e.update,Zs),function(){n&&h.forEach(function(c){c.removeEventListener("scroll",e.update,Zs)}),o&&l.removeEventListener("resize",e.update,Zs)}}const Qu={name:"eventListeners",enabled:!0,phase:"write",fn:function(){},effect:Xu,data:{}};var Zu={left:"right",right:"left",bottom:"top",top:"bottom"};function Js(r){return r.replace(/left|right|bottom|top/g,function(t){return Zu[t]})}var Ju={start:"end",end:"start"};function Zo(r){return r.replace(/start|end/g,function(t){return Ju[t]})}function dn(r){var t=ie(r),e=t.pageXOffset,i=t.pageYOffset;return{scrollLeft:e,scrollTop:i}}function un(r){return Li(Ke(r)).left+dn(r).scrollLeft}function tf(r,t){var e=ie(r),i=Ke(r),s=e.visualViewport,n=i.clientWidth,a=i.clientHeight,o=0,l=0;if(s){n=s.width,a=s.height;var h=jo();(h||!h&&t==="fixed")&&(o=s.offsetLeft,l=s.offsetTop)}return{width:n,height:a,x:o+un(r),y:l}}function ef(r){var t,e=Ke(r),i=dn(r),s=(t=r.ownerDocument)==null?void 0:t.body,n=li(e.scrollWidth,e.clientWidth,s?s.scrollWidth:0,s?s.clientWidth:0),a=li(e.scrollHeight,e.clientHeight,s?s.scrollHeight:0,s?s.clientHeight:0),o=-i.scrollLeft+un(r),l=-i.scrollTop;return Oe(s||e).direction==="rtl"&&(o+=li(e.clientWidth,s?s.clientWidth:0)-n),{width:n,height:a,x:o,y:l}}function fn(r){var t=Oe(r),e=t.overflow,i=t.overflowX,s=t.overflowY;return/auto|scroll|overlay|hidden/.test(e+s+i)}function Jo(r){return["html","body","#document"].indexOf(Te(r))>=0?r.ownerDocument.body:ce(r)&&fn(r)?r:Jo(Qs(r))}function gs(r,t){var e;t===void 0&&(t=[]);var i=Jo(r),s=i===((e=r.ownerDocument)==null?void 0:e.body),n=ie(i),a=s?[n].concat(n.visualViewport||[],fn(i)?i:[]):i,o=t.concat(a);return s?o:o.concat(gs(Qs(a)))}function pn(r){return Object.assign({},r,{left:r.x,top:r.y,right:r.x+r.width,bottom:r.y+r.height})}function sf(r,t){var e=Li(r,!1,t==="fixed");return e.top=e.top+r.clientTop,e.left=e.left+r.clientLeft,e.bottom=e.top+r.clientHeight,e.right=e.left+r.clientWidth,e.width=r.clientWidth,e.height=r.clientHeight,e.x=e.left,e.y=e.top,e}function tl(r,t,e){return t===Ho?pn(tf(r,e)):oi(t)?sf(t,e):pn(ef(Ke(r)))}function rf(r){var t=gs(Qs(r)),e=["absolute","fixed"].indexOf(Oe(r).position)>=0,i=e&&ce(r)?fs(r):r;return oi(i)?t.filter(function(s){return oi(s)&&Wo(s,i)&&Te(s)!=="body"}):[]}function nf(r,t,e,i){var s=t==="clippingParents"?rf(r):[].concat(t),n=[].concat(s,[e]),a=n[0],o=n.reduce(function(l,h){var c=tl(r,h,i);return l.top=li(c.top,l.top),l.right=Xs(c.right,l.right),l.bottom=Xs(c.bottom,l.bottom),l.left=li(c.left,l.left),l},tl(r,a,i));return o.width=o.right-o.left,o.height=o.bottom-o.top,o.x=o.left,o.y=o.top,o}function el(r){var t=r.reference,e=r.element,i=r.placement,s=i?Ae(i):null,n=i?Ri(i):null,a=t.x+t.width/2-e.width/2,o=t.y+t.height/2-e.height/2,l;switch(s){case qt:l={x:a,y:t.y-e.height};break;case le:l={x:a,y:t.y+t.height};break;case he:l={x:t.x+t.width,y:o};break;case Xt:l={x:t.x-e.width,y:o};break;default:l={x:t.x,y:t.y}}var h=s?cn(s):null;if(h!=null){var c=h==="y"?"height":"width";switch(n){case wi:l[h]=l[h]-(t[c]/2-e[c]/2);break;case ds:l[h]=l[h]+(t[c]/2-e[c]/2);break}}return l}function ms(r,t){t===void 0&&(t={});var e=t,i=e.placement,s=i===void 0?r.placement:i,n=e.strategy,a=n===void 0?r.strategy:n,o=e.boundary,l=o===void 0?Lu:o,h=e.rootBoundary,c=h===void 0?Ho:h,d=e.elementContext,u=d===void 0?us:d,f=e.altBoundary,p=f===void 0?!1:f,g=e.padding,v=g===void 0?0:g,E=qo(typeof v!="number"?v:Xo(v,cs)),A=u===us?Ru:us,L=r.rects.popper,y=r.elements[p?A:u],S=nf(oi(y)?y:y.contextElement||Ke(r.elements.popper),l,c,a),R=Li(r.elements.reference),C=el({reference:R,element:L,strategy:"absolute",placement:s}),M=pn(Object.assign({},L,C)),D=u===us?M:R,I={top:S.top-D.top+E.top,bottom:D.bottom-S.bottom+E.bottom,left:S.left-D.left+E.left,right:D.right-S.right+E.right},G=r.modifiersData.offset;if(u===us&&G){var F=G[s];Object.keys(I).forEach(function(V){var z=[he,le].indexOf(V)>=0?1:-1,w=[qt,le].indexOf(V)>=0?"y":"x";I[V]+=F[w]*z})}return I}function af(r,t){t===void 0&&(t={});var e=t,i=e.placement,s=e.boundary,n=e.rootBoundary,a=e.padding,o=e.flipVariations,l=e.allowedAutoPlacements,h=l===void 0?Vo:l,c=Ri(i),d=c?o?Go:Go.filter(function(p){return Ri(p)===c}):cs,u=d.filter(function(p){return h.indexOf(p)>=0});u.length===0&&(u=d);var f=u.reduce(function(p,g){return p[g]=ms(r,{placement:g,boundary:s,rootBoundary:n,padding:a})[Ae(g)],p},{});return Object.keys(f).sort(function(p,g){return f[p]-f[g]})}function of(r){if(Ae(r)===an)return[];var t=Js(r);return[Zo(r),t,Zo(t)]}function lf(r){var t=r.state,e=r.options,i=r.name;if(!t.modifiersData[i]._skip){for(var s=e.mainAxis,n=s===void 0?!0:s,a=e.altAxis,o=a===void 0?!0:a,l=e.fallbackPlacements,h=e.padding,c=e.boundary,d=e.rootBoundary,u=e.altBoundary,f=e.flipVariations,p=f===void 0?!0:f,g=e.allowedAutoPlacements,v=t.options.placement,E=Ae(v),A=E===v,L=l||(A||!p?[Js(v)]:of(v)),y=[v].concat(L).reduce(function(W,X){return W.concat(Ae(X)===an?af(t,{placement:X,boundary:c,rootBoundary:d,padding:h,flipVariations:p,allowedAutoPlacements:g}):X)},[]),S=t.rects.reference,R=t.rects.popper,C=new Map,M=!0,D=y[0],I=0;I<y.length;I++){var G=y[I],F=Ae(G),V=Ri(G)===wi,z=[qt,le].indexOf(F)>=0,w=z?"width":"height",P=ms(t,{placement:G,boundary:c,rootBoundary:d,altBoundary:u,padding:h}),H=z?V?he:Xt:V?le:qt;S[w]>R[w]&&(H=Js(H));var b=Js(H),T=[];if(n&&T.push(P[F]<=0),o&&T.push(P[H]<=0,P[b]<=0),T.every(function(W){return W})){D=G,M=!1;break}C.set(G,T)}if(M)for(var k=p?3:1,N=function(X){var lt=y.find(function(rt){var at=C.get(rt);if(at)return at.slice(0,X).every(function(Rt){return Rt})});if(lt)return D=lt,"break"},U=k;U>0;U--){var K=N(U);if(K==="break")break}t.placement!==D&&(t.modifiersData[i]._skip=!0,t.placement=D,t.reset=!0)}}const hf={name:"flip",enabled:!0,phase:"main",fn:lf,requiresIfExists:["offset"],data:{_skip:!1}};function il(r,t,e){return e===void 0&&(e={x:0,y:0}),{top:r.top-t.height-e.y,right:r.right-t.width+e.x,bottom:r.bottom-t.height+e.y,left:r.left-t.width-e.x}}function sl(r){return[qt,he,le,Xt].some(function(t){return r[t]>=0})}function cf(r){var t=r.state,e=r.name,i=t.rects.reference,s=t.rects.popper,n=t.modifiersData.preventOverflow,a=ms(t,{elementContext:"reference"}),o=ms(t,{altBoundary:!0}),l=il(a,i),h=il(o,s,n),c=sl(l),d=sl(h);t.modifiersData[e]={referenceClippingOffsets:l,popperEscapeOffsets:h,isReferenceHidden:c,hasPopperEscaped:d},t.attributes.popper=Object.assign({},t.attributes.popper,{"data-popper-reference-hidden":c,"data-popper-escaped":d})}const df={name:"hide",enabled:!0,phase:"main",requiresIfExists:["preventOverflow"],fn:cf};function uf(r,t,e){var i=Ae(r),s=[Xt,qt].indexOf(i)>=0?-1:1,n=typeof e=="function"?e(Object.assign({},t,{placement:r})):e,a=n[0],o=n[1];return a=a||0,o=(o||0)*s,[Xt,he].indexOf(i)>=0?{x:o,y:a}:{x:a,y:o}}function ff(r){var t=r.state,e=r.options,i=r.name,s=e.offset,n=s===void 0?[0,0]:s,a=Vo.reduce(function(c,d){return c[d]=uf(d,t.rects,n),c},{}),o=a[t.placement],l=o.x,h=o.y;t.modifiersData.popperOffsets!=null&&(t.modifiersData.popperOffsets.x+=l,t.modifiersData.popperOffsets.y+=h),t.modifiersData[i]=a}const pf={name:"offset",enabled:!0,phase:"main",requires:["popperOffsets"],fn:ff};function gf(r){var t=r.state,e=r.name;t.modifiersData[e]=el({reference:t.rects.reference,element:t.rects.popper,strategy:"absolute",placement:t.placement})}const mf={name:"popperOffsets",enabled:!0,phase:"read",fn:gf,data:{}};function vf(r){return r==="x"?"y":"x"}function yf(r){var t=r.state,e=r.options,i=r.name,s=e.mainAxis,n=s===void 0?!0:s,a=e.altAxis,o=a===void 0?!1:a,l=e.boundary,h=e.rootBoundary,c=e.altBoundary,d=e.padding,u=e.tether,f=u===void 0?!0:u,p=e.tetherOffset,g=p===void 0?0:p,v=ms(t,{boundary:l,rootBoundary:h,padding:d,altBoundary:c}),E=Ae(t.placement),A=Ri(t.placement),L=!A,y=cn(E),S=vf(y),R=t.modifiersData.popperOffsets,C=t.rects.reference,M=t.rects.popper,D=typeof g=="function"?g(Object.assign({},t.rects,{placement:t.placement})):g,I=typeof D=="number"?{mainAxis:D,altAxis:D}:Object.assign({mainAxis:0,altAxis:0},D),G=t.modifiersData.offset?t.modifiersData.offset[t.placement]:null,F={x:0,y:0};if(R){if(n){var V,z=y==="y"?qt:Xt,w=y==="y"?le:he,P=y==="y"?"height":"width",H=R[y],b=H+v[z],T=H-v[w],k=f?-M[P]/2:0,N=A===wi?C[P]:M[P],U=A===wi?-M[P]:-C[P],K=t.elements.arrow,W=f&&K?hn(K):{width:0,height:0},X=t.modifiersData["arrow#persistent"]?t.modifiersData["arrow#persistent"].padding:zo(),lt=X[z],rt=X[w],at=ps(0,C[P],W[P]),Rt=L?C[P]/2-k-at-lt-I.mainAxis:N-at-lt-I.mainAxis,nt=L?-C[P]/2+k+at+rt+I.mainAxis:U+at+rt+I.mainAxis,it=t.elements.arrow&&fs(t.elements.arrow),vt=it?y==="y"?it.clientTop||0:it.clientLeft||0:0,dt=(V=G==null?void 0:G[y])!=null?V:0,Ct=H+Rt-dt-vt,et=H+nt-dt,ut=ps(f?Xs(b,Ct):b,H,f?li(T,et):T);R[y]=ut,F[y]=ut-H}if(o){var bt,pt=y==="x"?qt:Xt,Tt=y==="x"?le:he,_t=R[S],Pt=S==="y"?"height":"width",ft=_t+v[pt],Yt=_t-v[Tt],Ee=[qt,Xt].indexOf(E)!==-1,Ie=(bt=G==null?void 0:G[S])!=null?bt:0,Ht=Ee?ft:_t-C[Pt]-M[Pt]-Ie+I.altAxis,ne=Ee?_t+C[Pt]+M[Pt]-Ie-I.altAxis:Yt,Ni=f&&Ee?Hu(Ht,_t,ne):ps(f?Ht:ft,_t,f?ne:Yt);R[S]=Ni,F[S]=Ni-_t}t.modifiersData[i]=F}}const Ef={name:"preventOverflow",enabled:!0,phase:"main",fn:yf,requiresIfExists:["offset"]};function bf(r){return{scrollLeft:r.scrollLeft,scrollTop:r.scrollTop}}function Tf(r){return r===ie(r)||!ce(r)?dn(r):bf(r)}function Af(r){var t=r.getBoundingClientRect(),e=Si(t.width)/r.offsetWidth||1,i=Si(t.height)/r.offsetHeight||1;return e!==1||i!==1}function wf(r,t,e){e===void 0&&(e=!1);var i=ce(t),s=ce(t)&&Af(t),n=Ke(t),a=Li(r,s,e),o={scrollLeft:0,scrollTop:0},l={x:0,y:0};return(i||!i&&!e)&&((Te(t)!=="body"||fn(n))&&(o=Tf(t)),ce(t)?(l=Li(t,!0),l.x+=t.clientLeft,l.y+=t.clientTop):n&&(l.x=un(n))),{x:a.left+o.scrollLeft-l.x,y:a.top+o.scrollTop-l.y,width:a.width,height:a.height}}function Sf(r){var t=new Map,e=new Set,i=[];r.forEach(function(n){t.set(n.name,n)});function s(n){e.add(n.name);var a=[].concat(n.requires||[],n.requiresIfExists||[]);a.forEach(function(o){if(!e.has(o)){var l=t.get(o);l&&s(l)}}),i.push(n)}return r.forEach(function(n){e.has(n.name)||s(n)}),i}function Lf(r){var t=Sf(r);return Mu.reduce(function(e,i){return e.concat(t.filter(function(s){return s.phase===i}))},[])}function Rf(r){var t;return function(){return t||(t=new Promise(function(e){Promise.resolve().then(function(){t=void 0,e(r())})})),t}}function _f(r){var t=r.reduce(function(e,i){var s=e[i.name];return e[i.name]=s?Object.assign({},s,i,{options:Object.assign({},s.options,i.options),data:Object.assign({},s.data,i.data)}):i,e},{});return Object.keys(t).map(function(e){return t[e]})}var rl={placement:"bottom",modifiers:[],strategy:"absolute"};function nl(){for(var r=arguments.length,t=new Array(r),e=0;e<r;e++)t[e]=arguments[e];return!t.some(function(i){return!(i&&typeof i.getBoundingClientRect=="function")})}function kf(r){r===void 0&&(r={});var t=r,e=t.defaultModifiers,i=e===void 0?[]:e,s=t.defaultOptions,n=s===void 0?rl:s;return function(o,l,h){h===void 0&&(h=n);var c={placement:"bottom",orderedModifiers:[],options:Object.assign({},rl,n),modifiersData:{},elements:{reference:o,popper:l},attributes:{},styles:{}},d=[],u=!1,f={state:c,setOptions:function(E){var A=typeof E=="function"?E(c.options):E;g(),c.options=Object.assign({},n,c.options,A),c.scrollParents={reference:oi(o)?gs(o):o.contextElement?gs(o.contextElement):[],popper:gs(l)};var L=Lf(_f([].concat(i,c.options.modifiers)));return c.orderedModifiers=L.filter(function(y){return y.enabled}),p(),f.update()},forceUpdate:function(){if(!u){var E=c.elements,A=E.reference,L=E.popper;if(nl(A,L)){c.rects={reference:wf(A,fs(L),c.options.strategy==="fixed"),popper:hn(L)},c.reset=!1,c.placement=c.options.placement,c.orderedModifiers.forEach(function(I){return c.modifiersData[I.name]=Object.assign({},I.data)});for(var y=0;y<c.orderedModifiers.length;y++){if(c.reset===!0){c.reset=!1,y=-1;continue}var S=c.orderedModifiers[y],R=S.fn,C=S.options,M=C===void 0?{}:C,D=S.name;typeof R=="function"&&(c=R({state:c,options:M,name:D,instance:f})||c)}}}},update:Rf(function(){return new Promise(function(v){f.forceUpdate(),v(c)})}),destroy:function(){g(),u=!0}};if(!nl(o,l))return f;f.setOptions(h).then(function(v){!u&&h.onFirstUpdate&&h.onFirstUpdate(v)});function p(){c.orderedModifiers.forEach(function(v){var E=v.name,A=v.options,L=A===void 0?{}:A,y=v.effect;if(typeof y=="function"){var S=y({state:c,name:E,instance:f,options:L}),R=function(){};d.push(S||R)}})}function g(){d.forEach(function(v){return v()}),d=[]}return f}}var If=[Qu,mf,qu,Ko,pf,hf,Ef,ju,df],Cf=kf({defaultModifiers:If}),Df="tippy-box",al="tippy-content",xf="tippy-backdrop",ol="tippy-arrow",ll="tippy-svg-arrow",hi={passive:!0,capture:!0},hl=function(){return document.body};function gn(r,t,e){if(Array.isArray(r)){var i=r[t];return i??(Array.isArray(e)?e[t]:e)}return r}function mn(r,t){var e={}.toString.call(r);return e.indexOf("[object")===0&&e.indexOf(t+"]")>-1}function cl(r,t){return typeof r=="function"?r.apply(void 0,t):r}function dl(r,t){if(t===0)return r;var e;return function(i){clearTimeout(e),e=setTimeout(function(){r(i)},t)}}function Pf(r){return r.split(/\s+/).filter(Boolean)}function _i(r){return[].concat(r)}function ul(r,t){r.indexOf(t)===-1&&r.push(t)}function Of(r){return r.filter(function(t,e){return r.indexOf(t)===e})}function $f(r){return r.split("-")[0]}function tr(r){return[].slice.call(r)}function fl(r){return Object.keys(r).reduce(function(t,e){return r[e]!==void 0&&(t[e]=r[e]),t},{})}function vs(){return document.createElement("div")}function er(r){return["Element","Fragment"].some(function(t){return mn(r,t)})}function Mf(r){return mn(r,"NodeList")}function Ff(r){return mn(r,"MouseEvent")}function Nf(r){return!!(r&&r._tippy&&r._tippy.reference===r)}function Uf(r){return er(r)?[r]:Mf(r)?tr(r):Array.isArray(r)?r:tr(document.querySelectorAll(r))}function vn(r,t){r.forEach(function(e){e&&(e.style.transitionDuration=t+"ms")})}function pl(r,t){r.forEach(function(e){e&&e.setAttribute("data-state",t)})}function Bf(r){var t,e=_i(r),i=e[0];return i!=null&&(t=i.ownerDocument)!=null&&t.body?i.ownerDocument:document}function Hf(r,t){var e=t.clientX,i=t.clientY;return r.every(function(s){var n=s.popperRect,a=s.popperState,o=s.props,l=o.interactiveBorder,h=$f(a.placement),c=a.modifiersData.offset;if(!c)return!0;var d=h==="bottom"?c.top.y:0,u=h==="top"?c.bottom.y:0,f=h==="right"?c.left.x:0,p=h==="left"?c.right.x:0,g=n.top-i+d>l,v=i-n.bottom-u>l,E=n.left-e+f>l,A=e-n.right-p>l;return g||v||E||A})}function yn(r,t,e){var i=t+"EventListener";["transitionend","webkitTransitionEnd"].forEach(function(s){r[i](s,e)})}function gl(r,t){for(var e=t;e;){var i;if(r.contains(e))return!0;e=e.getRootNode==null||(i=e.getRootNode())==null?void 0:i.host}return!1}var we={isTouch:!1},ml=0;function Gf(){we.isTouch||(we.isTouch=!0,window.performance&&document.addEventListener("mousemove",vl))}function vl(){var r=performance.now();r-ml<20&&(we.isTouch=!1,document.removeEventListener("mousemove",vl)),ml=r}function Vf(){var r=document.activeElement;if(Nf(r)){var t=r._tippy;r.blur&&!t.state.isVisible&&r.blur()}}function Kf(){document.addEventListener("touchstart",Gf,hi),window.addEventListener("blur",Vf)}var jf=typeof window<"u"&&typeof document<"u",Wf=jf?!!window.msCrypto:!1,Yf={animateFill:!1,followCursor:!1,inlinePositioning:!1,sticky:!1},zf={allowHTML:!1,animation:"fade",arrow:!0,content:"",inertia:!1,maxWidth:350,role:"tooltip",theme:"",zIndex:9999},ge=Object.assign({appendTo:hl,aria:{content:"auto",expanded:"auto"},delay:0,duration:[300,250],getReferenceClientRect:null,hideOnClick:!0,ignoreAttributes:!1,interactive:!1,interactiveBorder:2,interactiveDebounce:0,moveTransition:"",offset:[0,10],onAfterUpdate:function(){},onBeforeUpdate:function(){},onCreate:function(){},onDestroy:function(){},onHidden:function(){},onHide:function(){},onMount:function(){},onShow:function(){},onShown:function(){},onTrigger:function(){},onUntrigger:function(){},onClickOutside:function(){},placement:"top",plugins:[],popperOptions:{},render:null,showOnCreate:!1,touch:!0,trigger:"mouseenter focus",triggerTarget:null},Yf,zf),qf=Object.keys(ge),Xf=function(t){var e=Object.keys(t);e.forEach(function(i){ge[i]=t[i]})};function yl(r){var t=r.plugins||[],e=t.reduce(function(i,s){var n=s.name,a=s.defaultValue;if(n){var o;i[n]=r[n]!==void 0?r[n]:(o=ge[n])!=null?o:a}return i},{});return Object.assign({},r,e)}function Qf(r,t){var e=t?Object.keys(yl(Object.assign({},ge,{plugins:t}))):qf,i=e.reduce(function(s,n){var a=(r.getAttribute("data-tippy-"+n)||"").trim();if(!a)return s;if(n==="content")s[n]=a;else try{s[n]=JSON.parse(a)}catch{s[n]=a}return s},{});return i}function El(r,t){var e=Object.assign({},t,{content:cl(t.content,[r])},t.ignoreAttributes?{}:Qf(r,t.plugins));return e.aria=Object.assign({},ge.aria,e.aria),e.aria={expanded:e.aria.expanded==="auto"?t.interactive:e.aria.expanded,content:e.aria.content==="auto"?t.interactive?null:"describedby":e.aria.content},e}var Zf=function(){return"innerHTML"};function En(r,t){r[Zf()]=t}function bl(r){var t=vs();return r===!0?t.className=ol:(t.className=ll,er(r)?t.appendChild(r):En(t,r)),t}function Tl(r,t){er(t.content)?(En(r,""),r.appendChild(t.content)):typeof t.content!="function"&&(t.allowHTML?En(r,t.content):r.textContent=t.content)}function bn(r){var t=r.firstElementChild,e=tr(t.children);return{box:t,content:e.find(function(i){return i.classList.contains(al)}),arrow:e.find(function(i){return i.classList.contains(ol)||i.classList.contains(ll)}),backdrop:e.find(function(i){return i.classList.contains(xf)})}}function Al(r){var t=vs(),e=vs();e.className=Df,e.setAttribute("data-state","hidden"),e.setAttribute("tabindex","-1");var i=vs();i.className=al,i.setAttribute("data-state","hidden"),Tl(i,r.props),t.appendChild(e),e.appendChild(i),s(r.props,r.props);function s(n,a){var o=bn(t),l=o.box,h=o.content,c=o.arrow;a.theme?l.setAttribute("data-theme",a.theme):l.removeAttribute("data-theme"),typeof a.animation=="string"?l.setAttribute("data-animation",a.animation):l.removeAttribute("data-animation"),a.inertia?l.setAttribute("data-inertia",""):l.removeAttribute("data-inertia"),l.style.maxWidth=typeof a.maxWidth=="number"?a.maxWidth+"px":a.maxWidth,a.role?l.setAttribute("role",a.role):l.removeAttribute("role"),(n.content!==a.content||n.allowHTML!==a.allowHTML)&&Tl(h,r.props),a.arrow?c?n.arrow!==a.arrow&&(l.removeChild(c),l.appendChild(bl(a.arrow))):l.appendChild(bl(a.arrow)):c&&l.removeChild(c)}return{popper:t,onUpdate:s}}Al.$$tippy=!0;var Jf=1,ir=[],Tn=[];function tp(r,t){var e=El(r,Object.assign({},ge,yl(fl(t)))),i,s,n,a=!1,o=!1,l=!1,h=!1,c,d,u,f=[],p=dl(Ct,e.interactiveDebounce),g,v=Jf++,E=null,A=Of(e.plugins),L={isEnabled:!0,isVisible:!1,isDestroyed:!1,isMounted:!1,isShown:!1},y={id:v,reference:r,popper:vs(),popperInstance:E,props:e,state:L,plugins:A,clearDelayTimeouts:Ht,setProps:ne,setContent:Ni,show:ee,hide:vi,hideWithInteractivity:Is,enable:Ee,disable:Ie,unmount:Cs,destroy:Ce};if(!e.render)return y;var S=e.render(y),R=S.popper,C=S.onUpdate;R.setAttribute("data-tippy-root",""),R.id="tippy-"+y.id,y.popper=R,r._tippy=y,R._tippy=y;var M=A.map(function(O){return O.fn(y)}),D=r.hasAttribute("aria-expanded");return it(),k(),H(),b("onCreate",[y]),e.showOnCreate&&ft(),R.addEventListener("mouseenter",function(){y.props.interactive&&y.state.isVisible&&y.clearDelayTimeouts()}),R.addEventListener("mouseleave",function(){y.props.interactive&&y.props.trigger.indexOf("mouseenter")>=0&&z().addEventListener("mousemove",p)}),y;function I(){var O=y.props.touch;return Array.isArray(O)?O:[O,0]}function G(){return I()[0]==="hold"}function F(){var O;return!!((O=y.props.render)!=null&&O.$$tippy)}function V(){return g||r}function z(){var O=V().parentNode;return O?Bf(O):document}function w(){return bn(R)}function P(O){return y.state.isMounted&&!y.state.isVisible||we.isTouch||c&&c.type==="focus"?0:gn(y.props.delay,O?0:1,ge.delay)}function H(O){O===void 0&&(O=!1),R.style.pointerEvents=y.props.interactive&&!O?"":"none",R.style.zIndex=""+y.props.zIndex}function b(O,Y,tt){if(tt===void 0&&(tt=!0),M.forEach(function(ht){ht[O]&&ht[O].apply(ht,Y)}),tt){var gt;(gt=y.props)[O].apply(gt,Y)}}function T(){var O=y.props.aria;if(O.content){var Y="aria-"+O.content,tt=R.id,gt=_i(y.props.triggerTarget||r);gt.forEach(function(ht){var zt=ht.getAttribute(Y);if(y.state.isVisible)ht.setAttribute(Y,zt?zt+" "+tt:tt);else{var pe=zt&&zt.replace(tt,"").trim();pe?ht.setAttribute(Y,pe):ht.removeAttribute(Y)}})}}function k(){if(!(D||!y.props.aria.expanded)){var O=_i(y.props.triggerTarget||r);O.forEach(function(Y){y.props.interactive?Y.setAttribute("aria-expanded",y.state.isVisible&&Y===V()?"true":"false"):Y.removeAttribute("aria-expanded")})}}function N(){z().removeEventListener("mousemove",p),ir=ir.filter(function(O){return O!==p})}function U(O){if(!(we.isTouch&&(l||O.type==="mousedown"))){var Y=O.composedPath&&O.composedPath()[0]||O.target;if(!(y.props.interactive&&gl(R,Y))){if(_i(y.props.triggerTarget||r).some(function(tt){return gl(tt,Y)})){if(we.isTouch||y.state.isVisible&&y.props.trigger.indexOf("click")>=0)return}else b("onClickOutside",[y,O]);y.props.hideOnClick===!0&&(y.clearDelayTimeouts(),y.hide(),o=!0,setTimeout(function(){o=!1}),y.state.isMounted||lt())}}}function K(){l=!0}function W(){l=!1}function X(){var O=z();O.addEventListener("mousedown",U,!0),O.addEventListener("touchend",U,hi),O.addEventListener("touchstart",W,hi),O.addEventListener("touchmove",K,hi)}function lt(){var O=z();O.removeEventListener("mousedown",U,!0),O.removeEventListener("touchend",U,hi),O.removeEventListener("touchstart",W,hi),O.removeEventListener("touchmove",K,hi)}function rt(O,Y){Rt(O,function(){!y.state.isVisible&&R.parentNode&&R.parentNode.contains(R)&&Y()})}function at(O,Y){Rt(O,Y)}function Rt(O,Y){var tt=w().box;function gt(ht){ht.target===tt&&(yn(tt,"remove",gt),Y())}if(O===0)return Y();yn(tt,"remove",d),yn(tt,"add",gt),d=gt}function nt(O,Y,tt){tt===void 0&&(tt=!1);var gt=_i(y.props.triggerTarget||r);gt.forEach(function(ht){ht.addEventListener(O,Y,tt),f.push({node:ht,eventType:O,handler:Y,options:tt})})}function it(){G()&&(nt("touchstart",dt,{passive:!0}),nt("touchend",et,{passive:!0})),Pf(y.props.trigger).forEach(function(O){if(O!=="manual")switch(nt(O,dt),O){case"mouseenter":nt("mouseleave",et);break;case"focus":nt(Wf?"focusout":"blur",ut);break;case"focusin":nt("focusout",ut);break}})}function vt(){f.forEach(function(O){var Y=O.node,tt=O.eventType,gt=O.handler,ht=O.options;Y.removeEventListener(tt,gt,ht)}),f=[]}function dt(O){var Y,tt=!1;if(!(!y.state.isEnabled||bt(O)||o)){var gt=((Y=c)==null?void 0:Y.type)==="focus";c=O,g=O.currentTarget,k(),!y.state.isVisible&&Ff(O)&&ir.forEach(function(ht){return ht(O)}),O.type==="click"&&(y.props.trigger.indexOf("mouseenter")<0||a)&&y.props.hideOnClick!==!1&&y.state.isVisible?tt=!0:ft(O),O.type==="click"&&(a=!tt),tt&&!gt&&Yt(O)}}function Ct(O){var Y=O.target,tt=V().contains(Y)||R.contains(Y);if(!(O.type==="mousemove"&&tt)){var gt=Pt().concat(R).map(function(ht){var zt,pe=ht._tippy,Ui=(zt=pe.popperInstance)==null?void 0:zt.state;return Ui?{popperRect:ht.getBoundingClientRect(),popperState:Ui,props:e}:null}).filter(Boolean);Hf(gt,O)&&(N(),Yt(O))}}function et(O){var Y=bt(O)||y.props.trigger.indexOf("click")>=0&&a;if(!Y){if(y.props.interactive){y.hideWithInteractivity(O);return}Yt(O)}}function ut(O){y.props.trigger.indexOf("focusin")<0&&O.target!==V()||y.props.interactive&&O.relatedTarget&&R.contains(O.relatedTarget)||Yt(O)}function bt(O){return we.isTouch?G()!==O.type.indexOf("touch")>=0:!1}function pt(){Tt();var O=y.props,Y=O.popperOptions,tt=O.placement,gt=O.offset,ht=O.getReferenceClientRect,zt=O.moveTransition,pe=F()?bn(R).arrow:null,Ui=ht?{getBoundingClientRect:ht,contextElement:ht.contextElement||V()}:r,Cc={name:"$$tippy",enabled:!0,phase:"beforeWrite",requires:["computeStyles"],fn:function(kr){var Bi=kr.state;if(F()){var H0=w(),Ca=H0.box;["placement","reference-hidden","escaped"].forEach(function(Ir){Ir==="placement"?Ca.setAttribute("data-placement",Bi.placement):Bi.attributes.popper["data-popper-"+Ir]?Ca.setAttribute("data-"+Ir,""):Ca.removeAttribute("data-"+Ir)}),Bi.attributes.popper={}}}},yi=[{name:"offset",options:{offset:gt}},{name:"preventOverflow",options:{padding:{top:2,bottom:2,left:5,right:5}}},{name:"flip",options:{padding:5}},{name:"computeStyles",options:{adaptive:!zt}},Cc];F()&&pe&&yi.push({name:"arrow",options:{element:pe,padding:3}}),yi.push.apply(yi,(Y==null?void 0:Y.modifiers)||[]),y.popperInstance=Cf(Ui,R,Object.assign({},Y,{placement:tt,onFirstUpdate:u,modifiers:yi}))}function Tt(){y.popperInstance&&(y.popperInstance.destroy(),y.popperInstance=null)}function _t(){var O=y.props.appendTo,Y,tt=V();y.props.interactive&&O===hl||O==="parent"?Y=tt.parentNode:Y=cl(O,[tt]),Y.contains(R)||Y.appendChild(R),y.state.isMounted=!0,pt()}function Pt(){return tr(R.querySelectorAll("[data-tippy-root]"))}function ft(O){y.clearDelayTimeouts(),O&&b("onTrigger",[y,O]),X();var Y=P(!0),tt=I(),gt=tt[0],ht=tt[1];we.isTouch&&gt==="hold"&&ht&&(Y=ht),Y?i=setTimeout(function(){y.show()},Y):y.show()}function Yt(O){if(y.clearDelayTimeouts(),b("onUntrigger",[y,O]),!y.state.isVisible){lt();return}if(!(y.props.trigger.indexOf("mouseenter")>=0&&y.props.trigger.indexOf("click")>=0&&["mouseleave","mousemove"].indexOf(O.type)>=0&&a)){var Y=P(!1);Y?s=setTimeout(function(){y.state.isVisible&&y.hide()},Y):n=requestAnimationFrame(function(){y.hide()})}}function Ee(){y.state.isEnabled=!0}function Ie(){y.hide(),y.state.isEnabled=!1}function Ht(){clearTimeout(i),clearTimeout(s),cancelAnimationFrame(n)}function ne(O){if(!y.state.isDestroyed){b("onBeforeUpdate",[y,O]),vt();var Y=y.props,tt=El(r,Object.assign({},Y,fl(O),{ignoreAttributes:!0}));y.props=tt,it(),Y.interactiveDebounce!==tt.interactiveDebounce&&(N(),p=dl(Ct,tt.interactiveDebounce)),Y.triggerTarget&&!tt.triggerTarget?_i(Y.triggerTarget).forEach(function(gt){gt.removeAttribute("aria-expanded")}):tt.triggerTarget&&r.removeAttribute("aria-expanded"),k(),H(),C&&C(Y,tt),y.popperInstance&&(pt(),Pt().forEach(function(gt){requestAnimationFrame(gt._tippy.popperInstance.forceUpdate)})),b("onAfterUpdate",[y,O])}}function Ni(O){y.setProps({content:O})}function ee(){var O=y.state.isVisible,Y=y.state.isDestroyed,tt=!y.state.isEnabled,gt=we.isTouch&&!y.props.touch,ht=gn(y.props.duration,0,ge.duration);if(!(O||Y||tt||gt)&&!V().hasAttribute("disabled")&&(b("onShow",[y],!1),y.props.onShow(y)!==!1)){if(y.state.isVisible=!0,F()&&(R.style.visibility="visible"),H(),X(),y.state.isMounted||(R.style.transition="none"),F()){var zt=w(),pe=zt.box,Ui=zt.content;vn([pe,Ui],0)}u=function(){var yi;if(!(!y.state.isVisible||h)){if(h=!0,R.offsetHeight,R.style.transition=y.props.moveTransition,F()&&y.props.animation){var Ia=w(),kr=Ia.box,Bi=Ia.content;vn([kr,Bi],ht),pl([kr,Bi],"visible")}T(),k(),ul(Tn,y),(yi=y.popperInstance)==null||yi.forceUpdate(),b("onMount",[y]),y.props.animation&&F()&&at(ht,function(){y.state.isShown=!0,b("onShown",[y])})}},_t()}}function vi(){var O=!y.state.isVisible,Y=y.state.isDestroyed,tt=!y.state.isEnabled,gt=gn(y.props.duration,1,ge.duration);if(!(O||Y||tt)&&(b("onHide",[y],!1),y.props.onHide(y)!==!1)){if(y.state.isVisible=!1,y.state.isShown=!1,h=!1,a=!1,F()&&(R.style.visibility="hidden"),N(),lt(),H(!0),F()){var ht=w(),zt=ht.box,pe=ht.content;y.props.animation&&(vn([zt,pe],gt),pl([zt,pe],"hidden"))}T(),k(),y.props.animation?F()&&rt(gt,y.unmount):y.unmount()}}function Is(O){z().addEventListener("mousemove",p),ul(ir,p),p(O)}function Cs(){y.state.isVisible&&y.hide(),y.state.isMounted&&(Tt(),Pt().forEach(function(O){O._tippy.unmount()}),R.parentNode&&R.parentNode.removeChild(R),Tn=Tn.filter(function(O){return O!==y}),y.state.isMounted=!1,b("onHidden",[y]))}function Ce(){y.state.isDestroyed||(y.clearDelayTimeouts(),y.unmount(),vt(),delete r._tippy,y.state.isDestroyed=!0,b("onDestroy",[y]))}}function ci(r,t){t===void 0&&(t={});var e=ge.plugins.concat(t.plugins||[]);Kf();var i=Object.assign({},t,{plugins:e}),s=Uf(r),n=s.reduce(function(a,o){var l=o&&tp(o,i);return l&&a.push(l),a},[]);return er(r)?n[0]:n}ci.defaultProps=ge,ci.setDefaultProps=Xf,ci.currentInput=we,Object.assign({},Ko,{effect:function(t){var e=t.state,i={popper:{position:e.options.strategy,left:"0",top:"0",margin:"0"},arrow:{position:"absolute"},reference:{}};Object.assign(e.elements.popper.style,i.popper),e.styles=i,e.elements.arrow&&Object.assign(e.elements.arrow.style,i.arrow)}}),ci.setDefaultProps({render:Al});const ep=5;class ip{constructor(t){this._caption="",this._currentTime=0,this._activeScenes=[],this._upcomingScenes=[],this._fakeBufferSegments=[],this._canvas=ae(),this._controls=ae(),this.host=t}set activeScenes(t){if(t!==this._activeScenes){const e=t[0],i=this._activeScenes[0];this._activeScenes=t,e!==i&&(this.host.dispatchEvent(new CustomEvent("scenechange",{detail:t[0]})),this.host.requestUpdate())}}get activeScenes(){return this._activeScenes}set currentTime(t){var e,i,s,n,a;const o=Math.min(this.host.duration,Math.max(0,t));this._currentTime=o,this.activeScenes=((e=this.host.scenes)==null?void 0:e.filter(({start:c,duration:d})=>o>=c&&o<=c+d))??[],this._upcomingScenes=((i=this.host.scenes)==null?void 0:i.filter(({start:c})=>o>=c-ep&&o<c))??[],this.loadScenes(),this.syncVideoState(),(s=this._controls.value)==null||s.setAttribute("currentTime",o.toString());const l=this.activeScenes[0],h=Io((n=l==null?void 0:l.videoMeta)==null?void 0:n.captions);this.caption=((a=h.find(({start:c,end:d})=>{var u;const f=o-l.start+(((u=l.videoMeta)==null?void 0:u.start)??0);return c&&d&&f>=Ks(c)&&f<=Ks(d)}))==null?void 0:a.text)??"",this.draw(o),!this.host.paused&&!this.host.loading&&!this.host.processing&&!this.host.waiting&&!this.host.stalled&&this.host.dispatchEvent(new CustomEvent("timeupdate",{detail:o}))}get currentTime(){return this._currentTime}set fakeBufferSegments(t){t!==this._fakeBufferSegments&&(this._fakeBufferSegments=t,this.host.requestUpdate())}get fakeBufferSegments(){return this._fakeBufferSegments}set caption(t){t!==this._caption&&(this._caption=t,this.host.requestUpdate())}get caption(){return this._caption}canvas(){return oe(this._canvas)}controls(){return oe(this._controls)}loadScenes(){var t;let e=this.fakeBufferSegments;(t=this.host.scenes)==null||t.forEach(i=>{var s,n;const{start:a,duration:o,video:l,videoMeta:h}=i,c=this.activeScenes.includes(i),d=(this._upcomingScenes.includes(i)||c)&&(this.host.currentTime>0||this.host.preload==="auto"||!this.host.paused);if(l&&h){const{id:u,hls:f,node:p}=l,{start:g,duration:v}=h,E=this.host.videoState[u];p&&E&&(p.currentTime>=g+v||p.ended||d&&(f?(s=f.startLoadOnce)==null||s.call(f,p.currentTime):E.initialised||(n=p.startLoadOnce)==null||n.call(p)))}else if(d){const u={start:Math.max(0,a/this.host.duration*100),end:Math.min((a+o)/this.host.duration*100,100)};this.fakeBufferSegments.find(({start:f})=>f===u.start)||(e=[...e,u])}}),this.fakeBufferSegments=e}syncVideoState(){var t;(t=this.host.scenes)==null||t.forEach(e=>{if(e.video){const{id:i,node:s}=e.video,n=this.host.videoState[i],a=this.activeScenes.includes(e);if(s&&n)if(a&&!this.host.waiting&&!this.host.loading&&!this.host.paused){if(s.paused&&n.initialised)return s.play()}else s.paused||s.pause()}})}draw(t=this.currentTime){var e,i;this.host.sceneConfig&&this._canvas.value&&((i=(e=this.host).compilation)==null||i.call(e,{currentTime:t,scenes:this.host.sceneConfig,canvas:this._canvas.value}))}clear(){var t;const e=this._canvas.value;(t=e==null?void 0:e.getContext("2d"))==null||t.clearRect(0,0,e.width,e.height)}}function sp(r){return r&&r.__esModule&&Object.prototype.hasOwnProperty.call(r,"default")?r.default:r}var wl={exports:{}};(function(r,t){(function(e){var i=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,s=/^(?=([^\/?#]*))\1([^]*)$/,n=/(?:\/|^)\.(?=\/)/g,a=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,o={buildAbsoluteURL:function(l,h,c){if(c=c||{},l=l.trim(),h=h.trim(),!h){if(!c.alwaysNormalize)return l;var d=o.parseURL(l);if(!d)throw new Error("Error trying to parse base URL.");return d.path=o.normalizePath(d.path),o.buildURLFromParts(d)}var u=o.parseURL(h);if(!u)throw new Error("Error trying to parse relative URL.");if(u.scheme)return c.alwaysNormalize?(u.path=o.normalizePath(u.path),o.buildURLFromParts(u)):h;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 p=s.exec(f.path);f.netLoc=p[1],f.path=p[2]}f.netLoc&&!f.path&&(f.path="/");var g={scheme:f.scheme,netLoc:u.netLoc,path:null,params:u.params,query:u.query,fragment:u.fragment};if(!u.netLoc&&(g.netLoc=f.netLoc,u.path[0]!=="/"))if(!u.path)g.path=f.path,u.params||(g.params=f.params,u.query||(g.query=f.query));else{var v=f.path,E=v.substring(0,v.lastIndexOf("/")+1)+u.path;g.path=o.normalizePath(E)}return g.path===null&&(g.path=c.alwaysNormalize?o.normalizePath(u.path):u.path),o.buildURLFromParts(g)},parseURL:function(l){var h=i.exec(l);return h?{scheme:h[1]||"",netLoc:h[2]||"",path:h[3]||"",params:h[4]||"",query:h[5]||"",fragment:h[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}};r.exports=o})()})(wl);var An=wl.exports;function Sl(r,t){var e=Object.keys(r);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(r);t&&(i=i.filter(function(s){return Object.getOwnPropertyDescriptor(r,s).enumerable})),e.push.apply(e,i)}return e}function Qt(r){for(var t=1;t<arguments.length;t++){var e=arguments[t]!=null?arguments[t]:{};t%2?Sl(Object(e),!0).forEach(function(i){rp(r,i,e[i])}):Object.getOwnPropertyDescriptors?Object.defineProperties(r,Object.getOwnPropertyDescriptors(e)):Sl(Object(e)).forEach(function(i){Object.defineProperty(r,i,Object.getOwnPropertyDescriptor(e,i))})}return r}function rp(r,t,e){return t=ap(t),t in r?Object.defineProperty(r,t,{value:e,enumerable:!0,configurable:!0,writable:!0}):r[t]=e,r}function Dt(){return Dt=Object.assign?Object.assign.bind():function(r){for(var t=1;t<arguments.length;t++){var e=arguments[t];for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&(r[i]=e[i])}return r},Dt.apply(this,arguments)}function np(r,t){if(typeof r!="object"||r===null)return r;var e=r[Symbol.toPrimitive];if(e!==void 0){var i=e.call(r,t||"default");if(typeof i!="object")return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(r)}function ap(r){var t=np(r,"string");return typeof t=="symbol"?t:String(t)}const q=Number.isFinite||function(r){return typeof r=="number"&&isFinite(r)};let m=function(r){return r.MEDIA_ATTACHING="hlsMediaAttaching",r.MEDIA_ATTACHED="hlsMediaAttached",r.MEDIA_DETACHING="hlsMediaDetaching",r.MEDIA_DETACHED="hlsMediaDetached",r.BUFFER_RESET="hlsBufferReset",r.BUFFER_CODECS="hlsBufferCodecs",r.BUFFER_CREATED="hlsBufferCreated",r.BUFFER_APPENDING="hlsBufferAppending",r.BUFFER_APPENDED="hlsBufferAppended",r.BUFFER_EOS="hlsBufferEos",r.BUFFER_FLUSHING="hlsBufferFlushing",r.BUFFER_FLUSHED="hlsBufferFlushed",r.MANIFEST_LOADING="hlsManifestLoading",r.MANIFEST_LOADED="hlsManifestLoaded",r.MANIFEST_PARSED="hlsManifestParsed",r.LEVEL_SWITCHING="hlsLevelSwitching",r.LEVEL_SWITCHED="hlsLevelSwitched",r.LEVEL_LOADING="hlsLevelLoading",r.LEVEL_LOADED="hlsLevelLoaded",r.LEVEL_UPDATED="hlsLevelUpdated",r.LEVEL_PTS_UPDATED="hlsLevelPtsUpdated",r.LEVELS_UPDATED="hlsLevelsUpdated",r.AUDIO_TRACKS_UPDATED="hlsAudioTracksUpdated",r.AUDIO_TRACK_SWITCHING="hlsAudioTrackSwitching",r.AUDIO_TRACK_SWITCHED="hlsAudioTrackSwitched",r.AUDIO_TRACK_LOADING="hlsAudioTrackLoading",r.AUDIO_TRACK_LOADED="hlsAudioTrackLoaded",r.SUBTITLE_TRACKS_UPDATED="hlsSubtitleTracksUpdated",r.SUBTITLE_TRACKS_CLEARED="hlsSubtitleTracksCleared",r.SUBTITLE_TRACK_SWITCH="hlsSubtitleTrackSwitch",r.SUBTITLE_TRACK_LOADING="hlsSubtitleTrackLoading",r.SUBTITLE_TRACK_LOADED="hlsSubtitleTrackLoaded",r.SUBTITLE_FRAG_PROCESSED="hlsSubtitleFragProcessed",r.CUES_PARSED="hlsCuesParsed",r.NON_NATIVE_TEXT_TRACKS_FOUND="hlsNonNativeTextTracksFound",r.INIT_PTS_FOUND="hlsInitPtsFound",r.FRAG_LOADING="hlsFragLoading",r.FRAG_LOAD_EMERGENCY_ABORTED="hlsFragLoadEmergencyAborted",r.FRAG_LOADED="hlsFragLoaded",r.FRAG_DECRYPTED="hlsFragDecrypted",r.FRAG_PARSING_INIT_SEGMENT="hlsFragParsingInitSegment",r.FRAG_PARSING_USERDATA="hlsFragParsingUserdata",r.FRAG_PARSING_METADATA="hlsFragParsingMetadata",r.FRAG_PARSED="hlsFragParsed",r.FRAG_BUFFERED="hlsFragBuffered",r.FRAG_CHANGED="hlsFragChanged",r.FPS_DROP="hlsFpsDrop",r.FPS_DROP_LEVEL_CAPPING="hlsFpsDropLevelCapping",r.ERROR="hlsError",r.DESTROYING="hlsDestroying",r.KEY_LOADING="hlsKeyLoading",r.KEY_LOADED="hlsKeyLoaded",r.LIVE_BACK_BUFFER_REACHED="hlsLiveBackBufferReached",r.BACK_BUFFER_REACHED="hlsBackBufferReached",r}({}),Q=function(r){return r.NETWORK_ERROR="networkError",r.MEDIA_ERROR="mediaError",r.KEY_SYSTEM_ERROR="keySystemError",r.MUX_ERROR="muxError",r.OTHER_ERROR="otherError",r}({}),$=function(r){return r.KEY_SYSTEM_NO_KEYS="keySystemNoKeys",r.KEY_SYSTEM_NO_ACCESS="keySystemNoAccess",r.KEY_SYSTEM_NO_SESSION="keySystemNoSession",r.KEY_SYSTEM_NO_CONFIGURED_LICENSE="keySystemNoConfiguredLicense",r.KEY_SYSTEM_LICENSE_REQUEST_FAILED="keySystemLicenseRequestFailed",r.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED="keySystemServerCertificateRequestFailed",r.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED="keySystemServerCertificateUpdateFailed",r.KEY_SYSTEM_SESSION_UPDATE_FAILED="keySystemSessionUpdateFailed",r.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED="keySystemStatusOutputRestricted",r.KEY_SYSTEM_STATUS_INTERNAL_ERROR="keySystemStatusInternalError",r.MANIFEST_LOAD_ERROR="manifestLoadError",r.MANIFEST_LOAD_TIMEOUT="manifestLoadTimeOut",r.MANIFEST_PARSING_ERROR="manifestParsingError",r.MANIFEST_INCOMPATIBLE_CODECS_ERROR="manifestIncompatibleCodecsError",r.LEVEL_EMPTY_ERROR="levelEmptyError",r.LEVEL_LOAD_ERROR="levelLoadError",r.LEVEL_LOAD_TIMEOUT="levelLoadTimeOut",r.LEVEL_PARSING_ERROR="levelParsingError",r.LEVEL_SWITCH_ERROR="levelSwitchError",r.AUDIO_TRACK_LOAD_ERROR="audioTrackLoadError",r.AUDIO_TRACK_LOAD_TIMEOUT="audioTrackLoadTimeOut",r.SUBTITLE_LOAD_ERROR="subtitleTrackLoadError",r.SUBTITLE_TRACK_LOAD_TIMEOUT="subtitleTrackLoadTimeOut",r.FRAG_LOAD_ERROR="fragLoadError",r.FRAG_LOAD_TIMEOUT="fragLoadTimeOut",r.FRAG_DECRYPT_ERROR="fragDecryptError",r.FRAG_PARSING_ERROR="fragParsingError",r.FRAG_GAP="fragGap",r.REMUX_ALLOC_ERROR="remuxAllocError",r.KEY_LOAD_ERROR="keyLoadError",r.KEY_LOAD_TIMEOUT="keyLoadTimeOut",r.BUFFER_ADD_CODEC_ERROR="bufferAddCodecError",r.BUFFER_INCOMPATIBLE_CODECS_ERROR="bufferIncompatibleCodecsError",r.BUFFER_APPEND_ERROR="bufferAppendError",r.BUFFER_APPENDING_ERROR="bufferAppendingError",r.BUFFER_STALLED_ERROR="bufferStalledError",r.BUFFER_FULL_ERROR="bufferFullError",r.BUFFER_SEEK_OVER_HOLE="bufferSeekOverHole",r.BUFFER_NUDGE_ON_STALL="bufferNudgeOnStall",r.INTERNAL_EXCEPTION="internalException",r.INTERNAL_ABORTED="aborted",r.UNKNOWN="unknown",r}({});const di=function(){},wn={trace:di,debug:di,log:di,warn:di,info:di,error:di};let ys=wn;function op(r){const t=self.console[r];return t?t.bind(self.console,`[${r}] >`):di}function lp(r,...t){t.forEach(function(e){ys[e]=r[e]?r[e].bind(r):op(e)})}function hp(r,t){if(self.console&&r===!0||typeof r=="object"){lp(r,"debug","log","info","warn","error");try{ys.log(`Debug logs enabled for "${t}" in hls.js version 1.4.12`)}catch{ys=wn}}else ys=wn}const _=ys,cp=/^(\d+)x(\d+)$/,Ll=/(.+?)=(".*?"|.*?)(?:,|$)/g;class St{constructor(t){typeof t=="string"&&(t=St.parseAttrList(t));for(const e in t)t.hasOwnProperty(e)&&(e.substring(0,2)==="X-"&&(this.clientAttrs=this.clientAttrs||[],this.clientAttrs.push(e)),this[e]=t[e])}decimalInteger(t){const e=parseInt(this[t],10);return e>Number.MAX_SAFE_INTEGER?1/0:e}hexadecimalInteger(t){if(this[t]){let e=(this[t]||"0x").slice(2);e=(e.length&1?"0":"")+e;const i=new Uint8Array(e.length/2);for(let s=0;s<e.length/2;s++)i[s]=parseInt(e.slice(s*2,s*2+2),16);return i}else return null}hexadecimalIntegerAsNumber(t){const e=parseInt(this[t],16);return e>Number.MAX_SAFE_INTEGER?1/0:e}decimalFloatingPoint(t){return parseFloat(this[t])}optionalFloat(t,e){const i=this[t];return i?parseFloat(i):e}enumeratedString(t){return this[t]}bool(t){return this[t]==="YES"}decimalResolution(t){const e=cp.exec(this[t]);if(e!==null)return{width:parseInt(e[1],10),height:parseInt(e[2],10)}}static parseAttrList(t){let e;const i={},s='"';for(Ll.lastIndex=0;(e=Ll.exec(t))!==null;){let n=e[2];n.indexOf(s)===0&&n.lastIndexOf(s)===n.length-1&&(n=n.slice(1,-1));const a=e[1].trim();i[a]=n}return i}}function dp(r){return r!=="ID"&&r!=="CLASS"&&r!=="START-DATE"&&r!=="DURATION"&&r!=="END-DATE"&&r!=="END-ON-NEXT"}function up(r){return r==="SCTE35-OUT"||r==="SCTE35-IN"}class Rl{constructor(t,e){if(this.attr=void 0,this._startDate=void 0,this._endDate=void 0,this._badValueForSameId=void 0,e){const i=e.attr;for(const s in i)if(Object.prototype.hasOwnProperty.call(t,s)&&t[s]!==i[s]){_.warn(`DATERANGE tag attribute: "${s}" does not match for tags with ID: "${t.ID}"`),this._badValueForSameId=s;break}t=Dt(new St({}),i,t)}if(this.attr=t,this._startDate=new Date(t["START-DATE"]),"END-DATE"in this.attr){const i=new Date(this.attr["END-DATE"]);q(i.getTime())&&(this._endDate=i)}}get id(){return this.attr.ID}get class(){return this.attr.CLASS}get startDate(){return this._startDate}get endDate(){if(this._endDate)return this._endDate;const t=this.duration;return t!==null?new Date(this._startDate.getTime()+t*1e3):null}get duration(){if("DURATION"in this.attr){const t=this.attr.decimalFloatingPoint("DURATION");if(q(t))return t}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 isValid(){return!!this.id&&!this._badValueForSameId&&q(this.startDate.getTime())&&(this.duration===null||this.duration>=0)&&(!this.endOnNext||!!this.class)}}class sr{constructor(){this.aborted=!1,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}}}var mt={AUDIO:"audio",VIDEO:"video",AUDIOVIDEO:"audiovideo"};class _l{constructor(t){this._byteRange=null,this._url=null,this.baseurl=void 0,this.relurl=void 0,this.elementaryStreams={[mt.AUDIO]:null,[mt.VIDEO]:null,[mt.AUDIOVIDEO]:null},this.baseurl=t}setByteRange(t,e){const i=t.split("@",2),s=[];i.length===1?s[0]=e?e.byteRangeEndOffset:0:s[0]=parseInt(i[1]),s[1]=parseInt(i[0])+s[0],this._byteRange=s}get byteRange(){return this._byteRange?this._byteRange:[]}get byteRangeStartOffset(){return this.byteRange[0]}get byteRangeEndOffset(){return this.byteRange[1]}get url(){return!this._url&&this.baseurl&&this.relurl&&(this._url=An.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""}set url(t){this._url=t}}class Sn extends _l{constructor(t,e){super(e),this._decryptdata=null,this.rawProgramDateTime=null,this.programDateTime=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.deltaPTS=void 0,this.maxStartPTS=void 0,this.minEndPTS=void 0,this.stats=new sr,this.urlId=0,this.data=void 0,this.bitrateTest=!1,this.title=null,this.initSegment=null,this.endList=void 0,this.gap=void 0,this.type=t}get decryptdata(){const{levelkeys:t}=this;if(!t&&!this._decryptdata)return null;if(!this._decryptdata&&this.levelkeys&&!this.levelkeys.NONE){const e=this.levelkeys.identity;if(e)this._decryptdata=e.getDecryptData(this.sn);else{const i=Object.keys(this.levelkeys);if(i.length===1)return this._decryptdata=this.levelkeys[i[0]].getDecryptData(this.sn)}}return this._decryptdata}get end(){return this.start+this.duration}get endProgramDateTime(){if(this.programDateTime===null||!q(this.programDateTime))return null;const t=q(this.duration)?this.duration:0;return this.programDateTime+t*1e3}get encrypted(){var t;if((t=this._decryptdata)!=null&&t.encrypted)return!0;if(this.levelkeys){const e=Object.keys(this.levelkeys),i=e.length;if(i>1||i===1&&this.levelkeys[e[0]].encrypted)return!0}return!1}setKeyFormat(t){if(this.levelkeys){const e=this.levelkeys[t];e&&!this._decryptdata&&(this._decryptdata=e.getDecryptData(this.sn))}}abortRequests(){var t,e;(t=this.loader)==null||t.abort(),(e=this.keyLoader)==null||e.abort()}setElementaryStreamInfo(t,e,i,s,n,a=!1){const{elementaryStreams:o}=this,l=o[t];if(!l){o[t]={startPTS:e,endPTS:i,startDTS:s,endDTS:n,partial:a};return}l.startPTS=Math.min(l.startPTS,e),l.endPTS=Math.max(l.endPTS,i),l.startDTS=Math.min(l.startDTS,s),l.endDTS=Math.max(l.endDTS,n)}clearElementaryStreamInfo(){const{elementaryStreams:t}=this;t[mt.AUDIO]=null,t[mt.VIDEO]=null,t[mt.AUDIOVIDEO]=null}}class fp extends _l{constructor(t,e,i,s,n){super(i),this.fragOffset=0,this.duration=0,this.gap=!1,this.independent=!1,this.relurl=void 0,this.fragment=void 0,this.index=void 0,this.stats=new sr,this.duration=t.decimalFloatingPoint("DURATION"),this.gap=t.bool("GAP"),this.independent=t.bool("INDEPENDENT"),this.relurl=t.enumeratedString("URI"),this.fragment=e,this.index=s;const a=t.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(){const{elementaryStreams:t}=this;return!!(t.audio||t.video||t.audiovideo)}}const pp=10;class gp{constructor(t){this.PTSKnown=!1,this.alignedSliding=!1,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.live=!0,this.ageHeader=0,this.advancedDateTime=void 0,this.updated=!0,this.advanced=!0,this.availabilityDelay=void 0,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=!1,this.canSkipUntil=0,this.canSkipDateRanges=!1,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=!1,this.fragments=[],this.encryptedFragments=[],this.dateRanges={},this.url=t}reloaded(t){if(!t){this.advanced=!0,this.updated=!0;return}const e=this.lastPartSn-t.lastPartSn,i=this.lastPartIndex-t.lastPartIndex;this.updated=this.endSN!==t.endSN||!!i||!!e||!this.live,this.advanced=this.endSN>t.endSN||e>0||e===0&&i>0,this.updated||this.advanced?this.misses=Math.floor(t.misses*.6):this.misses=t.misses+1,this.availabilityDelay=t.availabilityDelay}get hasProgramDateTime(){return this.fragments.length?q(this.fragments[this.fragments.length-1].programDateTime):!1}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||pp}get drift(){const t=this.driftEndTime-this.driftStartTime;return t>0?(this.driftEnd-this.driftStart)*1e3/t:1}get edge(){return this.partEnd||this.fragmentEnd}get partEnd(){var t;return(t=this.partList)!=null&&t.length?this.partList[this.partList.length-1].end:this.fragmentEnd}get fragmentEnd(){var t;return(t=this.fragments)!=null&&t.length?this.fragments[this.fragments.length-1].end:0}get age(){return this.advancedDateTime?Math.max(Date.now()-this.advancedDateTime,0)/1e3:0}get lastPartIndex(){var t;return(t=this.partList)!=null&&t.length?this.partList[this.partList.length-1].index:-1}get lastPartSn(){var t;return(t=this.partList)!=null&&t.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}}function Ln(r){return Uint8Array.from(atob(r),t=>t.charCodeAt(0))}function mp(r){const t=kl(r).subarray(0,16),e=new Uint8Array(16);return e.set(t,16-t.length),e}function vp(r){const t=function(e,i,s){const n=e[i];e[i]=e[s],e[s]=n};t(r,0,3),t(r,1,2),t(r,4,5),t(r,6,7)}function yp(r){const t=r.split(":");let e=null;if(t[0]==="data"&&t.length===2){const i=t[1].split(";"),s=i[i.length-1].split(",");if(s.length===2){const n=s[0]==="base64",a=s[1];n?(i.splice(-1,1),e=Ln(a)):e=mp(a)}}return e}function kl(r){return Uint8Array.from(unescape(encodeURIComponent(r)),t=>t.charCodeAt(0))}var Lt={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},Zt={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.streamingkeydelivery",PLAYREADY:"com.microsoft.playready",WIDEVINE:"urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed"};function Il(r){switch(r){case Zt.FAIRPLAY:return Lt.FAIRPLAY;case Zt.PLAYREADY:return Lt.PLAYREADY;case Zt.WIDEVINE:return Lt.WIDEVINE;case Zt.CLEARKEY:return Lt.CLEARKEY}}var Cl={WIDEVINE:"edef8ba979d64acea3c827dcd51d21ed"};function Ep(r){if(r===Cl.WIDEVINE)return Lt.WIDEVINE}function Dl(r){switch(r){case Lt.FAIRPLAY:return Zt.FAIRPLAY;case Lt.PLAYREADY:return Zt.PLAYREADY;case Lt.WIDEVINE:return Zt.WIDEVINE;case Lt.CLEARKEY:return Zt.CLEARKEY}}function Rn(r){const{drmSystems:t,widevineLicenseUrl:e}=r,i=t?[Lt.FAIRPLAY,Lt.WIDEVINE,Lt.PLAYREADY,Lt.CLEARKEY].filter(s=>!!t[s]):[];return!i[Lt.WIDEVINE]&&e&&i.push(Lt.WIDEVINE),i}const xl=function(){return typeof self<"u"&&self.navigator&&self.navigator.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null}();function bp(r,t,e,i){let s;switch(r){case Lt.FAIRPLAY:s=["cenc","sinf"];break;case Lt.WIDEVINE:case Lt.PLAYREADY:s=["cenc"];break;case Lt.CLEARKEY:s=["cenc","keyids"];break;default:throw new Error(`Unknown key-system: ${r}`)}return Tp(s,t,e,i)}function Tp(r,t,e,i){return[{initDataTypes:r,persistentState:i.persistentState||"not-allowed",distinctiveIdentifier:i.distinctiveIdentifier||"not-allowed",sessionTypes:i.sessionTypes||[i.sessionType||"temporary"],audioCapabilities:t.map(s=>({contentType:`audio/mp4; codecs="${s}"`,robustness:i.audioRobustness||"",encryptionScheme:i.audioEncryptionScheme||null})),videoCapabilities:e.map(s=>({contentType:`video/mp4; codecs="${s}"`,robustness:i.videoRobustness||"",encryptionScheme:i.videoEncryptionScheme||null}))}]}function ui(r,t,e){return Uint8Array.prototype.slice?r.slice(t,e):new Uint8Array(Array.prototype.slice.call(r,t,e))}const _n=(r,t)=>t+10<=r.length&&r[t]===73&&r[t+1]===68&&r[t+2]===51&&r[t+3]<255&&r[t+4]<255&&r[t+6]<128&&r[t+7]<128&&r[t+8]<128&&r[t+9]<128,Pl=(r,t)=>t+10<=r.length&&r[t]===51&&r[t+1]===68&&r[t+2]===73&&r[t+3]<255&&r[t+4]<255&&r[t+6]<128&&r[t+7]<128&&r[t+8]<128&&r[t+9]<128,rr=(r,t)=>{const e=t;let i=0;for(;_n(r,t);){i+=10;const s=nr(r,t+6);i+=s,Pl(r,t+10)&&(i+=10),t+=i}if(i>0)return r.subarray(e,e+i)},nr=(r,t)=>{let e=0;return e=(r[t]&127)<<21,e|=(r[t+1]&127)<<14,e|=(r[t+2]&127)<<7,e|=r[t+3]&127,e},Ap=(r,t)=>_n(r,t)&&nr(r,t+6)+10<=r.length-t,wp=r=>{const t=$l(r);for(let e=0;e<t.length;e++){const i=t[e];if(Ol(i))return Ip(i)}},Ol=r=>r&&r.key==="PRIV"&&r.info==="com.apple.streaming.transportStreamTimestamp",Sp=r=>{const t=String.fromCharCode(r[0],r[1],r[2],r[3]),e=nr(r,4),i=10;return{type:t,size:e,data:r.subarray(i,i+e)}},$l=r=>{let t=0;const e=[];for(;_n(r,t);){const i=nr(r,t+6);t+=10;const s=t+i;for(;t+8<s;){const n=Sp(r.subarray(t)),a=Lp(n);a&&e.push(a),t+=n.size+10}Pl(r,t)&&(t+=10)}return e},Lp=r=>r.type==="PRIV"?Rp(r):r.type[0]==="W"?kp(r):_p(r),Rp=r=>{if(r.size<2)return;const t=Se(r.data,!0),e=new Uint8Array(r.data.subarray(t.length+1));return{key:r.type,info:t,data:e.buffer}},_p=r=>{if(r.size<2)return;if(r.type==="TXXX"){let e=1;const i=Se(r.data.subarray(e),!0);e+=i.length+1;const s=Se(r.data.subarray(e));return{key:r.type,info:i,data:s}}const t=Se(r.data.subarray(1));return{key:r.type,data:t}},kp=r=>{if(r.type==="WXXX"){if(r.size<2)return;let e=1;const i=Se(r.data.subarray(e),!0);e+=i.length+1;const s=Se(r.data.subarray(e));return{key:r.type,info:i,data:s}}const t=Se(r.data);return{key:r.type,data:t}},Ip=r=>{if(r.data.byteLength===8){const t=new Uint8Array(r.data),e=t[3]&1;let i=(t[4]<<23)+(t[5]<<15)+(t[6]<<7)+t[7];return i/=45,e&&(i+=4772185884e-2),Math.round(i)}},Se=(r,t=!1)=>{const e=Cp();if(e){const h=e.decode(r);if(t){const c=h.indexOf("\0");return c!==-1?h.substring(0,c):h}return h.replace(/\0/g,"")}const i=r.length;let s,n,a,o="",l=0;for(;l<i;){if(s=r[l++],s===0&&t)return o;if(!(s===0||s===3))switch(s>>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:o+=String.fromCharCode(s);break;case 12:case 13:n=r[l++],o+=String.fromCharCode((s&31)<<6|n&63);break;case 14:n=r[l++],a=r[l++],o+=String.fromCharCode((s&15)<<12|(n&63)<<6|(a&63)<<0);break}}return o};let kn;function Cp(){return!kn&&typeof self.TextDecoder<"u"&&(kn=new self.TextDecoder("utf-8")),kn}const Le={hexDump:function(r){let t="";for(let e=0;e<r.length;e++){let i=r[e].toString(16);i.length<2&&(i="0"+i),t+=i}return t}},ar=Math.pow(2,32)-1,Dp=[].push,Ml={video:1,audio:2,id3:3,text:4};function Ut(r){return String.fromCharCode.apply(null,r)}function Fl(r,t){const e=r[t]<<8|r[t+1];return e<0?65536+e:e}function J(r,t){const e=Nl(r,t);return e<0?4294967296+e:e}function Nl(r,t){return r[t]<<24|r[t+1]<<16|r[t+2]<<8|r[t+3]}function In(r,t,e){r[t]=e>>24,r[t+1]=e>>16&255,r[t+2]=e>>8&255,r[t+3]=e&255}function ot(r,t){const e=[];if(!t.length)return e;const i=r.byteLength;for(let s=0;s<i;){const n=J(r,s),a=Ut(r.subarray(s+4,s+8)),o=n>1?s+n:i;if(a===t[0])if(t.length===1)e.push(r.subarray(s+8,o));else{const l=ot(r.subarray(s+8,o),t.slice(1));l.length&&Dp.apply(e,l)}s=o}return e}function xp(r){const t=[],e=r[0];let i=8;const s=J(r,i);i+=4;const n=0,a=0;e===0?i+=8:i+=16,i+=2;let o=r.length+a;const l=Fl(r,i);i+=2;for(let h=0;h<l;h++){let c=i;const d=J(r,c);c+=4;const u=d&2147483647;if((d&2147483648)>>>31===1)return _.warn("SIDX has hierarchical references (not supported)"),null;const f=J(r,c);c+=4,t.push({referenceSize:u,subsegmentDuration:f,info:{duration:f/s,start:o,end:o+u-1}}),o+=u,c+=4,i=c}return{earliestPresentationTime:n,timescale:s,version:e,referencesCount:l,references:t}}function Ul(r){const t=[],e=ot(r,["moov","trak"]);for(let i=0;i<e.length;i++){const s=e[i],n=ot(s,["tkhd"])[0];if(n){let a=n[0],o=a===0?12:20;const l=J(n,o),h=ot(s,["mdia","mdhd"])[0];if(h){a=h[0],o=a===0?12:20;const c=J(h,o),d=ot(s,["mdia","hdlr"])[0];if(d){const u=Ut(d.subarray(8,12)),f={soun:mt.AUDIO,vide:mt.VIDEO}[u];if(f){const p=ot(s,["mdia","minf","stbl","stsd"])[0];let g;p&&(g=Ut(p.subarray(12,16))),t[l]={timescale:c,type:f},t[f]={timescale:c,id:l,codec:g}}}}}}return ot(r,["moov","mvex","trex"]).forEach(i=>{const s=J(i,4),n=t[s];n&&(n.default={duration:J(i,12),flags:J(i,20)})}),t}function Pp(r,t){if(!r||!t)return r;const e=t.keyId;return e&&t.isCommonEncryption&&ot(r,["moov","trak"]).forEach(i=>{const s=ot(i,["mdia","minf","stbl","stsd"])[0].subarray(8);let n=ot(s,["enca"]);const a=n.length>0;a||(n=ot(s,["encv"])),n.forEach(o=>{const l=a?o.subarray(28):o.subarray(78);ot(l,["sinf"]).forEach(h=>{const c=Bl(h);if(c){const d=c.subarray(8,24);d.some(u=>u!==0)||(_.log(`[eme] Patching keyId in 'enc${a?"a":"v"}>sinf>>tenc' box: ${Le.hexDump(d)} -> ${Le.hexDump(e)}`),c.set(e,8))}})})}),r}function Bl(r){const t=ot(r,["schm"])[0];if(t){const e=Ut(t.subarray(4,8));if(e==="cbcs"||e==="cenc")return ot(r,["schi","tenc"])[0]}return _.error("[eme] missing 'schm' box"),null}function Op(r,t){return ot(t,["moof","traf"]).reduce((e,i)=>{const s=ot(i,["tfdt"])[0],n=s[0],a=ot(i,["tfhd"]).reduce((o,l)=>{const h=J(l,4),c=r[h];if(c){let d=J(s,4);if(n===1){if(d===ar)return _.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"),o;d*=ar+1,d+=J(s,8)}const u=c.timescale||9e4,f=d/u;if(isFinite(f)&&(o===null||f<o))return f}return o},null);return a!==null&&isFinite(a)&&(e===null||a<e)?a:e},null)}function $p(r,t){let e=0,i=0,s=0;const n=ot(r,["moof","traf"]);for(let a=0;a<n.length;a++){const o=n[a],l=ot(o,["tfhd"])[0],h=J(l,4),c=t[h];if(!c)continue;const d=c.default,u=J(l,0)|(d==null?void 0:d.flags);let f=d==null?void 0:d.duration;u&8&&(u&2?f=J(l,12):f=J(l,8));const p=c.timescale||9e4,g=ot(o,["trun"]);for(let v=0;v<g.length;v++){if(e=Mp(g[v]),!e&&f){const E=J(g[v],4);e=f*E}c.type===mt.VIDEO?i+=e/p:c.type===mt.AUDIO&&(s+=e/p)}}if(i===0&&s===0){let a=0;const o=ot(r,["sidx"]);for(let l=0;l<o.length;l++){const h=xp(o[l]);h!=null&&h.references&&(a+=h.references.reduce((c,d)=>c+d.info.duration||0,0))}return a}return i||s}function Mp(r){const t=J(r,0);let e=8;t&1&&(e+=4),t&4&&(e+=4);let i=0;const s=J(r,4);for(let n=0;n<s;n++){if(t&256){const a=J(r,e);i+=a,e+=4}t&512&&(e+=4),t&1024&&(e+=4),t&2048&&(e+=4)}return i}function Fp(r,t,e){ot(t,["moof","traf"]).forEach(i=>{ot(i,["tfhd"]).forEach(s=>{const n=J(s,4),a=r[n];if(!a)return;const o=a.timescale||9e4;ot(i,["tfdt"]).forEach(l=>{const h=l[0];let c=J(l,4);if(h===0)c-=e*o,c=Math.max(c,0),In(l,4,c);else{c*=Math.pow(2,32),c+=J(l,8),c-=e*o,c=Math.max(c,0);const d=Math.floor(c/(ar+1)),u=Math.floor(c%(ar+1));In(l,4,d),In(l,8,u)}})})})}function Np(r){const t={valid:null,remainder:null},e=ot(r,["moof"]);if(e){if(e.length<2)return t.remainder=r,t}else return t;const i=e[e.length-1];return t.valid=ui(r,0,i.byteOffset-8),t.remainder=ui(r,i.byteOffset-8),t}function fi(r,t){const e=new Uint8Array(r.length+t.length);return e.set(r),e.set(t,r.length),e}function Hl(r,t){const e=[],i=t.samples,s=t.timescale,n=t.id;let a=!1;return ot(i,["moof"]).map(o=>{const l=o.byteOffset-8;ot(o,["traf"]).map(h=>{const c=ot(h,["tfdt"]).map(d=>{const u=d[0];let f=J(d,4);return u===1&&(f*=Math.pow(2,32),f+=J(d,8)),f/s})[0];return c!==void 0&&(r=c),ot(h,["tfhd"]).map(d=>{const u=J(d,4),f=J(d,0)&16777215,p=(f&1)!==0,g=(f&2)!==0,v=(f&8)!==0;let E=0;const A=(f&16)!==0;let L=0;const y=(f&32)!==0;let S=8;u===n&&(p&&(S+=8),g&&(S+=4),v&&(E=J(d,S),S+=4),A&&(L=J(d,S),S+=4),y&&(S+=4),t.type==="video"&&(a=Up(t.codec)),ot(h,["trun"]).map(R=>{const C=R[0],M=J(R,0)&16777215,D=(M&1)!==0;let I=0;const G=(M&4)!==0,F=(M&256)!==0;let V=0;const z=(M&512)!==0;let w=0;const P=(M&1024)!==0,H=(M&2048)!==0;let b=0;const T=J(R,4);let k=8;D&&(I=J(R,k),k+=4),G&&(k+=4);let N=I+l;for(let U=0;U<T;U++){if(F?(V=J(R,k),k+=4):V=E,z?(w=J(R,k),k+=4):w=L,P&&(k+=4),H&&(C===0?b=J(R,k):b=Nl(R,k),k+=4),t.type===mt.VIDEO){let K=0;for(;K<w;){const W=J(i,N);if(N+=4,Bp(a,i[N])){const X=i.subarray(N,N+W);Gl(X,a?2:1,r+b/s,e)}N+=W,K+=W+4}}r+=V/s}}))})})}),e}function Up(r){if(!r)return!1;const t=r.indexOf("."),e=t<0?r:r.substring(0,t);return e==="hvc1"||e==="hev1"||e==="dvh1"||e==="dvhe"}function Bp(r,t){if(r){const e=t>>1&63;return e===39||e===40}else return(t&31)===6}function Gl(r,t,e,i){const s=Vl(r);let n=0;n+=t;let a=0,o=0,l=!1,h=0;for(;n<s.length;){a=0;do{if(n>=s.length)break;h=s[n++],a+=h}while(h===255);o=0;do{if(n>=s.length)break;h=s[n++],o+=h}while(h===255);const c=s.length-n;if(!l&&a===4&&n<s.length){if(l=!0,s[n++]===181){const d=Fl(s,n);if(n+=2,d===49){const u=J(s,n);if(n+=4,u===1195456820){const f=s[n++];if(f===3){const p=s[n++],g=31&p,v=64&p,E=v?2+g*3:0,A=new Uint8Array(E);if(v){A[0]=p;for(let L=1;L<E;L++)A[L]=s[n++]}i.push({type:f,payloadType:a,pts:e,bytes:A})}}}}}else if(a===5&&o<c){if(l=!0,o>16){const d=[];for(let p=0;p<16;p++){const g=s[n++].toString(16);d.push(g.length==1?"0"+g:g),(p===3||p===5||p===7||p===9)&&d.push("-")}const u=o-16,f=new Uint8Array(u);for(let p=0;p<u;p++)f[p]=s[n++];i.push({payloadType:a,pts:e,uuid:d.join(""),userData:Se(f),userDataBytes:f})}}else if(o<c)n+=o;else if(o>c)break}}function Vl(r){const t=r.byteLength,e=[];let i=1;for(;i<t-2;)r[i]===0&&r[i+1]===0&&r[i+2]===3?(e.push(i+2),i+=2):i++;if(e.length===0)return r;const s=t-e.length,n=new Uint8Array(s);let a=0;for(i=0;i<s;a++,i++)a===e[0]&&(a++,e.shift()),n[i]=r[a];return n}function Hp(r){const t=r[0];let e="",i="",s=0,n=0,a=0,o=0,l=0,h=0;if(t===0){for(;Ut(r.subarray(h,h+1))!=="\0";)e+=Ut(r.subarray(h,h+1)),h+=1;for(e+=Ut(r.subarray(h,h+1)),h+=1;Ut(r.subarray(h,h+1))!=="\0";)i+=Ut(r.subarray(h,h+1)),h+=1;i+=Ut(r.subarray(h,h+1)),h+=1,s=J(r,12),n=J(r,16),o=J(r,20),l=J(r,24),h=28}else if(t===1){h+=4,s=J(r,h),h+=4;const d=J(r,h);h+=4;const u=J(r,h);for(h+=4,a=4294967296*d+u,Number.isSafeInteger(a)||(a=Number.MAX_SAFE_INTEGER,_.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),o=J(r,h),h+=4,l=J(r,h),h+=4;Ut(r.subarray(h,h+1))!=="\0";)e+=Ut(r.subarray(h,h+1)),h+=1;for(e+=Ut(r.subarray(h,h+1)),h+=1;Ut(r.subarray(h,h+1))!=="\0";)i+=Ut(r.subarray(h,h+1)),h+=1;i+=Ut(r.subarray(h,h+1)),h+=1}const c=r.subarray(h,r.byteLength);return{schemeIdUri:e,value:i,timeScale:s,presentationTime:a,presentationTimeDelta:n,eventDuration:o,id:l,payload:c}}function Gp(r,...t){const e=t.length;let i=8,s=e;for(;s--;)i+=t[s].byteLength;const 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(r,4),s=0,i=8;s<e;s++)n.set(t[s],i),i+=t[s].byteLength;return n}function Vp(r,t,e){if(r.byteLength!==16)throw new RangeError("Invalid system id");let i,s;if(t){i=1,s=new Uint8Array(t.length*16);for(let o=0;o<t.length;o++){const l=t[o];if(l.byteLength!==16)throw new RangeError("Invalid key");s.set(l,o*16)}}else i=0,s=new Uint8Array;let n;i>0?(n=new Uint8Array(4),t.length>0&&new DataView(n.buffer).setUint32(0,t.length,!1)):n=new Uint8Array;const a=new Uint8Array(4);return e&&e.byteLength>0&&new DataView(a.buffer).setUint32(0,e.byteLength,!1),Gp([112,115,115,104],new Uint8Array([i,0,0,0]),r,n,s,a,e||new Uint8Array)}function Kp(r){if(!(r instanceof ArrayBuffer)||r.byteLength<32)return null;const t={version:0,systemId:"",kids:null,data:null},e=new DataView(r),i=e.getUint32(0);if(r.byteLength!==i&&i>44||e.getUint32(4)!==1886614376||(t.version=e.getUint32(8)>>>24,t.version>1))return null;t.systemId=Le.hexDump(new Uint8Array(r,12,16));const s=e.getUint32(28);if(t.version===0){if(i-32<s)return null;t.data=new Uint8Array(r,32,s)}else if(t.version===1){t.kids=[];for(let n=0;n<s;n++)t.kids.push(new Uint8Array(r,32+n*16,16))}return t}let or={};class Es{static clearKeyUriToKeyIdMap(){or={}}constructor(t,e,i,s=[1],n=null){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=t,this.uri=e,this.keyFormat=i,this.keyFormatVersions=s,this.iv=n,this.encrypted=t?t!=="NONE":!1,this.isCommonEncryption=this.encrypted&&t!=="AES-128"}isSupported(){if(this.method){if(this.method==="AES-128"||this.method==="NONE")return!0;if(this.keyFormat==="identity")return this.method==="SAMPLE-AES";switch(this.keyFormat){case Zt.FAIRPLAY:case Zt.WIDEVINE:case Zt.PLAYREADY:case Zt.CLEARKEY:return["ISO-23001-7","SAMPLE-AES","SAMPLE-AES-CENC","SAMPLE-AES-CTR"].indexOf(this.method)!==-1}}return!1}getDecryptData(t){if(!this.encrypted||!this.uri)return null;if(this.method==="AES-128"&&this.uri&&!this.iv){typeof t!="number"&&(this.method==="AES-128"&&!this.iv&&_.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),t=0);const i=jp(t);return new Es(this.method,this.uri,"identity",this.keyFormatVersions,i)}const e=yp(this.uri);if(e)switch(this.keyFormat){case Zt.WIDEVINE:this.pssh=e,e.length>=22&&(this.keyId=e.subarray(e.length-22,e.length-6));break;case Zt.PLAYREADY:{const i=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=Vp(i,null,e);const s=new Uint16Array(e.buffer,e.byteOffset,e.byteLength/2),n=String.fromCharCode.apply(null,Array.from(s)),a=n.substring(n.indexOf("<"),n.length),o=new DOMParser().parseFromString(a,"text/xml").getElementsByTagName("KID")[0];if(o){const l=o.childNodes[0]?o.childNodes[0].nodeValue:o.getAttribute("VALUE");if(l){const h=Ln(l).subarray(0,16);vp(h),this.keyId=h}}break}default:{let i=e.subarray(0,16);if(i.length!==16){const s=new Uint8Array(16);s.set(i,16-i.length),i=s}this.keyId=i;break}}if(!this.keyId||this.keyId.byteLength!==16){let i=or[this.uri];if(!i){const s=Object.keys(or).length%Number.MAX_SAFE_INTEGER;i=new Uint8Array(16),new DataView(i.buffer,12,4).setUint32(0,s),or[this.uri]=i}this.keyId=i}return this}}function jp(r){const t=new Uint8Array(16);for(let e=12;e<16;e++)t[e]=r>>8*(15-e)&255;return t}const Kl=/\{\$([a-zA-Z0-9-_]+)\}/g;function jl(r){return Kl.test(r)}function Jt(r,t,e){if(r.variableList!==null||r.hasVariableRefs)for(let i=e.length;i--;){const s=e[i],n=t[s];n&&(t[s]=Cn(r,n))}}function Cn(r,t){if(r.variableList!==null||r.hasVariableRefs){const e=r.variableList;return t.replace(Kl,i=>{const s=i.substring(2,i.length-1),n=e==null?void 0:e[s];return n===void 0?(r.playlistParsingError||(r.playlistParsingError=new Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${s}"`)),i):n})}return t}function Wl(r,t,e){let i=r.variableList;i||(r.variableList=i={});let s,n;if("QUERYPARAM"in t){s=t.QUERYPARAM;try{const a=new self.URL(e).searchParams;if(a.has(s))n=a.get(s);else throw new Error(`"${s}" does not match any query parameter in URI: "${e}"`)}catch(a){r.playlistParsingError||(r.playlistParsingError=new Error(`EXT-X-DEFINE QUERYPARAM: ${a.message}`))}}else s=t.NAME,n=t.VALUE;s in i?r.playlistParsingError||(r.playlistParsingError=new Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${s}"`)):i[s]=n||""}function Wp(r,t,e){const i=t.IMPORT;if(e&&i in e){let s=r.variableList;s||(r.variableList=s={}),s[i]=e[i]}else r.playlistParsingError||(r.playlistParsingError=new Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${i}"`))}function lr(){if(!(typeof self>"u"))return self.MediaSource||self.WebKitMediaSource}const Yp={audio:{a3ds:!0,"ac-3":!0,"ac-4":!0,alac:!0,alaw:!0,dra1:!0,"dts+":!0,"dts-":!0,dtsc:!0,dtse:!0,dtsh:!0,"ec-3":!0,enca:!0,g719:!0,g726:!0,m4ae:!0,mha1:!0,mha2:!0,mhm1:!0,mhm2:!0,mlpa:!0,mp4a:!0,"raw ":!0,Opus:!0,opus:!0,samr:!0,sawb:!0,sawp:!0,sevc:!0,sqcp:!0,ssmv:!0,twos:!0,ulaw:!0},video:{avc1:!0,avc2:!0,avc3:!0,avc4:!0,avcp:!0,av01:!0,drac:!0,dva1:!0,dvav:!0,dvh1:!0,dvhe:!0,encv:!0,hev1:!0,hvc1:!0,mjp2:!0,mp4v:!0,mvc1:!0,mvc2:!0,mvc3:!0,mvc4:!0,resv:!0,rv60:!0,s263:!0,svc1:!0,svc2:!0,"vc-1":!0,vp08:!0,vp09:!0},text:{stpp:!0,wvtt:!0}},Yl=lr();function zp(r,t){const e=Yp[t];return!!e&&e[r.slice(0,4)]===!0}function Dn(r,t){var e;return(e=Yl==null?void 0:Yl.isTypeSupported(`${t||"video"}/mp4;codecs="${r}"`))!=null?e:!1}const zl=/#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,ql=/#EXT-X-MEDIA:(.*)/g,qp=/^#EXT(?:INF|-X-TARGETDURATION):/m,Xl=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[\S ]*)/.source,/#EXT-X-BYTERANGE:*(.+)/.source,/#EXT-X-PROGRAM-DATE-TIME:(.+)/.source,/#.*/.source].join("|"),"g"),Xp=new RegExp([/#(EXTM3U)/.source,/#EXT-X-(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)/.source,/(#)([^:]*):(.*)/.source,/(#)(.*)(?:.*)\r?\n?/.source].join("|"));class me{static findGroup(t,e){for(let i=0;i<t.length;i++){const s=t[i];if(s.id===e)return s}}static convertAVC1ToAVCOTI(t){const e=t.split(".");if(e.length>2){let i=e.shift()+".";return i+=parseInt(e.shift()).toString(16),i+=("000"+parseInt(e.shift()).toString(16)).slice(-4),i}return t}static resolve(t,e){return An.buildAbsoluteURL(e,t,{alwaysNormalize:!0})}static isMediaPlaylist(t){return qp.test(t)}static parseMasterPlaylist(t,e){const i=jl(t),s={contentSteering:null,levels:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:i},n=[];zl.lastIndex=0;let a;for(;(a=zl.exec(t))!=null;)if(a[1]){var o;const h=new St(a[1]);Jt(s,h,["CODECS","SUPPLEMENTAL-CODECS","ALLOWED-CPC","PATHWAY-ID","STABLE-VARIANT-ID","AUDIO","VIDEO","SUBTITLES","CLOSED-CAPTIONS","NAME"]);const c=Cn(s,a[2]),d={attrs:h,bitrate:h.decimalInteger("AVERAGE-BANDWIDTH")||h.decimalInteger("BANDWIDTH"),name:h.NAME,url:me.resolve(c,e)},u=h.decimalResolution("RESOLUTION");u&&(d.width=u.width,d.height=u.height),Qp((h.CODECS||"").split(/[ ,]+/).filter(f=>f),d),d.videoCodec&&d.videoCodec.indexOf("avc1")!==-1&&(d.videoCodec=me.convertAVC1ToAVCOTI(d.videoCodec)),(o=d.unknownCodecs)!=null&&o.length||n.push(d),s.levels.push(d)}else if(a[3]){const h=a[3],c=a[4];switch(h){case"SESSION-DATA":{const d=new St(c);Jt(s,d,["DATA-ID","LANGUAGE","VALUE","URI"]);const u=d["DATA-ID"];u&&(s.sessionData===null&&(s.sessionData={}),s.sessionData[u]=d);break}case"SESSION-KEY":{const d=Ql(c,e,s);d.encrypted&&d.isSupported()?(s.sessionKeys===null&&(s.sessionKeys=[]),s.sessionKeys.push(d)):_.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${c}"`);break}case"DEFINE":{{const d=new St(c);Jt(s,d,["NAME","VALUE","QUERYPARAM"]),Wl(s,d,e)}break}case"CONTENT-STEERING":{const d=new St(c);Jt(s,d,["SERVER-URI","PATHWAY-ID"]),s.contentSteering={uri:me.resolve(d["SERVER-URI"],e),pathwayId:d["PATHWAY-ID"]||"."};break}case"START":{s.startTimeOffset=Zl(c);break}}}const l=n.length>0&&n.length<s.levels.length;return s.levels=l?n:s.levels,s.levels.length===0&&(s.playlistParsingError=new Error("no levels found in manifest")),s}static parseMasterPlaylistMedia(t,e,i){let s;const n={},a=i.levels,o={AUDIO:a.map(h=>({id:h.attrs.AUDIO,audioCodec:h.audioCodec})),SUBTITLES:a.map(h=>({id:h.attrs.SUBTITLES,textCodec:h.textCodec})),"CLOSED-CAPTIONS":[]};let l=0;for(ql.lastIndex=0;(s=ql.exec(t))!==null;){const h=new St(s[1]),c=h.TYPE;if(c){const d=o[c],u=n[c]||[];n[c]=u,Jt(i,h,["URI","GROUP-ID","LANGUAGE","ASSOC-LANGUAGE","STABLE-RENDITION-ID","NAME","INSTREAM-ID","CHARACTERISTICS","CHANNELS"]);const f={attrs:h,bitrate:0,id:l++,groupId:h["GROUP-ID"]||"",instreamId:h["INSTREAM-ID"],name:h.NAME||h.LANGUAGE||"",type:c,default:h.bool("DEFAULT"),autoselect:h.bool("AUTOSELECT"),forced:h.bool("FORCED"),lang:h.LANGUAGE,url:h.URI?me.resolve(h.URI,e):""};if(d!=null&&d.length){const p=me.findGroup(d,f.groupId)||d[0];Jl(f,p,"audioCodec"),Jl(f,p,"textCodec")}u.push(f)}}return n}static parseLevelPlaylist(t,e,i,s,n,a){const o=new gp(e),l=o.fragments;let h=null,c=0,d=0,u=0,f=0,p=null,g=new Sn(s,e),v,E,A,L=-1,y=!1;for(Xl.lastIndex=0,o.m3u8=t,o.hasVariableRefs=jl(t);(v=Xl.exec(t))!==null;){y&&(y=!1,g=new Sn(s,e),g.start=u,g.sn=c,g.cc=f,g.level=i,h&&(g.initSegment=h,g.rawProgramDateTime=h.rawProgramDateTime,h.rawProgramDateTime=null));const M=v[1];if(M){g.duration=parseFloat(M);const D=(" "+v[2]).slice(1);g.title=D||null,g.tagList.push(D?["INF",M,D]:["INF",M])}else if(v[3]){if(q(g.duration)){g.start=u,A&&ih(g,A,o),g.sn=c,g.level=i,g.cc=f,g.urlId=n,l.push(g);const D=(" "+v[3]).slice(1);g.relurl=Cn(o,D),th(g,p),p=g,u+=g.duration,c++,d=0,y=!0}}else if(v[4]){const D=(" "+v[4]).slice(1);p?g.setByteRange(D,p):g.setByteRange(D)}else if(v[5])g.rawProgramDateTime=(" "+v[5]).slice(1),g.tagList.push(["PROGRAM-DATE-TIME",g.rawProgramDateTime]),L===-1&&(L=l.length);else{if(v=v[0].match(Xp),!v){_.warn("No matches on slow regex match for level playlist!");continue}for(E=1;E<v.length&&!(typeof v[E]<"u");E++);const D=(" "+v[E]).slice(1),I=(" "+v[E+1]).slice(1),G=v[E+2]?(" "+v[E+2]).slice(1):"";switch(D){case"PLAYLIST-TYPE":o.type=I.toUpperCase();break;case"MEDIA-SEQUENCE":c=o.startSN=parseInt(I);break;case"SKIP":{const F=new St(I);Jt(o,F,["RECENTLY-REMOVED-DATERANGES"]);const V=F.decimalInteger("SKIPPED-SEGMENTS");if(q(V)){o.skippedSegments=V;for(let w=V;w--;)l.unshift(null);c+=V}const z=F.enumeratedString("RECENTLY-REMOVED-DATERANGES");z&&(o.recentlyRemovedDateranges=z.split(" "));break}case"TARGETDURATION":o.targetduration=Math.max(parseInt(I),1);break;case"VERSION":o.version=parseInt(I);break;case"EXTM3U":break;case"ENDLIST":o.live=!1;break;case"#":(I||G)&&g.tagList.push(G?[I,G]:[I]);break;case"DISCONTINUITY":f++,g.tagList.push(["DIS"]);break;case"GAP":g.gap=!0,g.tagList.push([D]);break;case"BITRATE":g.tagList.push([D,I]);break;case"DATERANGE":{const F=new St(I);Jt(o,F,["ID","CLASS","START-DATE","END-DATE","SCTE35-CMD","SCTE35-OUT","SCTE35-IN"]),Jt(o,F,F.clientAttrs);const V=new Rl(F,o.dateRanges[F.ID]);V.isValid||o.skippedSegments?o.dateRanges[V.id]=V:_.warn(`Ignoring invalid DATERANGE tag: "${I}"`),g.tagList.push(["EXT-X-DATERANGE",I]);break}case"DEFINE":{{const F=new St(I);Jt(o,F,["NAME","VALUE","IMPORT","QUERYPARAM"]),"IMPORT"in F?Wp(o,F,a):Wl(o,F,e)}break}case"DISCONTINUITY-SEQUENCE":f=parseInt(I);break;case"KEY":{const F=Ql(I,e,o);if(F.isSupported()){if(F.method==="NONE"){A=void 0;break}A||(A={}),A[F.keyFormat]&&(A=Dt({},A)),A[F.keyFormat]=F}else _.warn(`[Keys] Ignoring invalid EXT-X-KEY tag: "${I}"`);break}case"START":o.startTimeOffset=Zl(I);break;case"MAP":{const F=new St(I);if(Jt(o,F,["BYTERANGE","URI"]),g.duration){const V=new Sn(s,e);eh(V,F,i,A),h=V,g.initSegment=h,h.rawProgramDateTime&&!g.rawProgramDateTime&&(g.rawProgramDateTime=h.rawProgramDateTime)}else eh(g,F,i,A),h=g,y=!0;break}case"SERVER-CONTROL":{const F=new St(I);o.canBlockReload=F.bool("CAN-BLOCK-RELOAD"),o.canSkipUntil=F.optionalFloat("CAN-SKIP-UNTIL",0),o.canSkipDateRanges=o.canSkipUntil>0&&F.bool("CAN-SKIP-DATERANGES"),o.partHoldBack=F.optionalFloat("PART-HOLD-BACK",0),o.holdBack=F.optionalFloat("HOLD-BACK",0);break}case"PART-INF":{const F=new St(I);o.partTarget=F.decimalFloatingPoint("PART-TARGET");break}case"PART":{let F=o.partList;F||(F=o.partList=[]);const V=d>0?F[F.length-1]:void 0,z=d++,w=new St(I);Jt(o,w,["BYTERANGE","URI"]);const P=new fp(w,g,e,z,V);F.push(P),g.duration+=P.duration;break}case"PRELOAD-HINT":{const F=new St(I);Jt(o,F,["URI"]),o.preloadHint=F;break}case"RENDITION-REPORT":{const F=new St(I);Jt(o,F,["URI"]),o.renditionReports=o.renditionReports||[],o.renditionReports.push(F);break}default:_.warn(`line parsed but not handled: ${v}`);break}}}p&&!p.relurl?(l.pop(),u-=p.duration,o.partList&&(o.fragmentHint=p)):o.partList&&(th(g,p),g.cc=f,o.fragmentHint=g,A&&ih(g,A,o));const S=l.length,R=l[0],C=l[S-1];if(u+=o.skippedSegments*o.targetduration,u>0&&S&&C){o.averagetargetduration=u/S;const M=C.sn;o.endSN=M!=="initSegment"?M:0,o.live||(C.endList=!0),R&&(o.startCC=R.cc)}else o.endSN=0,o.startCC=0;return o.fragmentHint&&(u+=o.fragmentHint.duration),o.totalduration=u,o.endCC=f,L>0&&Zp(l,L),o}}function Ql(r,t,e){var i,s;const n=new St(r);Jt(e,n,["KEYFORMAT","KEYFORMATVERSIONS","URI","IV","URI"]);const a=(i=n.METHOD)!=null?i:"",o=n.URI,l=n.hexadecimalInteger("IV"),h=n.KEYFORMATVERSIONS,c=(s=n.KEYFORMAT)!=null?s:"identity";o&&n.IV&&!l&&_.error(`Invalid IV: ${n.IV}`);const d=o?me.resolve(o,t):"",u=(h||"1").split("/").map(Number).filter(Number.isFinite);return new Es(a,d,c,u,l)}function Zl(r){const t=new St(r).decimalFloatingPoint("TIME-OFFSET");return q(t)?t:null}function Qp(r,t){["video","audio","text"].forEach(e=>{const i=r.filter(s=>zp(s,e));if(i.length){const s=i.filter(n=>n.lastIndexOf("avc1",0)===0||n.lastIndexOf("mp4a",0)===0);t[`${e}Codec`]=s.length>0?s[0]:i[0],r=r.filter(n=>i.indexOf(n)===-1)}}),t.unknownCodecs=r}function Jl(r,t,e){const i=t[e];i&&(r[e]=i)}function Zp(r,t){let e=r[t];for(let i=t;i--;){const s=r[i];if(!s)return;s.programDateTime=e.programDateTime-s.duration*1e3,e=s}}function th(r,t){r.rawProgramDateTime?r.programDateTime=Date.parse(r.rawProgramDateTime):t!=null&&t.programDateTime&&(r.programDateTime=t.endProgramDateTime),q(r.programDateTime)||(r.programDateTime=null,r.rawProgramDateTime=null)}function eh(r,t,e,i){r.relurl=t.URI,t.BYTERANGE&&r.setByteRange(t.BYTERANGE),r.level=e,r.sn="initSegment",i&&(r.levelkeys=i),r.initSegment=null}function ih(r,t,e){r.levelkeys=t;const{encryptedFragments:i}=e;(!i.length||i[i.length-1].levelkeys!==t)&&Object.keys(t).some(s=>t[s].isCommonEncryption)&&i.push(r)}var ct={MANIFEST:"manifest",LEVEL:"level",AUDIO_TRACK:"audioTrack",SUBTITLE_TRACK:"subtitleTrack"},Z={MAIN:"main",AUDIO:"audio",SUBTITLE:"subtitle"};function sh(r){const{type:t}=r;switch(t){case ct.AUDIO_TRACK:return Z.AUDIO;case ct.SUBTITLE_TRACK:return Z.SUBTITLE;default:return Z.MAIN}}function xn(r,t){let e=r.url;return(e===void 0||e.indexOf("data:")===0)&&(e=t.url),e}class Jp{constructor(t){this.hls=void 0,this.loaders=Object.create(null),this.variableList=null,this.hls=t,this.registerListeners()}startLoad(t){}stopLoad(){this.destroyInternalLoaders()}registerListeners(){const{hls:t}=this;t.on(m.MANIFEST_LOADING,this.onManifestLoading,this),t.on(m.LEVEL_LOADING,this.onLevelLoading,this),t.on(m.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),t.on(m.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this)}unregisterListeners(){const{hls:t}=this;t.off(m.MANIFEST_LOADING,this.onManifestLoading,this),t.off(m.LEVEL_LOADING,this.onLevelLoading,this),t.off(m.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),t.off(m.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this)}createInternalLoader(t){const e=this.hls.config,i=e.pLoader,s=e.loader,n=i||s,a=new n(e);return this.loaders[t.type]=a,a}getInternalLoader(t){return this.loaders[t.type]}resetInternalLoader(t){this.loaders[t]&&delete this.loaders[t]}destroyInternalLoaders(){for(const t in this.loaders){const e=this.loaders[t];e&&e.destroy(),this.resetInternalLoader(t)}}destroy(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders()}onManifestLoading(t,e){const{url:i}=e;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:ct.MANIFEST,url:i,deliveryDirectives:null})}onLevelLoading(t,e){const{id:i,level:s,url:n,deliveryDirectives:a}=e;this.load({id:i,level:s,responseType:"text",type:ct.LEVEL,url:n,deliveryDirectives:a})}onAudioTrackLoading(t,e){const{id:i,groupId:s,url:n,deliveryDirectives:a}=e;this.load({id:i,groupId:s,level:null,responseType:"text",type:ct.AUDIO_TRACK,url:n,deliveryDirectives:a})}onSubtitleTrackLoading(t,e){const{id:i,groupId:s,url:n,deliveryDirectives:a}=e;this.load({id:i,groupId:s,level:null,responseType:"text",type:ct.SUBTITLE_TRACK,url:n,deliveryDirectives:a})}load(t){var e;const i=this.hls.config;let s=this.getInternalLoader(t);if(s){const h=s.context;if(h&&h.url===t.url){_.trace("[playlist-loader]: playlist request ongoing");return}_.log(`[playlist-loader]: aborting previous loader for type: ${t.type}`),s.abort()}let n;if(t.type===ct.MANIFEST?n=i.manifestLoadPolicy.default:n=Dt({},i.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),s=this.createInternalLoader(t),(e=t.deliveryDirectives)!=null&&e.part){let h;if(t.type===ct.LEVEL&&t.level!==null?h=this.hls.levels[t.level].details:t.type===ct.AUDIO_TRACK&&t.id!==null?h=this.hls.audioTracks[t.id].details:t.type===ct.SUBTITLE_TRACK&&t.id!==null&&(h=this.hls.subtitleTracks[t.id].details),h){const c=h.partTarget,d=h.targetduration;if(c&&d){const u=Math.max(c*3,d*.8)*1e3;n=Dt({},n,{maxTimeToFirstByteMs:Math.min(u,n.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(u,n.maxTimeToFirstByteMs)})}}}const 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:(h,c,d,u)=>{const f=this.getInternalLoader(d);this.resetInternalLoader(d.type);const p=h.data;if(p.indexOf("#EXTM3U")!==0){this.handleManifestParsingError(h,d,new Error("no EXTM3U delimiter"),u||null,c);return}c.parsing.start=performance.now(),me.isMediaPlaylist(p)?this.handleTrackOrLevelPlaylist(h,c,d,u||null,f):this.handleMasterPlaylist(h,c,d,u)},onError:(h,c,d,u)=>{this.handleNetworkError(c,d,!1,h,u)},onTimeout:(h,c,d)=>{this.handleNetworkError(c,d,!0,void 0,h)}};s.load(t,o,l)}handleMasterPlaylist(t,e,i,s){const n=this.hls,a=t.data,o=xn(t,i),l=me.parseMasterPlaylist(a,o);if(l.playlistParsingError){this.handleManifestParsingError(t,i,l.playlistParsingError,s,e);return}const{contentSteering:h,levels:c,sessionData:d,sessionKeys:u,startTimeOffset:f,variableList:p}=l;this.variableList=p;const{AUDIO:g=[],SUBTITLES:v,"CLOSED-CAPTIONS":E}=me.parseMasterPlaylistMedia(a,o,l);g.length&&!g.some(A=>!A.url)&&c[0].audioCodec&&!c[0].attrs.AUDIO&&(_.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),g.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new St({}),bitrate:0,url:""})),n.trigger(m.MANIFEST_LOADED,{levels:c,audioTracks:g,subtitles:v,captions:E,contentSteering:h,url:o,stats:e,networkDetails:s,sessionData:d,sessionKeys:u,startTimeOffset:f,variableList:p})}handleTrackOrLevelPlaylist(t,e,i,s,n){const a=this.hls,{id:o,level:l,type:h}=i,c=xn(t,i),d=q(o)?o:0,u=q(l)?l:d,f=sh(i),p=me.parseLevelPlaylist(t.data,c,u,f,d,this.variableList);if(h===ct.MANIFEST){const g={attrs:new St({}),bitrate:0,details:p,name:"",url:c};a.trigger(m.MANIFEST_LOADED,{levels:[g],audioTracks:[],url:c,stats:e,networkDetails:s,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}e.parsing.end=performance.now(),i.levelDetails=p,this.handlePlaylistLoaded(p,t,e,i,s,n)}handleManifestParsingError(t,e,i,s,n){this.hls.trigger(m.ERROR,{type:Q.NETWORK_ERROR,details:$.MANIFEST_PARSING_ERROR,fatal:e.type===ct.MANIFEST,url:t.url,err:i,error:i,reason:i.message,response:t,context:e,networkDetails:s,stats:n})}handleNetworkError(t,e,i=!1,s,n){let a=`A network ${i?"timeout":"error"+(s?" (status "+s.code+")":"")} occurred while loading ${t.type}`;t.type===ct.LEVEL?a+=`: ${t.level} id: ${t.id}`:(t.type===ct.AUDIO_TRACK||t.type===ct.SUBTITLE_TRACK)&&(a+=` id: ${t.id} group-id: "${t.groupId}"`);const o=new Error(a);_.warn(`[playlist-loader]: ${a}`);let l=$.UNKNOWN,h=!1;const c=this.getInternalLoader(t);switch(t.type){case ct.MANIFEST:l=i?$.MANIFEST_LOAD_TIMEOUT:$.MANIFEST_LOAD_ERROR,h=!0;break;case ct.LEVEL:l=i?$.LEVEL_LOAD_TIMEOUT:$.LEVEL_LOAD_ERROR,h=!1;break;case ct.AUDIO_TRACK:l=i?$.AUDIO_TRACK_LOAD_TIMEOUT:$.AUDIO_TRACK_LOAD_ERROR,h=!1;break;case ct.SUBTITLE_TRACK:l=i?$.SUBTITLE_TRACK_LOAD_TIMEOUT:$.SUBTITLE_LOAD_ERROR,h=!1;break}c&&this.resetInternalLoader(t.type);const d={type:Q.NETWORK_ERROR,details:l,fatal:h,url:t.url,loader:c,context:t,error:o,networkDetails:e,stats:n};if(s){const u=(e==null?void 0:e.url)||t.url;d.response=Qt({url:u,data:void 0},s)}this.hls.trigger(m.ERROR,d)}handlePlaylistLoaded(t,e,i,s,n,a){const o=this.hls,{type:l,level:h,id:c,groupId:d,deliveryDirectives:u}=s,f=xn(e,s),p=sh(s),g=typeof s.level=="number"&&p===Z.MAIN?h:void 0;if(!t.fragments.length){const E=new Error("No Segments found in Playlist");o.trigger(m.ERROR,{type:Q.NETWORK_ERROR,details:$.LEVEL_EMPTY_ERROR,fatal:!1,url:f,error:E,reason:E.message,response:e,context:s,level:g,parent:p,networkDetails:n,stats:i});return}t.targetduration||(t.playlistParsingError=new Error("Missing Target Duration"));const v=t.playlistParsingError;if(v){o.trigger(m.ERROR,{type:Q.NETWORK_ERROR,details:$.LEVEL_PARSING_ERROR,fatal:!1,url:f,error:v,reason:v.message,response:e,context:s,level:g,parent:p,networkDetails:n,stats:i});return}switch(t.live&&a&&(a.getCacheAge&&(t.ageHeader=a.getCacheAge()||0),(!a.getCacheAge||isNaN(t.ageHeader))&&(t.ageHeader=0)),l){case ct.MANIFEST:case ct.LEVEL:o.trigger(m.LEVEL_LOADED,{details:t,level:g||0,id:c||0,stats:i,networkDetails:n,deliveryDirectives:u});break;case ct.AUDIO_TRACK:o.trigger(m.AUDIO_TRACK_LOADED,{details:t,id:c||0,groupId:d||"",stats:i,networkDetails:n,deliveryDirectives:u});break;case ct.SUBTITLE_TRACK:o.trigger(m.SUBTITLE_TRACK_LOADED,{details:t,id:c||0,groupId:d||"",stats:i,networkDetails:n,deliveryDirectives:u});break}}}function rh(r,t){let e;try{e=new Event("addtrack")}catch{e=document.createEvent("Event"),e.initEvent("addtrack",!1,!1)}e.track=r,t.dispatchEvent(e)}function nh(r,t){const e=r.mode;if(e==="disabled"&&(r.mode="hidden"),r.cues&&!r.cues.getCueById(t.id))try{if(r.addCue(t),!r.cues.getCueById(t.id))throw new Error(`addCue is failed for: ${t}`)}catch(i){_.debug(`[texttrack-utils]: ${i}`);try{const s=new self.TextTrackCue(t.startTime,t.endTime,t.text);s.id=t.id,r.addCue(s)}catch(s){_.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${s}`)}}e==="disabled"&&(r.mode=e)}function ki(r){const t=r.mode;if(t==="disabled"&&(r.mode="hidden"),r.cues)for(let e=r.cues.length;e--;)r.removeCue(r.cues[e]);t==="disabled"&&(r.mode=t)}function Pn(r,t,e,i){const s=r.mode;if(s==="disabled"&&(r.mode="hidden"),r.cues&&r.cues.length>0){const n=eg(r.cues,t,e);for(let a=0;a<n.length;a++)(!i||i(n[a]))&&r.removeCue(n[a])}s==="disabled"&&(r.mode=s)}function tg(r,t){if(t<r[0].startTime)return 0;const e=r.length-1;if(t>r[e].endTime)return-1;let i=0,s=e;for(;i<=s;){const n=Math.floor((s+i)/2);if(t<r[n].startTime)s=n-1;else if(t>r[n].startTime&&i<e)i=n+1;else return n}return r[i].startTime-t<t-r[s].startTime?i:s}function eg(r,t,e){const i=[],s=tg(r,t);if(s>-1)for(let n=s,a=r.length;n<a;n++){const o=r[n];if(o.startTime>=t&&o.endTime<=e)i.push(o);else if(o.startTime>e)return i}return i}var ve={audioId3:"org.id3",dateRange:"com.apple.quicktime.HLS",emsg:"https://aomedia.org/emsg/ID3"};const ig=.25;function On(){if(!(typeof self>"u"))return self.WebKitDataCue||self.VTTCue||self.TextTrackCue}const hr=(()=>{const r=On();try{new r(0,Number.POSITIVE_INFINITY,"")}catch{return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();function $n(r,t){return r.getTime()/1e3-t}function sg(r){return Uint8Array.from(r.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer}class rg{constructor(t){this.hls=void 0,this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=t,this._registerListeners()}destroy(){this._unregisterListeners(),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=null}_registerListeners(){const{hls:t}=this;t.on(m.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(m.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(m.MANIFEST_LOADING,this.onManifestLoading,this),t.on(m.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),t.on(m.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(m.LEVEL_UPDATED,this.onLevelUpdated,this)}_unregisterListeners(){const{hls:t}=this;t.off(m.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(m.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(m.MANIFEST_LOADING,this.onManifestLoading,this),t.off(m.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),t.off(m.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(m.LEVEL_UPDATED,this.onLevelUpdated,this)}onMediaAttached(t,e){this.media=e.media}onMediaDetaching(){this.id3Track&&(ki(this.id3Track),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={})}onManifestLoading(){this.dateRangeCuesAppended={}}createTrack(t){const e=this.getID3Track(t.textTracks);return e.mode="hidden",e}getID3Track(t){if(this.media){for(let e=0;e<t.length;e++){const i=t[e];if(i.kind==="metadata"&&i.label==="id3")return rh(i,this.media),i}return this.media.addTextTrack("metadata","id3")}}onFragParsingMetadata(t,e){if(!this.media)return;const{hls:{config:{enableEmsgMetadataCues:i,enableID3MetadataCues:s}}}=this;if(!i&&!s)return;const{samples:n}=e;this.id3Track||(this.id3Track=this.createTrack(this.media));const a=On();for(let o=0;o<n.length;o++){const l=n[o].type;if(l===ve.emsg&&!i||!s)continue;const h=$l(n[o].data);if(h){const c=n[o].pts;let d=c+n[o].duration;d>hr&&(d=hr),d-c<=0&&(d=c+ig);for(let u=0;u<h.length;u++){const f=h[u];if(!Ol(f)){this.updateId3CueEnds(c,l);const p=new a(c,d,"");p.value=f,l&&(p.type=l),this.id3Track.addCue(p)}}}}}updateId3CueEnds(t,e){var i;const s=(i=this.id3Track)==null?void 0:i.cues;if(s)for(let n=s.length;n--;){const a=s[n];a.type===e&&a.startTime<t&&a.endTime===hr&&(a.endTime=t)}}onBufferFlushing(t,{startOffset:e,endOffset:i,type:s}){const{id3Track:n,hls:a}=this;if(!a)return;const{config:{enableEmsgMetadataCues:o,enableID3MetadataCues:l}}=a;if(n&&(o||l)){let h;s==="audio"?h=c=>c.type===ve.audioId3&&l:s==="video"?h=c=>c.type===ve.emsg&&o:h=c=>c.type===ve.audioId3&&l||c.type===ve.emsg&&o,Pn(n,e,i,h)}}onLevelUpdated(t,{details:e}){if(!this.media||!e.hasProgramDateTime||!this.hls.config.enableDateRangeMetadataCues)return;const{dateRangeCuesAppended:i,id3Track:s}=this,{dateRanges:n}=e,a=Object.keys(n);if(s){const c=Object.keys(i).filter(d=>!a.includes(d));for(let d=c.length;d--;){const u=c[d];Object.keys(i[u].cues).forEach(f=>{s.removeCue(i[u].cues[f])}),delete i[u]}}const o=e.fragments[e.fragments.length-1];if(a.length===0||!q(o==null?void 0:o.programDateTime))return;this.id3Track||(this.id3Track=this.createTrack(this.media));const l=o.programDateTime/1e3-o.start,h=On();for(let c=0;c<a.length;c++){const d=a[c],u=n[d],f=i[d],p=(f==null?void 0:f.cues)||{};let g=(f==null?void 0:f.durationKnown)||!1;const v=$n(u.startDate,l);let E=hr;const A=u.endDate;if(A)E=$n(A,l),g=!0;else if(u.endOnNext&&!g){const y=a.reduce((S,R)=>{const C=n[R];return C.class===u.class&&C.id!==R&&C.startDate>u.startDate&&S.push(C),S},[]).sort((S,R)=>S.startDate.getTime()-R.startDate.getTime())[0];y&&(E=$n(y.startDate,l),g=!0)}const L=Object.keys(u.attr);for(let y=0;y<L.length;y++){const S=L[y];if(!dp(S))continue;let R=p[S];if(R)g&&!f.durationKnown&&(R.endTime=E);else{let C=u.attr[S];R=new h(v,E,""),up(S)&&(C=sg(C)),R.value={key:S,data:C},R.type=ve.dateRange,R.id=d,this.id3Track.addCue(R),p[S]=R}}i[d]={cues:p,dateRange:u,durationKnown:g}}}}class ng{constructor(t){this.hls=void 0,this.config=void 0,this.media=null,this.levelDetails=null,this.currentTime=0,this.stallCount=0,this._latency=null,this.timeupdateHandler=()=>this.timeupdate(),this.hls=t,this.config=t.config,this.registerListeners()}get latency(){return this._latency||0}get maxLatency(){const{config:t,levelDetails:e}=this;return t.liveMaxLatencyDuration!==void 0?t.liveMaxLatencyDuration:e?t.liveMaxLatencyDurationCount*e.targetduration:0}get targetLatency(){const{levelDetails:t}=this;if(t===null)return null;const{holdBack:e,partHoldBack:i,targetduration:s}=t,{liveSyncDuration:n,liveSyncDurationCount:a,lowLatencyMode:o}=this.config,l=this.hls.userConfig;let h=o&&i||e;(l.liveSyncDuration||l.liveSyncDurationCount||h===0)&&(h=n!==void 0?n:a*s);const c=s,d=1;return h+Math.min(this.stallCount*d,c)}get liveSyncPosition(){const t=this.estimateLiveEdge(),e=this.targetLatency,i=this.levelDetails;if(t===null||e===null||i===null)return null;const s=i.edge,n=t-e-this.edgeStalled,a=s-i.totalduration,o=s-(this.config.lowLatencyMode&&i.partTarget||i.targetduration);return Math.min(Math.max(a,n),o)}get drift(){const{levelDetails:t}=this;return t===null?1:t.drift}get edgeStalled(){const{levelDetails:t}=this;if(t===null)return 0;const e=(this.config.lowLatencyMode&&t.partTarget||t.targetduration)*3;return Math.max(t.age-e,0)}get forwardBufferLength(){const{media:t,levelDetails:e}=this;if(!t||!e)return 0;const i=t.buffered.length;return(i?t.buffered.end(i-1):e.edge)-this.currentTime}destroy(){this.unregisterListeners(),this.onMediaDetaching(),this.levelDetails=null,this.hls=this.timeupdateHandler=null}registerListeners(){this.hls.on(m.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(m.MEDIA_DETACHING,this.onMediaDetaching,this),this.hls.on(m.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(m.LEVEL_UPDATED,this.onLevelUpdated,this),this.hls.on(m.ERROR,this.onError,this)}unregisterListeners(){this.hls.off(m.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(m.MEDIA_DETACHING,this.onMediaDetaching,this),this.hls.off(m.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(m.LEVEL_UPDATED,this.onLevelUpdated,this),this.hls.off(m.ERROR,this.onError,this)}onMediaAttached(t,e){this.media=e.media,this.media.addEventListener("timeupdate",this.timeupdateHandler)}onMediaDetaching(){this.media&&(this.media.removeEventListener("timeupdate",this.timeupdateHandler),this.media=null)}onManifestLoading(){this.levelDetails=null,this._latency=null,this.stallCount=0}onLevelUpdated(t,{details:e}){this.levelDetails=e,e.advanced&&this.timeupdate(),!e.live&&this.media&&this.media.removeEventListener("timeupdate",this.timeupdateHandler)}onError(t,e){var i;e.details===$.BUFFER_STALLED_ERROR&&(this.stallCount++,(i=this.levelDetails)!=null&&i.live&&_.warn("[playback-rate-controller]: Stall detected, adjusting target latency"))}timeupdate(){const{media:t,levelDetails:e}=this;if(!t||!e)return;this.currentTime=t.currentTime;const i=this.computeLatency();if(i===null)return;this._latency=i;const{lowLatencyMode:s,maxLiveSyncPlaybackRate:n}=this.config;if(!s||n===1)return;const a=this.targetLatency;if(a===null)return;const o=i-a,l=Math.min(this.maxLatency,a+e.targetduration),h=o<l;if(e.live&&h&&o>.05&&this.forwardBufferLength>1){const c=Math.min(2,Math.max(1,n)),d=Math.round(2/(1+Math.exp(-.75*o-this.edgeStalled))*20)/20;t.playbackRate=Math.min(c,Math.max(1,d))}else t.playbackRate!==1&&t.playbackRate!==0&&(t.playbackRate=1)}estimateLiveEdge(){const{levelDetails:t}=this;return t===null?null:t.edge+t.age}computeLatency(){const t=this.estimateLiveEdge();return t===null?null:t-this.currentTime}}const Mn=["NONE","TYPE-0","TYPE-1",null];var bs={No:"",Yes:"YES",v2:"v2"};function ag(r,t){const{canSkipUntil:e,canSkipDateRanges:i,endSN:s}=r,n=t!==void 0?t-s:0;return e&&n<e?i?bs.v2:bs.Yes:bs.No}class ah{constructor(t,e,i){this.msn=void 0,this.part=void 0,this.skip=void 0,this.msn=t,this.part=e,this.skip=i}addDirectives(t){const e=new self.URL(t);return this.msn!==void 0&&e.searchParams.set("_HLS_msn",this.msn.toString()),this.part!==void 0&&e.searchParams.set("_HLS_part",this.part.toString()),this.skip&&e.searchParams.set("_HLS_skip",this.skip),e.href}}class Ts{constructor(t){this._attrs=void 0,this.audioCodec=void 0,this.bitrate=void 0,this.codecSet=void 0,this.height=void 0,this.id=void 0,this.name=void 0,this.videoCodec=void 0,this.width=void 0,this.unknownCodecs=void 0,this.audioGroupIds=void 0,this.details=void 0,this.fragmentError=0,this.loadError=0,this.loaded=void 0,this.realBitrate=0,this.textGroupIds=void 0,this.url=void 0,this._urlId=0,this.url=[t.url],this._attrs=[t.attrs],this.bitrate=t.bitrate,t.details&&(this.details=t.details),this.id=t.id||0,this.name=t.name,this.width=t.width||0,this.height=t.height||0,this.audioCodec=t.audioCodec,this.videoCodec=t.videoCodec,this.unknownCodecs=t.unknownCodecs,this.codecSet=[t.videoCodec,t.audioCodec].filter(e=>e).join(",").replace(/\.[^.,]+/g,"")}get maxBitrate(){return Math.max(this.realBitrate,this.bitrate)}get attrs(){return this._attrs[this._urlId]}get pathwayId(){return this.attrs["PATHWAY-ID"]||"."}get uri(){return this.url[this._urlId]||""}get urlId(){return this._urlId}set urlId(t){const e=t%this.url.length;this._urlId!==e&&(this.fragmentError=0,this.loadError=0,this.details=void 0,this._urlId=e)}get audioGroupId(){var t;return(t=this.audioGroupIds)==null?void 0:t[this.urlId]}get textGroupId(){var t;return(t=this.textGroupIds)==null?void 0:t[this.urlId]}addFallback(t){this.url.push(t.url),this._attrs.push(t.attrs)}}function Fn(r,t){const e=t.startPTS;if(q(e)){let i=0,s;t.sn>r.sn?(i=e-r.start,s=r):(i=r.start-e,s=t),s.duration!==i&&(s.duration=i)}else t.sn>r.sn?r.cc===t.cc&&r.minEndPTS?t.start=r.start+(r.minEndPTS-r.start):t.start=r.start+r.duration:t.start=Math.max(r.start-t.duration,0)}function oh(r,t,e,i,s,n){i-e<=0&&(_.warn("Fragment should have a positive duration",t),i=e+t.duration,n=s+t.duration);let a=e,o=i;const l=t.startPTS,h=t.endPTS;if(q(l)){const g=Math.abs(l-e);q(t.deltaPTS)?t.deltaPTS=Math.max(g,t.deltaPTS):t.deltaPTS=g,a=Math.max(e,l),e=Math.min(e,l),s=Math.min(s,t.startDTS),o=Math.min(i,h),i=Math.max(i,h),n=Math.max(n,t.endDTS)}const c=e-t.start;t.start!==0&&(t.start=e),t.duration=i-t.start,t.startPTS=e,t.maxStartPTS=a,t.startDTS=s,t.endPTS=i,t.minEndPTS=o,t.endDTS=n;const d=t.sn;if(!r||d<r.startSN||d>r.endSN)return 0;let u;const f=d-r.startSN,p=r.fragments;for(p[f]=t,u=f;u>0;u--)Fn(p[u],p[u-1]);for(u=f;u<p.length-1;u++)Fn(p[u],p[u+1]);return r.fragmentHint&&Fn(p[p.length-1],r.fragmentHint),r.PTSKnown=r.alignedSliding=!0,c}function og(r,t){let e=null;const i=r.fragments;for(let l=i.length-1;l>=0;l--){const h=i[l].initSegment;if(h){e=h;break}}r.fragmentHint&&delete r.fragmentHint.endPTS;let s=0,n;if(cg(r,t,(l,h)=>{l.relurl&&(s=l.cc-h.cc),q(l.startPTS)&&q(l.endPTS)&&(h.start=h.startPTS=l.startPTS,h.startDTS=l.startDTS,h.maxStartPTS=l.maxStartPTS,h.endPTS=l.endPTS,h.endDTS=l.endDTS,h.minEndPTS=l.minEndPTS,h.duration=l.endPTS-l.startPTS,h.duration&&(n=h),t.PTSKnown=t.alignedSliding=!0),h.elementaryStreams=l.elementaryStreams,h.loader=l.loader,h.stats=l.stats,h.urlId=l.urlId,l.initSegment&&(h.initSegment=l.initSegment,e=l.initSegment)}),e&&(t.fragmentHint?t.fragments.concat(t.fragmentHint):t.fragments).forEach(l=>{var h;(!l.initSegment||l.initSegment.relurl===((h=e)==null?void 0:h.relurl))&&(l.initSegment=e)}),t.skippedSegments)if(t.deltaUpdateFailed=t.fragments.some(l=>!l),t.deltaUpdateFailed){_.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let l=t.skippedSegments;l--;)t.fragments.shift();t.startSN=t.fragments[0].sn,t.startCC=t.fragments[0].cc}else t.canSkipDateRanges&&(t.dateRanges=lg(r.dateRanges,t.dateRanges,t.recentlyRemovedDateranges));const a=t.fragments;if(s){_.warn("discontinuity sliding from playlist, take drift into account");for(let l=0;l<a.length;l++)a[l].cc+=s}t.skippedSegments&&(t.startCC=t.fragments[0].cc),hg(r.partList,t.partList,(l,h)=>{h.elementaryStreams=l.elementaryStreams,h.stats=l.stats}),n?oh(t,n,n.startPTS,n.endPTS,n.startDTS,n.endDTS):lh(r,t),a.length&&(t.totalduration=t.edge-a[0].start),t.driftStartTime=r.driftStartTime,t.driftStart=r.driftStart;const o=t.advancedDateTime;if(t.advanced&&o){const l=t.edge;t.driftStart||(t.driftStartTime=o,t.driftStart=l),t.driftEndTime=o,t.driftEnd=l}else t.driftEndTime=r.driftEndTime,t.driftEnd=r.driftEnd,t.advancedDateTime=r.advancedDateTime}function lg(r,t,e){const i=Dt({},r);return e&&e.forEach(s=>{delete i[s]}),Object.keys(t).forEach(s=>{const n=new Rl(t[s].attr,i[s]);n.isValid?i[s]=n:_.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${JSON.stringify(t[s].attr)}"`)}),i}function hg(r,t,e){if(r&&t){let i=0;for(let s=0,n=r.length;s<=n;s++){const a=r[s],o=t[s+i];a&&o&&a.index===o.index&&a.fragment.sn===o.fragment.sn?e(a,o):i--}}}function cg(r,t,e){const i=t.skippedSegments,s=Math.max(r.startSN,t.startSN)-t.startSN,n=(r.fragmentHint?1:0)+(i?t.endSN:Math.min(r.endSN,t.endSN))-t.startSN,a=t.startSN-r.startSN,o=t.fragmentHint?t.fragments.concat(t.fragmentHint):t.fragments,l=r.fragmentHint?r.fragments.concat(r.fragmentHint):r.fragments;for(let h=s;h<=n;h++){const c=l[a+h];let d=o[h];i&&!d&&h<i&&(d=t.fragments[h]=c),c&&d&&e(c,d)}}function lh(r,t){const e=t.startSN+t.skippedSegments-r.startSN,i=r.fragments;e<0||e>=i.length||Nn(t,i[e].start)}function Nn(r,t){if(t){const e=r.fragments;for(let i=r.skippedSegments;i<e.length;i++)e[i].start+=t;r.fragmentHint&&(r.fragmentHint.start+=t)}}function dg(r,t=1/0){let e=1e3*r.targetduration;if(r.updated){const i=r.fragments,s=4;if(i.length&&e*s>t){const n=i[i.length-1].duration*1e3;n<e&&(e=n)}}else e/=2;return Math.round(e)}function ug(r,t,e){if(!(r!=null&&r.details))return null;const i=r.details;let s=i.fragments[t-i.startSN];return s||(s=i.fragmentHint,s&&s.sn===t)?s:t<i.startSN&&e&&e.sn===t?e:null}function hh(r,t,e){var i;return r!=null&&r.details?ch((i=r.details)==null?void 0:i.partList,t,e):null}function ch(r,t,e){if(r)for(let i=r.length;i--;){const s=r[i];if(s.index===e&&s.fragment.sn===t)return s}return null}function cr(r){switch(r.details){case $.FRAG_LOAD_TIMEOUT:case $.KEY_LOAD_TIMEOUT:case $.LEVEL_LOAD_TIMEOUT:case $.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function dh(r,t){const e=cr(t);return r.default[`${e?"timeout":"error"}Retry`]}function Un(r,t){const e=r.backoff==="linear"?1:Math.pow(2,t);return Math.min(e*r.retryDelayMs,r.maxRetryDelayMs)}function uh(r){return Qt(Qt({},r),{errorRetry:null,timeoutRetry:null})}function dr(r,t,e,i){return!!r&&t<r.maxNumRetry&&(fg(i)||!!e)}function fg(r){return r===0&&navigator.onLine===!1||!!r&&(r<400||r>499)}const fh={search:function(r,t){let e=0,i=r.length-1,s=null,n=null;for(;e<=i;){s=(e+i)/2|0,n=r[s];const a=t(n);if(a>0)e=s+1;else if(a<0)i=s-1;else return n}return null}};function pg(r,t,e){if(t===null||!Array.isArray(r)||!r.length||!q(t))return null;const i=r[0].programDateTime;if(t<(i||0))return null;const s=r[r.length-1].endProgramDateTime;if(t>=(s||0))return null;e=e||0;for(let n=0;n<r.length;++n){const a=r[n];if(gg(t,e,a))return a}return null}function As(r,t,e=0,i=0){let s=null;if(r?s=t[r.sn-t[0].sn+1]||null:e===0&&t[0].start===0&&(s=t[0]),s&&Bn(e,i,s)===0)return s;const n=fh.search(t,Bn.bind(null,e,i));return n&&(n!==r||!s)?n:s}function Bn(r=0,t=0,e){if(e.start<=r&&e.start+e.duration>r)return 0;const i=Math.min(t,e.duration+(e.deltaPTS?e.deltaPTS:0));return e.start+e.duration-i<=r?1:e.start-i>r&&e.start?-1:0}function gg(r,t,e){const i=Math.min(t,e.duration+(e.deltaPTS?e.deltaPTS:0))*1e3;return(e.endProgramDateTime||0)-i>r}function mg(r,t){return fh.search(r,e=>e.cc<t?1:e.cc>t?-1:0)}const vg=3e5;var Gt={DoNothing:0,SendEndCallback:1,SendAlternateToPenaltyBox:2,RemoveAlternatePermanently:3,InsertDiscontinuity:4,RetryRequest:5},de={None:0,MoveAllAlternatesMatchingHost:1,MoveAllAlternatesMatchingHDCP:2,SwitchToSDR:4};class yg{constructor(t){this.hls=void 0,this.playlistError=0,this.penalizedRenditions={},this.log=void 0,this.warn=void 0,this.error=void 0,this.hls=t,this.log=_.log.bind(_,"[info]:"),this.warn=_.warn.bind(_,"[warning]:"),this.error=_.error.bind(_,"[error]:"),this.registerListeners()}registerListeners(){const t=this.hls;t.on(m.ERROR,this.onError,this),t.on(m.MANIFEST_LOADING,this.onManifestLoading,this),t.on(m.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){const t=this.hls;t&&(t.off(m.ERROR,this.onError,this),t.off(m.ERROR,this.onErrorOut,this),t.off(m.MANIFEST_LOADING,this.onManifestLoading,this),t.off(m.LEVEL_UPDATED,this.onLevelUpdated,this))}destroy(){this.unregisterListeners(),this.hls=null,this.penalizedRenditions={}}startLoad(t){this.playlistError=0}stopLoad(){}getVariantLevelIndex(t){return(t==null?void 0:t.type)===Z.MAIN?t.level:this.hls.loadLevel}onManifestLoading(){this.playlistError=0,this.penalizedRenditions={}}onLevelUpdated(){this.playlistError=0}onError(t,e){var i,s;if(e.fatal)return;const n=this.hls,a=e.context;switch(e.details){case $.FRAG_LOAD_ERROR:case $.FRAG_LOAD_TIMEOUT:case $.KEY_LOAD_ERROR:case $.KEY_LOAD_TIMEOUT:e.errorAction=this.getFragRetryOrSwitchAction(e);return;case $.FRAG_PARSING_ERROR:if((i=e.frag)!=null&&i.gap){e.errorAction={action:Gt.DoNothing,flags:de.None};return}case $.FRAG_GAP:case $.FRAG_DECRYPT_ERROR:{e.errorAction=this.getFragRetryOrSwitchAction(e),e.errorAction.action=Gt.SendAlternateToPenaltyBox;return}case $.LEVEL_EMPTY_ERROR:case $.LEVEL_PARSING_ERROR:{var o,l;const h=e.parent===Z.MAIN?e.level:n.loadLevel;e.details===$.LEVEL_EMPTY_ERROR&&(o=e.context)!=null&&(l=o.levelDetails)!=null&&l.live?e.errorAction=this.getPlaylistRetryOrSwitchAction(e,h):(e.levelRetry=!1,e.errorAction=this.getLevelSwitchAction(e,h))}return;case $.LEVEL_LOAD_ERROR:case $.LEVEL_LOAD_TIMEOUT:typeof(a==null?void 0:a.level)=="number"&&(e.errorAction=this.getPlaylistRetryOrSwitchAction(e,a.level));return;case $.AUDIO_TRACK_LOAD_ERROR:case $.AUDIO_TRACK_LOAD_TIMEOUT:case $.SUBTITLE_LOAD_ERROR:case $.SUBTITLE_TRACK_LOAD_TIMEOUT:if(a){const h=n.levels[n.loadLevel];if(h&&(a.type===ct.AUDIO_TRACK&&a.groupId===h.audioGroupId||a.type===ct.SUBTITLE_TRACK&&a.groupId===h.textGroupId)){e.errorAction=this.getPlaylistRetryOrSwitchAction(e,n.loadLevel),e.errorAction.action=Gt.SendAlternateToPenaltyBox,e.errorAction.flags=de.MoveAllAlternatesMatchingHost;return}}return;case $.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:{const h=n.levels[n.loadLevel],c=h==null?void 0:h.attrs["HDCP-LEVEL"];c&&(e.errorAction={action:Gt.SendAlternateToPenaltyBox,flags:de.MoveAllAlternatesMatchingHDCP,hdcpLevel:c})}return;case $.BUFFER_ADD_CODEC_ERROR:case $.REMUX_ALLOC_ERROR:e.errorAction=this.getLevelSwitchAction(e,(s=e.level)!=null?s:n.loadLevel);return;case $.INTERNAL_EXCEPTION:case $.BUFFER_APPENDING_ERROR:case $.BUFFER_APPEND_ERROR:case $.BUFFER_FULL_ERROR:case $.LEVEL_SWITCH_ERROR:case $.BUFFER_STALLED_ERROR:case $.BUFFER_SEEK_OVER_HOLE:case $.BUFFER_NUDGE_ON_STALL:e.errorAction={action:Gt.DoNothing,flags:de.None};return}if(e.type===Q.KEY_SYSTEM_ERROR){const h=this.getVariantLevelIndex(e.frag);e.levelRetry=!1,e.errorAction=this.getLevelSwitchAction(e,h);return}}getPlaylistRetryOrSwitchAction(t,e){var i;const s=this.hls,n=dh(s.config.playlistLoadPolicy,t),a=this.playlistError++,o=(i=t.response)==null?void 0:i.code;if(dr(n,a,cr(t),o))return{action:Gt.RetryRequest,flags:de.None,retryConfig:n,retryCount:a};const l=this.getLevelSwitchAction(t,e);return n&&(l.retryConfig=n,l.retryCount=a),l}getFragRetryOrSwitchAction(t){const e=this.hls,i=this.getVariantLevelIndex(t.frag),s=e.levels[i],{fragLoadPolicy:n,keyLoadPolicy:a}=e.config,o=dh(t.details.startsWith("key")?a:n,t),l=e.levels.reduce((d,u)=>d+u.fragmentError,0);if(s){var h;t.details!==$.FRAG_GAP&&s.fragmentError++;const d=(h=t.response)==null?void 0:h.code;if(dr(o,l,cr(t),d))return{action:Gt.RetryRequest,flags:de.None,retryConfig:o,retryCount:l}}const c=this.getLevelSwitchAction(t,i);return o&&(c.retryConfig=o,c.retryCount=l),c}getLevelSwitchAction(t,e){const i=this.hls;e==null&&(e=i.loadLevel);const s=this.hls.levels[e];if(s&&(s.loadError++,i.autoLevelEnabled)){var n,a;let o=-1;const{levels:l,loadLevel:h,minAutoLevel:c,maxAutoLevel:d}=i,u=(n=t.frag)==null?void 0:n.type,{type:f,groupId:p}=(a=t.context)!=null?a:{};for(let g=l.length;g--;){const v=(g+h)%l.length;if(v!==h&&v>=c&&v<=d&&l[v].loadError===0){const E=l[v];if(t.details===$.FRAG_GAP&&t.frag){const A=l[v].details;if(A){const L=As(t.frag,A.fragments,t.frag.start);if(L!=null&&L.gap)continue}}else if(f===ct.AUDIO_TRACK&&p===E.audioGroupId||f===ct.SUBTITLE_TRACK&&p===E.textGroupId||u===Z.AUDIO&&s.audioGroupId===E.audioGroupId||u===Z.SUBTITLE&&s.textGroupId===E.textGroupId)continue;o=v;break}}if(o>-1&&i.loadLevel!==o)return t.levelRetry=!0,this.playlistError=0,{action:Gt.SendAlternateToPenaltyBox,flags:de.None,nextAutoLevel:o}}return{action:Gt.SendAlternateToPenaltyBox,flags:de.MoveAllAlternatesMatchingHost}}onErrorOut(t,e){var i;switch((i=e.errorAction)==null?void 0:i.action){case Gt.DoNothing:break;case Gt.SendAlternateToPenaltyBox:this.sendAlternateToPenaltyBox(e),!e.errorAction.resolved&&e.details!==$.FRAG_GAP&&(e.fatal=!0);break}if(e.fatal){this.hls.stopLoad();return}}sendAlternateToPenaltyBox(t){const e=this.hls,i=t.errorAction;if(!i)return;const{flags:s,hdcpLevel:n,nextAutoLevel:a}=i;switch(s){case de.None:this.switchLevel(t,a);break;case de.MoveAllAlternatesMatchingHost:i.resolved||(i.resolved=this.redundantFailover(t));break;case de.MoveAllAlternatesMatchingHDCP:n&&(e.maxHdcpLevel=Mn[Mn.indexOf(n)-1],i.resolved=!0),this.warn(`Restricting playback to HDCP-LEVEL of "${e.maxHdcpLevel}" or lower`);break}i.resolved||this.switchLevel(t,a)}switchLevel(t,e){e!==void 0&&t.errorAction&&(this.warn(`switching to level ${e} after ${t.details}`),this.hls.nextAutoLevel=e,t.errorAction.resolved=!0,this.hls.nextLoadLevel=this.hls.nextAutoLevel)}redundantFailover(t){const{hls:e,penalizedRenditions:i}=this,s=t.parent===Z.MAIN?t.level:e.loadLevel,n=e.levels[s],a=n.url.length,o=t.frag?t.frag.urlId:n.urlId;n.urlId===o&&(!t.frag||n.details)&&this.penalizeRendition(n,t);for(let l=1;l<a;l++){const h=(o+l)%a,c=i[h];if(!c||Eg(c,t,i[o]))return this.warn(`Switching to Redundant Stream ${h+1}/${a}: "${n.url[h]}" after ${t.details}`),this.playlistError=0,e.levels.forEach(d=>{d.urlId=h}),e.nextLoadLevel=s,!0}return!1}penalizeRendition(t,e){const{penalizedRenditions:i}=this,s=i[t.urlId]||{lastErrorPerfMs:0,errors:[],details:void 0};s.lastErrorPerfMs=performance.now(),s.errors.push(e),s.details=t.details,i[t.urlId]=s}}function Eg(r,t,e){if(performance.now()-r.lastErrorPerfMs>vg)return!0;const i=r.details;if(t.details===$.FRAG_GAP&&i&&t.frag){const s=t.frag.start,n=As(null,i.fragments,s);if(n&&!n.gap)return!0}if(e&&r.errors.length<e.errors.length){const s=r.errors[r.errors.length-1];if(i&&s.frag&&t.frag&&Math.abs(s.frag.start-t.frag.start)>i.targetduration*3)return!0}return!1}class Hn{constructor(t,e){this.hls=void 0,this.timer=-1,this.requestScheduled=-1,this.canLoad=!1,this.log=void 0,this.warn=void 0,this.log=_.log.bind(_,`${e}:`),this.warn=_.warn.bind(_,`${e}:`),this.hls=t}destroy(){this.clearTimer(),this.hls=this.log=this.warn=null}clearTimer(){clearTimeout(this.timer),this.timer=-1}startLoad(){this.canLoad=!0,this.requestScheduled=-1,this.loadPlaylist()}stopLoad(){this.canLoad=!1,this.clearTimer()}switchParams(t,e){const i=e==null?void 0:e.renditionReports;if(i){let s=-1;for(let n=0;n<i.length;n++){const a=i[n];let o;try{o=new self.URL(a.URI,e.url).href}catch(l){_.warn(`Could not construct new URL for Rendition Report: ${l}`),o=a.URI||""}if(o===t){s=n;break}else o===t.substring(0,o.length)&&(s=n)}if(s!==-1){const n=i[s],a=parseInt(n["LAST-MSN"])||(e==null?void 0:e.lastPartSn);let o=parseInt(n["LAST-PART"])||(e==null?void 0:e.lastPartIndex);if(this.hls.config.lowLatencyMode){const l=Math.min(e.age-e.partTarget,e.targetduration);o>=0&&l>e.partTarget&&(o+=1)}return new ah(a,o>=0?o:void 0,bs.No)}}}loadPlaylist(t){this.requestScheduled===-1&&(this.requestScheduled=self.performance.now())}shouldLoadPlaylist(t){return this.canLoad&&!!t&&!!t.url&&(!t.details||t.details.live)}shouldReloadPlaylist(t){return this.timer===-1&&this.requestScheduled===-1&&this.shouldLoadPlaylist(t)}playlistLoaded(t,e,i){const{details:s,stats:n}=e,a=self.performance.now(),o=n.loading.first?Math.max(0,a-n.loading.first):0;if(s.advancedDateTime=Date.now()-o,s.live||i!=null&&i.live){if(s.reloaded(i),i&&this.log(`live playlist ${t} ${s.advanced?"REFRESHED "+s.lastPartSn+"-"+s.lastPartIndex:s.updated?"UPDATED":"MISSED"}`),i&&s.fragments.length>0&&og(i,s),!this.canLoad||!s.live)return;let l,h,c;if(s.canBlockReload&&s.endSN&&s.advanced){const v=this.hls.config.lowLatencyMode,E=s.lastPartSn,A=s.endSN,L=s.lastPartIndex,y=L!==-1,S=E===A,R=v?0:L;y?(h=S?A+1:E,c=S?R:L+1):h=A+1;const C=s.age,M=C+s.ageHeader;let D=Math.min(M-s.partTarget,s.targetduration*1.5);if(D>0){if(i&&D>i.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${i.tuneInGoal} to: ${D} with playlist age: ${s.age}`),D=0;else{const I=Math.floor(D/s.targetduration);if(h+=I,c!==void 0){const G=Math.round(D%s.targetduration/s.partTarget);c+=G}this.log(`CDN Tune-in age: ${s.ageHeader}s last advanced ${C.toFixed(2)}s goal: ${D} skip sn ${I} to part ${c}`)}s.tuneInGoal=D}if(l=this.getDeliveryDirectives(s,e.deliveryDirectives,h,c),v||!S){this.loadPlaylist(l);return}}else(s.canBlockReload||s.canSkipUntil)&&(l=this.getDeliveryDirectives(s,e.deliveryDirectives,h,c));const d=this.hls.mainForwardBufferInfo,u=d?d.end-d.len:0,f=(s.edge-u)*1e3,p=dg(s,f);s.updated&&a>this.requestScheduled+p&&(this.requestScheduled=n.loading.start),h!==void 0&&s.canBlockReload?this.requestScheduled=n.loading.first+p-(s.partTarget*1e3||1e3):this.requestScheduled===-1||this.requestScheduled+p<a?this.requestScheduled=a:this.requestScheduled-a<=0&&(this.requestScheduled+=p);let g=this.requestScheduled-a;g=Math.max(0,g),this.log(`reload live playlist ${t} in ${Math.round(g)} ms`),this.timer=self.setTimeout(()=>this.loadPlaylist(l),g)}else this.clearTimer()}getDeliveryDirectives(t,e,i,s){let n=ag(t,i);return e!=null&&e.skip&&t.deltaUpdateFailed&&(i=e.msn,s=e.part,n=bs.No),new ah(i,s,n)}checkRetry(t){const e=t.details,i=cr(t),s=t.errorAction,{action:n,retryCount:a=0,retryConfig:o}=s||{},l=!!s&&!!o&&(n===Gt.RetryRequest||!s.resolved&&n===Gt.SendAlternateToPenaltyBox);if(l){var h;if(this.requestScheduled=-1,a>=o.maxNumRetry)return!1;if(i&&(h=t.context)!=null&&h.deliveryDirectives)this.warn(`Retrying playlist loading ${a+1}/${o.maxNumRetry} after "${e}" without delivery-directives`),this.loadPlaylist();else{const c=Un(o,a);this.timer=self.setTimeout(()=>this.loadPlaylist(),c),this.warn(`Retrying playlist loading ${a+1}/${o.maxNumRetry} after "${e}" in ${c}ms`)}t.levelRetry=!0,s.resolved=!0}return l}}let Gn;class bg extends Hn{constructor(t,e){super(t,"[level-controller]"),this._levels=[],this._firstLevel=-1,this._startLevel=void 0,this.currentLevel=null,this.currentLevelIndex=-1,this.manualLevelIndex=-1,this.steering=void 0,this.onParsedComplete=void 0,this.steering=e,this._registerListeners()}_registerListeners(){const{hls:t}=this;t.on(m.MANIFEST_LOADING,this.onManifestLoading,this),t.on(m.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(m.LEVEL_LOADED,this.onLevelLoaded,this),t.on(m.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(m.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),t.on(m.FRAG_LOADED,this.onFragLoaded,this),t.on(m.ERROR,this.onError,this)}_unregisterListeners(){const{hls:t}=this;t.off(m.MANIFEST_LOADING,this.onManifestLoading,this),t.off(m.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(m.LEVEL_LOADED,this.onLevelLoaded,this),t.off(m.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(m.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),t.off(m.FRAG_LOADED,this.onFragLoaded,this),t.off(m.ERROR,this.onError,this)}destroy(){this._unregisterListeners(),this.steering=null,this.resetLevels(),super.destroy()}startLoad(){this._levels.forEach(t=>{t.loadError=0,t.fragmentError=0}),super.startLoad()}resetLevels(){this._startLevel=void 0,this.manualLevelIndex=-1,this.currentLevelIndex=-1,this.currentLevel=null,this._levels=[]}onManifestLoading(t,e){this.resetLevels()}onManifestLoaded(t,e){const i=[],s={};let n;e.levels.forEach(a=>{var o;const l=a.attrs;((o=a.audioCodec)==null?void 0:o.indexOf("mp4a.40.34"))!==-1&&(Gn||(Gn=/chrome|firefox/i.test(navigator.userAgent)),Gn&&(a.audioCodec=void 0));const{AUDIO:h,CODECS:c,"FRAME-RATE":d,"PATHWAY-ID":u,RESOLUTION:f,SUBTITLES:p}=l,g=`${`${u||"."}-`}${a.bitrate}-${f}-${d}-${c}`;n=s[g],n?n.addFallback(a):(n=new Ts(a),s[g]=n,i.push(n)),ur(n,"audio",h),ur(n,"text",p)}),this.filterAndSortMediaOptions(i,e)}filterAndSortMediaOptions(t,e){let i=[],s=[],n=!1,a=!1,o=!1,l=t.filter(({audioCodec:f,videoCodec:p,width:g,height:v,unknownCodecs:E})=>(n||(n=!!(g&&v)),a||(a=!!p),o||(o=!!f),!(E!=null&&E.length)&&(!f||Dn(f,"audio"))&&(!p||Dn(p,"video"))));if((n||a)&&o&&(l=l.filter(({videoCodec:f,width:p,height:g})=>!!f||!!(p&&g))),l.length===0){Promise.resolve().then(()=>{if(this.hls){const f=new Error("no level with compatible codecs found in manifest");this.hls.trigger(m.ERROR,{type:Q.MEDIA_ERROR,details:$.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:e.url,error:f,reason:f.message})}});return}e.audioTracks&&(i=e.audioTracks.filter(f=>!f.audioCodec||Dn(f.audioCodec,"audio")),ph(i)),e.subtitles&&(s=e.subtitles,ph(s));const h=l.slice(0);l.sort((f,p)=>f.attrs["HDCP-LEVEL"]!==p.attrs["HDCP-LEVEL"]?(f.attrs["HDCP-LEVEL"]||"")>(p.attrs["HDCP-LEVEL"]||"")?1:-1:f.bitrate!==p.bitrate?f.bitrate-p.bitrate:f.attrs["FRAME-RATE"]!==p.attrs["FRAME-RATE"]?f.attrs.decimalFloatingPoint("FRAME-RATE")-p.attrs.decimalFloatingPoint("FRAME-RATE"):f.attrs.SCORE!==p.attrs.SCORE?f.attrs.decimalFloatingPoint("SCORE")-p.attrs.decimalFloatingPoint("SCORE"):n&&f.height!==p.height?f.height-p.height:0);let c=h[0];if(this.steering&&(l=this.steering.filterParsedLevels(l),l.length!==h.length)){for(let f=0;f<h.length;f++)if(h[f].pathwayId===l[0].pathwayId){c=h[f];break}}this._levels=l;for(let f=0;f<l.length;f++)if(l[f]===c){this._firstLevel=f,this.log(`manifest loaded, ${l.length} level(s) found, first bitrate: ${c.bitrate}`);break}const d=o&&!a,u={levels:l,audioTracks:i,subtitleTracks:s,sessionData:e.sessionData,sessionKeys:e.sessionKeys,firstLevel:this._firstLevel,stats:e.stats,audio:o,video:a,altAudio:!d&&i.some(f=>!!f.url)};this.hls.trigger(m.MANIFEST_PARSED,u),(this.hls.config.autoStartLoad||this.hls.forceStartLoad)&&this.hls.startLoad(this.hls.config.startPosition)}get levels(){return this._levels.length===0?null:this._levels}get level(){return this.currentLevelIndex}set level(t){const e=this._levels;if(e.length===0)return;if(t<0||t>=e.length){const c=new Error("invalid level idx"),d=t<0;if(this.hls.trigger(m.ERROR,{type:Q.OTHER_ERROR,details:$.LEVEL_SWITCH_ERROR,level:t,fatal:d,error:c,reason:c.message}),d)return;t=Math.min(t,e.length-1)}const i=this.currentLevelIndex,s=this.currentLevel,n=s?s.attrs["PATHWAY-ID"]:void 0,a=e[t],o=a.attrs["PATHWAY-ID"];if(this.currentLevelIndex=t,this.currentLevel=a,i===t&&a.details&&s&&n===o)return;this.log(`Switching to level ${t}${o?" with Pathway "+o:""} from level ${i}${n?" with Pathway "+n:""}`);const l=Dt({},a,{level:t,maxBitrate:a.maxBitrate,attrs:a.attrs,uri:a.uri,urlId:a.urlId});delete l._attrs,delete l._urlId,this.hls.trigger(m.LEVEL_SWITCHING,l);const h=a.details;if(!h||h.live){const c=this.switchParams(a.uri,s==null?void 0:s.details);this.loadPlaylist(c)}}get manualLevel(){return this.manualLevelIndex}set manualLevel(t){this.manualLevelIndex=t,this._startLevel===void 0&&(this._startLevel=t),t!==-1&&(this.level=t)}get firstLevel(){return this._firstLevel}set firstLevel(t){this._firstLevel=t}get startLevel(){if(this._startLevel===void 0){const t=this.hls.config.startLevel;return t!==void 0?t:this._firstLevel}else return this._startLevel}set startLevel(t){this._startLevel=t}onError(t,e){e.fatal||!e.context||e.context.type===ct.LEVEL&&e.context.level===this.level&&this.checkRetry(e)}onFragLoaded(t,{frag:e}){if(e!==void 0&&e.type===Z.MAIN){const i=this._levels[e.level];i!==void 0&&(i.loadError=0)}}onLevelLoaded(t,e){var i;const{level:s,details:n}=e,a=this._levels[s];if(!a){var o;this.warn(`Invalid level index ${s}`),(o=e.deliveryDirectives)!=null&&o.skip&&(n.deltaUpdateFailed=!0);return}s===this.currentLevelIndex?(a.fragmentError===0&&(a.loadError=0),this.playlistLoaded(s,e,a.details)):(i=e.deliveryDirectives)!=null&&i.skip&&(n.deltaUpdateFailed=!0)}onAudioTrackSwitched(t,e){const i=this.currentLevel;if(!i)return;const s=this.hls.audioTracks[e.id].groupId;if(i.audioGroupIds&&i.audioGroupId!==s){let n=-1;for(let a=0;a<i.audioGroupIds.length;a++)if(i.audioGroupIds[a]===s){n=a;break}n!==-1&&n!==i.urlId&&(i.urlId=n,this.canLoad&&this.startLoad())}}loadPlaylist(t){super.loadPlaylist();const e=this.currentLevelIndex,i=this.currentLevel;if(i&&this.shouldLoadPlaylist(i)){const s=i.urlId;let n=i.uri;if(t)try{n=t.addDirectives(n)}catch(o){this.warn(`Could not construct new URL with HLS Delivery Directives: ${o}`)}const a=i.attrs["PATHWAY-ID"];this.log(`Loading level index ${e}${(t==null?void 0:t.msn)!==void 0?" at sn "+t.msn+" part "+t.part:""} with${a?" Pathway "+a:""} URI ${s+1}/${i.url.length} ${n}`),this.clearTimer(),this.hls.trigger(m.LEVEL_LOADING,{url:n,level:e,id:s,deliveryDirectives:t||null})}}get nextLoadLevel(){return this.manualLevelIndex!==-1?this.manualLevelIndex:this.hls.nextAutoLevel}set nextLoadLevel(t){this.level=t,this.manualLevelIndex===-1&&(this.hls.nextAutoLevel=t)}removeLevel(t,e){const i=(n,a)=>a!==e,s=this._levels.filter((n,a)=>a!==t?!0:n.url.length>1&&e!==void 0?(n.url=n.url.filter(i),n.audioGroupIds&&(n.audioGroupIds=n.audioGroupIds.filter(i)),n.textGroupIds&&(n.textGroupIds=n.textGroupIds.filter(i)),n.urlId=0,!0):(this.steering&&this.steering.removeLevel(n),!1));this.hls.trigger(m.LEVELS_UPDATED,{levels:s})}onLevelsUpdated(t,{levels:e}){e.forEach((i,s)=>{const{details:n}=i;n!=null&&n.fragments&&n.fragments.forEach(a=>{a.level=s})}),this._levels=e}}function ur(r,t,e){e&&(t==="audio"?(r.audioGroupIds||(r.audioGroupIds=[]),r.audioGroupIds[r.url.length-1]=e):t==="text"&&(r.textGroupIds||(r.textGroupIds=[]),r.textGroupIds[r.url.length-1]=e))}function ph(r){const t={};r.forEach(e=>{const i=e.groupId||"";e.id=t[i]=t[i]||0,t[i]++})}var $t={NOT_LOADED:"NOT_LOADED",APPENDING:"APPENDING",PARTIAL:"PARTIAL",OK:"OK"};class Tg{constructor(t){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=!1,this.hls=t,this._registerListeners()}_registerListeners(){const{hls:t}=this;t.on(m.BUFFER_APPENDED,this.onBufferAppended,this),t.on(m.FRAG_BUFFERED,this.onFragBuffered,this),t.on(m.FRAG_LOADED,this.onFragLoaded,this)}_unregisterListeners(){const{hls:t}=this;t.off(m.BUFFER_APPENDED,this.onBufferAppended,this),t.off(m.FRAG_BUFFERED,this.onFragBuffered,this),t.off(m.FRAG_LOADED,this.onFragLoaded,this)}destroy(){this._unregisterListeners(),this.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null}getAppendedFrag(t,e){const i=this.activePartLists[e];if(i)for(let s=i.length;s--;){const n=i[s];if(!n)break;const a=n.end;if(n.start<=t&&a!==null&&t<=a)return n}return this.getBufferedFrag(t,e)}getBufferedFrag(t,e){const{fragments:i}=this,s=Object.keys(i);for(let n=s.length;n--;){const a=i[s[n]];if((a==null?void 0:a.body.type)===e&&a.buffered){const o=a.body;if(o.start<=t&&t<=o.end)return o}}return null}detectEvictedFragments(t,e,i,s){this.timeRanges&&(this.timeRanges[t]=e);const n=(s==null?void 0:s.fragment.sn)||-1;Object.keys(this.fragments).forEach(a=>{const o=this.fragments[a];if(!o||n>=o.body.sn)return;if(!o.buffered&&!o.loaded){o.body.type===i&&this.removeFragment(o.body);return}const l=o.range[t];l&&l.time.some(h=>{const c=!this.isTimeBuffered(h.startPTS,h.endPTS,e);return c&&this.removeFragment(o.body),c})})}detectPartialFragments(t){const e=this.timeRanges,{frag:i,part:s}=t;if(!e||i.sn==="initSegment")return;const n=Ii(i),a=this.fragments[n];if(!a||a.buffered&&i.gap)return;const o=!i.relurl;Object.keys(e).forEach(l=>{const h=i.elementaryStreams[l];if(!h)return;const c=e[l],d=o||h.partial===!0;a.range[l]=this.getBufferedTimes(i,s,d,c)}),a.loaded=null,Object.keys(a.range).length?(a.buffered=!0,(a.body.endList=i.endList||a.body.endList)&&(this.endListFragments[a.body.type]=a),fr(a)||this.removeParts(i.sn-1,i.type)):this.removeFragment(a.body)}removeParts(t,e){const i=this.activePartLists[e];i&&(this.activePartLists[e]=i.filter(s=>s.fragment.sn>=t))}fragBuffered(t,e){const i=Ii(t);let s=this.fragments[i];!s&&e&&(s=this.fragments[i]={body:t,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},t.gap&&(this.hasGaps=!0)),s&&(s.loaded=null,s.buffered=!0)}getBufferedTimes(t,e,i,s){const n={time:[],partial:i},a=t.start,o=t.end,l=t.minEndPTS||o,h=t.maxStartPTS||a;for(let c=0;c<s.length;c++){const d=s.start(c)-this.bufferPadding,u=s.end(c)+this.bufferPadding;if(h>=d&&l<=u){n.time.push({startPTS:Math.max(a,s.start(c)),endPTS:Math.min(o,s.end(c))});break}else if(a<u&&o>d)n.partial=!0,n.time.push({startPTS:Math.max(a,s.start(c)),endPTS:Math.min(o,s.end(c))});else if(o<=d)break}return n}getPartialFragment(t){let e=null,i,s,n,a=0;const{bufferPadding:o,fragments:l}=this;return Object.keys(l).forEach(h=>{const c=l[h];c&&fr(c)&&(s=c.body.start-o,n=c.body.end+o,t>=s&&t<=n&&(i=Math.min(t-s,n-t),a<=i&&(e=c.body,a=i)))}),e}isEndListAppended(t){const e=this.endListFragments[t];return e!==void 0&&(e.buffered||fr(e))}getState(t){const e=Ii(t),i=this.fragments[e];return i?i.buffered?fr(i)?$t.PARTIAL:$t.OK:$t.APPENDING:$t.NOT_LOADED}isTimeBuffered(t,e,i){let s,n;for(let a=0;a<i.length;a++){if(s=i.start(a)-this.bufferPadding,n=i.end(a)+this.bufferPadding,t>=s&&e<=n)return!0;if(e<=s)return!1}return!1}onFragLoaded(t,e){const{frag:i,part:s}=e;if(i.sn==="initSegment"||i.bitrateTest)return;const n=s?null:e,a=Ii(i);this.fragments[a]={body:i,appendedPTS:null,loaded:n,buffered:!1,range:Object.create(null)}}onBufferAppended(t,e){const{frag:i,part:s,timeRanges:n}=e;if(i.sn==="initSegment")return;const a=i.type;if(s){let o=this.activePartLists[a];o||(this.activePartLists[a]=o=[]),o.push(s)}this.timeRanges=n,Object.keys(n).forEach(o=>{const l=n[o];this.detectEvictedFragments(o,l,a,s)})}onFragBuffered(t,e){this.detectPartialFragments(e)}hasFragment(t){const e=Ii(t);return!!this.fragments[e]}hasParts(t){var e;return!!((e=this.activePartLists[t])!=null&&e.length)}removeFragmentsInRange(t,e,i,s,n){s&&!this.hasGaps||Object.keys(this.fragments).forEach(a=>{const o=this.fragments[a];if(!o)return;const l=o.body;l.type!==i||s&&!l.gap||l.start<e&&l.end>t&&(o.buffered||n)&&this.removeFragment(l)})}removeFragment(t){const e=Ii(t);t.stats.loaded=0,t.clearElementaryStreamInfo();const i=this.activePartLists[t.type];if(i){const s=t.sn;this.activePartLists[t.type]=i.filter(n=>n.fragment.sn!==s)}delete this.fragments[e],t.endList&&delete this.endListFragments[t.type]}removeAllFragments(){this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=!1}}function fr(r){var t,e,i;return r.buffered&&(r.body.gap||((t=r.range.video)==null?void 0:t.partial)||((e=r.range.audio)==null?void 0:e.partial)||((i=r.range.audiovideo)==null?void 0:i.partial))}function Ii(r){return`${r.type}_${r.level}_${r.urlId}_${r.sn}`}const gh=Math.pow(2,17);class Ag{constructor(t){this.config=void 0,this.loader=null,this.partLoadTimeout=-1,this.config=t}destroy(){this.loader&&(this.loader.destroy(),this.loader=null)}abort(){this.loader&&this.loader.abort()}load(t,e){const i=t.url;if(!i)return Promise.reject(new $e({type:Q.NETWORK_ERROR,details:$.FRAG_LOAD_ERROR,fatal:!1,frag:t,error:new Error(`Fragment does not have a ${i?"part list":"url"}`),networkDetails:null}));this.abort();const s=this.config,n=s.fLoader,a=s.loader;return new Promise((o,l)=>{if(this.loader&&this.loader.destroy(),t.gap)if(t.tagList.some(f=>f[0]==="GAP")){l(vh(t));return}else t.gap=!1;const h=this.loader=t.loader=n?new n(s):new a(s),c=mh(t),d=uh(s.fragLoadPolicy.default),u={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:t.sn==="initSegment"?1/0:gh};t.stats=h.stats,h.load(c,u,{onSuccess:(f,p,g,v)=>{this.resetLoader(t,h);let E=f.data;g.resetIV&&t.decryptdata&&(t.decryptdata.iv=new Uint8Array(E.slice(0,16)),E=E.slice(16)),o({frag:t,part:null,payload:E,networkDetails:v})},onError:(f,p,g,v)=>{this.resetLoader(t,h),l(new $e({type:Q.NETWORK_ERROR,details:$.FRAG_LOAD_ERROR,fatal:!1,frag:t,response:Qt({url:i,data:void 0},f),error:new Error(`HTTP Error ${f.code} ${f.text}`),networkDetails:g,stats:v}))},onAbort:(f,p,g)=>{this.resetLoader(t,h),l(new $e({type:Q.NETWORK_ERROR,details:$.INTERNAL_ABORTED,fatal:!1,frag:t,error:new Error("Aborted"),networkDetails:g,stats:f}))},onTimeout:(f,p,g)=>{this.resetLoader(t,h),l(new $e({type:Q.NETWORK_ERROR,details:$.FRAG_LOAD_TIMEOUT,fatal:!1,frag:t,error:new Error(`Timeout after ${u.timeout}ms`),networkDetails:g,stats:f}))},onProgress:(f,p,g,v)=>{e&&e({frag:t,part:null,payload:g,networkDetails:v})}})})}loadPart(t,e,i){this.abort();const s=this.config,n=s.fLoader,a=s.loader;return new Promise((o,l)=>{if(this.loader&&this.loader.destroy(),t.gap||e.gap){l(vh(t,e));return}const h=this.loader=t.loader=n?new n(s):new a(s),c=mh(t,e),d=uh(s.fragLoadPolicy.default),u={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:gh};e.stats=h.stats,h.load(c,u,{onSuccess:(f,p,g,v)=>{this.resetLoader(t,h),this.updateStatsFromPart(t,e);const E={frag:t,part:e,payload:f.data,networkDetails:v};i(E),o(E)},onError:(f,p,g,v)=>{this.resetLoader(t,h),l(new $e({type:Q.NETWORK_ERROR,details:$.FRAG_LOAD_ERROR,fatal:!1,frag:t,part:e,response:Qt({url:c.url,data:void 0},f),error:new Error(`HTTP Error ${f.code} ${f.text}`),networkDetails:g,stats:v}))},onAbort:(f,p,g)=>{t.stats.aborted=e.stats.aborted,this.resetLoader(t,h),l(new $e({type:Q.NETWORK_ERROR,details:$.INTERNAL_ABORTED,fatal:!1,frag:t,part:e,error:new Error("Aborted"),networkDetails:g,stats:f}))},onTimeout:(f,p,g)=>{this.resetLoader(t,h),l(new $e({type:Q.NETWORK_ERROR,details:$.FRAG_LOAD_TIMEOUT,fatal:!1,frag:t,part:e,error:new Error(`Timeout after ${u.timeout}ms`),networkDetails:g,stats:f}))}})})}updateStatsFromPart(t,e){const i=t.stats,s=e.stats,n=s.total;if(i.loaded+=s.loaded,n){const l=Math.round(t.duration/e.duration),h=Math.min(Math.round(i.loaded/n),l),c=(l-h)*Math.round(i.loaded/h);i.total=i.loaded+c}else i.total=Math.max(i.loaded,i.total);const a=i.loading,o=s.loading;a.start?a.first+=o.first-o.start:(a.start=o.start,a.first=o.first),a.end=o.end}resetLoader(t,e){t.loader=null,this.loader===e&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),e.destroy()}}function mh(r,t=null){const e=t||r,i={frag:r,part:t,responseType:"arraybuffer",url:e.url,headers:{},rangeStart:0,rangeEnd:0},s=e.byteRangeStartOffset,n=e.byteRangeEndOffset;if(q(s)&&q(n)){var a;let o=s,l=n;if(r.sn==="initSegment"&&((a=r.decryptdata)==null?void 0:a.method)==="AES-128"){const h=n-s;h%16&&(l=n+(16-h%16)),s!==0&&(i.resetIV=!0,o=s-16)}i.rangeStart=o,i.rangeEnd=l}return i}function vh(r,t){const e=new Error(`GAP ${r.gap?"tag":"attribute"} found`),i={type:Q.MEDIA_ERROR,details:$.FRAG_GAP,fatal:!1,frag:r,error:e,networkDetails:null};return t&&(i.part=t),(t||r).stats.aborted=!0,new $e(i)}class $e extends Error{constructor(t){super(t.error.message),this.data=void 0,this.data=t}}class wg{constructor(t){this.config=void 0,this.keyUriToKeyInfo={},this.emeController=null,this.config=t}abort(t){for(const e in this.keyUriToKeyInfo){const i=this.keyUriToKeyInfo[e].loader;if(i){if(t&&t!==i.context.frag.type)return;i.abort()}}}detach(){for(const t in this.keyUriToKeyInfo){const e=this.keyUriToKeyInfo[t];(e.mediaKeySessionContext||e.decryptdata.isCommonEncryption)&&delete this.keyUriToKeyInfo[t]}}destroy(){this.detach();for(const t in this.keyUriToKeyInfo){const e=this.keyUriToKeyInfo[t].loader;e&&e.destroy()}this.keyUriToKeyInfo={}}createKeyLoadError(t,e=$.KEY_LOAD_ERROR,i,s,n){return new $e({type:Q.NETWORK_ERROR,details:e,fatal:!1,frag:t,response:n,error:i,networkDetails:s})}loadClear(t,e){if(this.emeController&&this.config.emeEnabled){const{sn:i,cc:s}=t;for(let n=0;n<e.length;n++){const a=e[n];if(s<=a.cc&&(i==="initSegment"||a.sn==="initSegment"||i<a.sn)){this.emeController.selectKeySystemFormat(a).then(o=>{a.setKeyFormat(o)});break}}}}load(t){return!t.decryptdata&&t.encrypted&&this.emeController?this.emeController.selectKeySystemFormat(t).then(e=>this.loadInternal(t,e)):this.loadInternal(t)}loadInternal(t,e){var i,s;e&&t.setKeyFormat(e);const n=t.decryptdata;if(!n){const h=new Error(e?`Expected frag.decryptdata to be defined after setting format ${e}`:"Missing decryption data on fragment in onKeyLoading");return Promise.reject(this.createKeyLoadError(t,$.KEY_LOAD_ERROR,h))}const a=n.uri;if(!a)return Promise.reject(this.createKeyLoadError(t,$.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${a}"`)));let o=this.keyUriToKeyInfo[a];if((i=o)!=null&&i.decryptdata.key)return n.key=o.decryptdata.key,Promise.resolve({frag:t,keyInfo:o});if((s=o)!=null&&s.keyLoadPromise){var l;switch((l=o.mediaKeySessionContext)==null?void 0:l.keyStatus){case void 0:case"status-pending":case"usable":case"usable-in-future":return o.keyLoadPromise.then(h=>(n.key=h.keyInfo.decryptdata.key,{frag:t,keyInfo:o}))}}switch(o=this.keyUriToKeyInfo[a]={decryptdata:n,keyLoadPromise:null,loader:null,mediaKeySessionContext:null},n.method){case"ISO-23001-7":case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return n.keyFormat==="identity"?this.loadKeyHTTP(o,t):this.loadKeyEME(o,t);case"AES-128":return this.loadKeyHTTP(o,t);default:return Promise.reject(this.createKeyLoadError(t,$.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${n.method}"`)))}}loadKeyEME(t,e){const i={frag:e,keyInfo:t};if(this.emeController&&this.config.emeEnabled){const s=this.emeController.loadKey(i);if(s)return(t.keyLoadPromise=s.then(n=>(t.mediaKeySessionContext=n,i))).catch(n=>{throw t.keyLoadPromise=null,n})}return Promise.resolve(i)}loadKeyHTTP(t,e){const i=this.config,s=i.loader,n=new s(i);return e.keyLoader=t.loader=n,t.keyLoadPromise=new Promise((a,o)=>{const l={keyInfo:t,frag:e,responseType:"arraybuffer",url:t.decryptdata.uri},h=i.keyLoadPolicy.default,c={loadPolicy:h,timeout:h.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},d={onSuccess:(u,f,p,g)=>{const{frag:v,keyInfo:E,url:A}=p;if(!v.decryptdata||E!==this.keyUriToKeyInfo[A])return o(this.createKeyLoadError(v,$.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),g));E.decryptdata.key=v.decryptdata.key=new Uint8Array(u.data),v.keyLoader=null,E.loader=null,a({frag:v,keyInfo:E})},onError:(u,f,p,g)=>{this.resetLoader(f),o(this.createKeyLoadError(e,$.KEY_LOAD_ERROR,new Error(`HTTP Error ${u.code} loading key ${u.text}`),p,Qt({url:l.url,data:void 0},u)))},onTimeout:(u,f,p)=>{this.resetLoader(f),o(this.createKeyLoadError(e,$.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),p))},onAbort:(u,f,p)=>{this.resetLoader(f),o(this.createKeyLoadError(e,$.INTERNAL_ABORTED,new Error("key loading aborted"),p))}};n.load(l,c,d)})}resetLoader(t){const{frag:e,keyInfo:i,url:s}=t,n=i.loader;e.keyLoader===n&&(e.keyLoader=null,i.loader=null),delete this.keyUriToKeyInfo[s],n&&n.destroy()}}class Sg{constructor(){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(t){return this._tickInterval?!1:(this._tickCallCount=0,this._tickInterval=self.setInterval(this._boundTick,t),!0)}clearInterval(){return this._tickInterval?(self.clearInterval(this._tickInterval),this._tickInterval=null,!0):!1}clearNextTick(){return this._tickTimer?(self.clearTimeout(this._tickTimer),this._tickTimer=null,!0):!1}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(){}}const Lg={length:0,start:()=>0,end:()=>0};class Et{static isBuffered(t,e){try{if(t){const i=Et.getBuffered(t);for(let s=0;s<i.length;s++)if(e>=i.start(s)&&e<=i.end(s))return!0}}catch{}return!1}static bufferInfo(t,e,i){try{if(t){const s=Et.getBuffered(t),n=[];let a;for(a=0;a<s.length;a++)n.push({start:s.start(a),end:s.end(a)});return this.bufferedInfo(n,e,i)}}catch{}return{len:0,start:e,end:e,nextStart:void 0}}static bufferedInfo(t,e,i){e=Math.max(0,e),t.sort(function(h,c){return h.start-c.start||c.end-h.end});let s=[];if(i)for(let h=0;h<t.length;h++){const c=s.length;if(c){const d=s[c-1].end;t[h].start-d<i?t[h].end>d&&(s[c-1].end=t[h].end):s.push(t[h])}else s.push(t[h])}else s=t;let n=0,a,o=e,l=e;for(let h=0;h<s.length;h++){const c=s[h].start,d=s[h].end;if(e+i>=c&&e<d)o=c,l=d,n=l-e;else if(e+i<c){a=c;break}}return{len:n,start:o||0,end:l||0,nextStart:a}}static getBuffered(t){try{return t.buffered}catch(e){return _.log("failed to get media.buffered",e),Lg}}}class Vn{constructor(t,e,i,s=0,n=-1,a=!1){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=pr(),this.buffering={audio:pr(),video:pr(),audiovideo:pr()},this.level=t,this.sn=e,this.id=i,this.size=s,this.part=n,this.partial=a}}function pr(){return{start:0,executeStart:0,executeEnd:0,end:0}}function yh(r,t){let e=null;for(let i=0,s=r.length;i<s;i++){const n=r[i];if(n&&n.cc===t){e=n;break}}return e}function Rg(r,t,e){return!!(t.details&&(e.endCC>e.startCC||r&&r.cc<e.startCC))}function _g(r,t,e=0){const i=r.fragments,s=t.fragments;if(!s.length||!i.length){_.log("No fragments to align");return}const n=yh(i,s[0].cc);if(!n||n&&!n.startPTS){_.log("No frag in previous level to align on");return}return n}function Eh(r,t){if(r){const e=r.start+t;r.start=r.startPTS=e,r.endPTS=e+r.duration}}function Kn(r,t){const e=t.fragments;for(let i=0,s=e.length;i<s;i++)Eh(e[i],r);t.fragmentHint&&Eh(t.fragmentHint,r),t.alignedSliding=!0}function kg(r,t,e){t&&(Ig(r,e,t),!e.alignedSliding&&t.details&&Cg(e,t.details),!e.alignedSliding&&t.details&&!e.skippedSegments&&lh(t.details,e))}function Ig(r,t,e){if(Rg(r,e,t)){const i=_g(e.details,t);i&&q(i.start)&&(_.log(`Adjusting PTS using last level due to CC increase within current level ${t.url}`),Kn(i.start,t))}}function Cg(r,t){if(!t.fragments.length||!r.hasProgramDateTime||!t.hasProgramDateTime)return;const e=t.fragments[0].programDateTime,i=r.fragments[0].programDateTime,s=(i-e)/1e3+t.fragments[0].start;s&&q(s)&&(_.log(`Adjusting PTS using programDateTime delta ${i-e}ms, sliding:${s.toFixed(3)} ${r.url} `),Kn(s,r))}function bh(r,t){if(!r.hasProgramDateTime||!t.hasProgramDateTime)return;const e=r.fragments,i=t.fragments;if(!e.length||!i.length)return;const s=Math.round(i.length/2)-1,n=i[s],a=yh(e,n.cc)||e[Math.round(e.length/2)-1],o=n.programDateTime,l=a.programDateTime;if(o===null||l===null)return;const h=(l-o)/1e3-(a.start-n.start);Kn(h,r)}class Dg{constructor(t,e){this.subtle=void 0,this.aesIV=void 0,this.subtle=t,this.aesIV=e}decrypt(t,e){return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},e,t)}}class xg{constructor(t,e){this.subtle=void 0,this.key=void 0,this.subtle=t,this.key=e}expandKey(){return this.subtle.importKey("raw",this.key,{name:"AES-CBC"},!1,["encrypt","decrypt"])}}function Pg(r){const t=r.byteLength,e=t&&new DataView(r.buffer).getUint8(t-1);return e?ui(r,0,t-e):r}class Og{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_(t){const e=new DataView(t),i=new Uint32Array(4);for(let s=0;s<4;s++)i[s]=e.getUint32(s*4);return i}initTable(){const t=this.sBox,e=this.invSBox,i=this.subMix,s=i[0],n=i[1],a=i[2],o=i[3],l=this.invSubMix,h=l[0],c=l[1],d=l[2],u=l[3],f=new Uint32Array(256);let p=0,g=0,v=0;for(v=0;v<256;v++)v<128?f[v]=v<<1:f[v]=v<<1^283;for(v=0;v<256;v++){let E=g^g<<1^g<<2^g<<3^g<<4;E=E>>>8^E&255^99,t[p]=E,e[E]=p;const A=f[p],L=f[A],y=f[L];let S=f[E]*257^E*16843008;s[p]=S<<24|S>>>8,n[p]=S<<16|S>>>16,a[p]=S<<8|S>>>24,o[p]=S,S=y*16843009^L*65537^A*257^p*16843008,h[E]=S<<24|S>>>8,c[E]=S<<16|S>>>16,d[E]=S<<8|S>>>24,u[E]=S,p?(p=A^f[f[f[y^A]]],g^=f[f[g]]):p=g=1}}expandKey(t){const e=this.uint8ArrayToUint32Array_(t);let i=!0,s=0;for(;s<e.length&&i;)i=e[s]===this.key[s],s++;if(i)return;this.key=e;const n=this.keySize=e.length;if(n!==4&&n!==6&&n!==8)throw new Error("Invalid aes key size="+n);const a=this.ksRows=(n+6+1)*4;let o,l;const h=this.keySchedule=new Uint32Array(a),c=this.invKeySchedule=new Uint32Array(a),d=this.sBox,u=this.rcon,f=this.invSubMix,p=f[0],g=f[1],v=f[2],E=f[3];let A,L;for(o=0;o<a;o++){if(o<n){A=h[o]=e[o];continue}L=A,o%n===0?(L=L<<8|L>>>24,L=d[L>>>24]<<24|d[L>>>16&255]<<16|d[L>>>8&255]<<8|d[L&255],L^=u[o/n|0]<<24):n>6&&o%n===4&&(L=d[L>>>24]<<24|d[L>>>16&255]<<16|d[L>>>8&255]<<8|d[L&255]),h[o]=A=(h[o-n]^L)>>>0}for(l=0;l<a;l++)o=a-l,l&3?L=h[o]:L=h[o-4],l<4||o<=4?c[l]=L:c[l]=p[d[L>>>24]]^g[d[L>>>16&255]]^v[d[L>>>8&255]]^E[d[L&255]],c[l]=c[l]>>>0}networkToHostOrderSwap(t){return t<<24|(t&65280)<<8|(t&16711680)>>8|t>>>24}decrypt(t,e,i){const s=this.keySize+6,n=this.invKeySchedule,a=this.invSBox,o=this.invSubMix,l=o[0],h=o[1],c=o[2],d=o[3],u=this.uint8ArrayToUint32Array_(i);let f=u[0],p=u[1],g=u[2],v=u[3];const E=new Int32Array(t),A=new Int32Array(E.length);let L,y,S,R,C,M,D,I,G,F,V,z,w,P;const H=this.networkToHostOrderSwap;for(;e<E.length;){for(G=H(E[e]),F=H(E[e+1]),V=H(E[e+2]),z=H(E[e+3]),C=G^n[0],M=z^n[1],D=V^n[2],I=F^n[3],w=4,P=1;P<s;P++)L=l[C>>>24]^h[M>>16&255]^c[D>>8&255]^d[I&255]^n[w],y=l[M>>>24]^h[D>>16&255]^c[I>>8&255]^d[C&255]^n[w+1],S=l[D>>>24]^h[I>>16&255]^c[C>>8&255]^d[M&255]^n[w+2],R=l[I>>>24]^h[C>>16&255]^c[M>>8&255]^d[D&255]^n[w+3],C=L,M=y,D=S,I=R,w=w+4;L=a[C>>>24]<<24^a[M>>16&255]<<16^a[D>>8&255]<<8^a[I&255]^n[w],y=a[M>>>24]<<24^a[D>>16&255]<<16^a[I>>8&255]<<8^a[C&255]^n[w+1],S=a[D>>>24]<<24^a[I>>16&255]<<16^a[C>>8&255]<<8^a[M&255]^n[w+2],R=a[I>>>24]<<24^a[C>>16&255]<<16^a[M>>8&255]<<8^a[D&255]^n[w+3],A[e]=H(L^f),A[e+1]=H(R^p),A[e+2]=H(S^g),A[e+3]=H(y^v),f=G,p=F,g=V,v=z,e=e+4}return A.buffer}}const $g=16;class jn{constructor(t,{removePKCS7Padding:e=!0}={}){if(this.logEnabled=!0,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.useSoftware=t.enableSoftwareAES,this.removePKCS7Padding=e,e)try{const i=self.crypto;i&&(this.subtle=i.subtle||i.webkitSubtle)}catch{}this.subtle===null&&(this.useSoftware=!0)}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(){const{currentResult:t,remainderData:e}=this;if(!t||e)return this.reset(),null;const i=new Uint8Array(t);return this.reset(),this.removePKCS7Padding?Pg(i):i}reset(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&(this.softwareDecrypter=null)}decrypt(t,e,i){return this.useSoftware?new Promise((s,n)=>{this.softwareDecrypt(new Uint8Array(t),e,i);const a=this.flush();a?s(a.buffer):n(new Error("[softwareDecrypt] Failed to decrypt data"))}):this.webCryptoDecrypt(new Uint8Array(t),e,i)}softwareDecrypt(t,e,i){const{currentIV:s,currentResult:n,remainderData:a}=this;this.logOnce("JS AES decrypt"),a&&(t=fi(a,t),this.remainderData=null);const o=this.getValidChunk(t);if(!o.length)return null;s&&(i=s);let l=this.softwareDecrypter;l||(l=this.softwareDecrypter=new Og),l.expandKey(e);const h=n;return this.currentResult=l.decrypt(o.buffer,0,i),this.currentIV=ui(o,-16).buffer,h||null}webCryptoDecrypt(t,e,i){const s=this.subtle;return(this.key!==e||!this.fastAesKey)&&(this.key=e,this.fastAesKey=new xg(s,e)),this.fastAesKey.expandKey().then(n=>s?(this.logOnce("WebCrypto AES decrypt"),new Dg(s,new Uint8Array(i)).decrypt(t.buffer,n)):Promise.reject(new Error("web crypto not initialized"))).catch(n=>(_.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${n.name}: ${n.message}`),this.onWebCryptoError(t,e,i)))}onWebCryptoError(t,e,i){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(t,e,i);const s=this.flush();if(s)return s.buffer;throw new Error("WebCrypto and softwareDecrypt: failed to decrypt data")}getValidChunk(t){let e=t;const i=t.length-t.length%$g;return i!==t.length&&(e=ui(t,0,i),this.remainderData=ui(t,i)),e}logOnce(t){this.logEnabled&&(_.log(`[decrypter]: ${t}`),this.logEnabled=!1)}}const Mg={toString:function(r){let t="";const e=r.length;for(let i=0;i<e;i++)t+=`[${r.start(i).toFixed(3)}-${r.end(i).toFixed(3)}]`;return t}},B={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"};class Wn extends Sg{constructor(t,e,i,s,n){super(),this.hls=void 0,this.fragPrevious=null,this.fragCurrent=null,this.fragmentTracker=void 0,this.transmuxer=null,this._state=B.STOPPED,this.playlistType=void 0,this.media=null,this.mediaBuffer=null,this.config=void 0,this.bitrateTest=!1,this.lastCurrentTime=0,this.nextLoadPosition=0,this.startPosition=0,this.startTimeOffset=null,this.loadedmetadata=!1,this.retryDate=0,this.levels=null,this.fragmentLoader=void 0,this.keyLoader=void 0,this.levelLastLoaded=null,this.startFragRequested=!1,this.decrypter=void 0,this.initPTS=[],this.onvseeking=null,this.onvended=null,this.logPrefix="",this.log=void 0,this.warn=void 0,this.playlistType=n,this.logPrefix=s,this.log=_.log.bind(_,`${s}:`),this.warn=_.warn.bind(_,`${s}:`),this.hls=t,this.fragmentLoader=new Ag(t.config),this.keyLoader=i,this.fragmentTracker=e,this.config=t.config,this.decrypter=new jn(t.config),t.on(m.MANIFEST_LOADED,this.onManifestLoaded,this)}doTick(){this.onTickEnd()}onTickEnd(){}startLoad(t){}stopLoad(){this.fragmentLoader.abort(),this.keyLoader.abort(this.playlistType);const t=this.fragCurrent;t!=null&&t.loader&&(t.abortRequests(),this.fragmentTracker.removeFragment(t)),this.resetTransmuxer(),this.fragCurrent=null,this.fragPrevious=null,this.clearInterval(),this.clearNextTick(),this.state=B.STOPPED}_streamEnded(t,e){if(e.live||t.nextStart||!t.end||!this.media)return!1;const i=e.partList;if(i!=null&&i.length){const n=i[i.length-1];return Et.isBuffered(this.media,n.start+n.duration/2)}const s=e.fragments[e.fragments.length-1].type;return this.fragmentTracker.isEndListAppended(s)}getLevelDetails(){if(this.levels&&this.levelLastLoaded!==null){var t;return(t=this.levels[this.levelLastLoaded])==null?void 0:t.details}}onMediaAttached(t,e){const i=this.media=this.mediaBuffer=e.media;this.onvseeking=this.onMediaSeeking.bind(this),this.onvended=this.onMediaEnded.bind(this),i.addEventListener("seeking",this.onvseeking),i.addEventListener("ended",this.onvended);const s=this.config;this.levels&&s.autoStartLoad&&this.state===B.STOPPED&&this.startLoad(s.startPosition)}onMediaDetaching(){const t=this.media;t!=null&&t.ended&&(this.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0),t&&this.onvseeking&&this.onvended&&(t.removeEventListener("seeking",this.onvseeking),t.removeEventListener("ended",this.onvended),this.onvseeking=this.onvended=null),this.keyLoader&&this.keyLoader.detach(),this.media=this.mediaBuffer=null,this.loadedmetadata=!1,this.fragmentTracker.removeAllFragments(),this.stopLoad()}onMediaSeeking(){const{config:t,fragCurrent:e,media:i,mediaBuffer:s,state:n}=this,a=i?i.currentTime:0,o=Et.bufferInfo(s||i,a,t.maxBufferHole);if(this.log(`media seeking to ${q(a)?a.toFixed(3):a}, state: ${n}`),this.state===B.ENDED)this.resetLoadingState();else if(e){const l=t.maxFragLookUpTolerance,h=e.start-l,c=e.start+e.duration+l;if(!o.len||c<o.start||h>o.end){const d=a>c;(a<h||d)&&(d&&e.loader&&(this.log("seeking outside of buffer while fragment load in progress, cancel fragment load"),e.abortRequests(),this.resetLoadingState()),this.fragPrevious=null)}}i&&(this.fragmentTracker.removeFragmentsInRange(a,1/0,this.playlistType,!0),this.lastCurrentTime=a),!this.loadedmetadata&&!o.len&&(this.nextLoadPosition=this.startPosition=a),this.tickImmediate()}onMediaEnded(){this.startPosition=this.lastCurrentTime=0}onManifestLoaded(t,e){this.startTimeOffset=e.startTimeOffset,this.initPTS=[]}onHandlerDestroying(){this.stopLoad(),super.onHandlerDestroying()}onHandlerDestroyed(){this.state=B.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(t,e,i){this._loadFragForPlayback(t,e,i)}_loadFragForPlayback(t,e,i){const s=n=>{if(this.fragContextChanged(t)){this.warn(`Fragment ${t.sn}${n.part?" p: "+n.part.index:""} of level ${t.level} was dropped during download.`),this.fragmentTracker.removeFragment(t);return}t.stats.chunkCount++,this._handleFragmentLoadProgress(n)};this._doFragLoad(t,e,i,s).then(n=>{if(!n)return;const a=this.state;if(this.fragContextChanged(t)){(a===B.FRAG_LOADING||!this.fragCurrent&&a===B.PARSING)&&(this.fragmentTracker.removeFragment(t),this.state=B.IDLE);return}"payload"in n&&(this.log(`Loaded fragment ${t.sn} of level ${t.level}`),this.hls.trigger(m.FRAG_LOADED,n)),this._handleFragmentLoadComplete(n)}).catch(n=>{this.state===B.STOPPED||this.state===B.ERROR||(this.warn(n),this.resetFragmentLoading(t))})}clearTrackerIfNeeded(t){var e;const{fragmentTracker:i}=this;if(i.getState(t)===$t.APPENDING){const s=t.type,n=this.getFwdBufferInfo(this.mediaBuffer,s),a=Math.max(t.duration,n?n.len:this.config.maxBufferLength);this.reduceMaxBufferLength(a)&&i.removeFragment(t)}else((e=this.mediaBuffer)==null?void 0:e.buffered.length)===0?i.removeAllFragments():i.hasParts(t.type)&&(i.detectPartialFragments({frag:t,part:null,stats:t.stats,id:t.type}),i.getState(t)===$t.PARTIAL&&i.removeFragment(t))}checkLiveUpdate(t){if(t.updated&&!t.live){const e=t.fragments[t.fragments.length-1];this.fragmentTracker.detectPartialFragments({frag:e,part:null,stats:e.stats,id:e.type})}t.fragments[0]||(t.deltaUpdateFailed=!0)}flushMainBuffer(t,e,i=null){if(!(t-e))return;const s={startOffset:t,endOffset:e,type:i};this.hls.trigger(m.BUFFER_FLUSHING,s)}_loadInitSegment(t,e){this._doFragLoad(t,e).then(i=>{if(!i||this.fragContextChanged(t)||!this.levels)throw new Error("init load aborted");return i}).then(i=>{const{hls:s}=this,{payload:n}=i,a=t.decryptdata;if(n&&n.byteLength>0&&a&&a.key&&a.iv&&a.method==="AES-128"){const o=self.performance.now();return this.decrypter.decrypt(new Uint8Array(n),a.key.buffer,a.iv.buffer).catch(l=>{throw s.trigger(m.ERROR,{type:Q.MEDIA_ERROR,details:$.FRAG_DECRYPT_ERROR,fatal:!1,error:l,reason:l.message,frag:t}),l}).then(l=>{const h=self.performance.now();return s.trigger(m.FRAG_DECRYPTED,{frag:t,payload:l,stats:{tstart:o,tdecrypt:h}}),i.payload=l,i})}return i}).then(i=>{const{fragCurrent:s,hls:n,levels:a}=this;if(!a)throw new Error("init load aborted, missing levels");const o=t.stats;this.state=B.IDLE,e.fragmentError=0,t.data=new Uint8Array(i.payload),o.parsing.start=o.buffering.start=self.performance.now(),o.parsing.end=o.buffering.end=self.performance.now(),i.frag===s&&n.trigger(m.FRAG_BUFFERED,{stats:o,frag:s,part:null,id:t.type}),this.tick()}).catch(i=>{this.state===B.STOPPED||this.state===B.ERROR||(this.warn(i),this.resetFragmentLoading(t))})}fragContextChanged(t){const{fragCurrent:e}=this;return!t||!e||t.level!==e.level||t.sn!==e.sn||t.urlId!==e.urlId}fragBufferedComplete(t,e){var i,s,n,a;const o=this.mediaBuffer?this.mediaBuffer:this.media;this.log(`Buffered ${t.type} sn: ${t.sn}${e?" part: "+e.index:""} of ${this.playlistType===Z.MAIN?"level":"track"} ${t.level} (frag:[${((i=t.startPTS)!=null?i:NaN).toFixed(3)}-${((s=t.endPTS)!=null?s:NaN).toFixed(3)}] > buffer:${o?Mg.toString(Et.getBuffered(o)):"(detached)"})`),this.state=B.IDLE,o&&(!this.loadedmetadata&&t.type==Z.MAIN&&o.buffered.length&&((n=this.fragCurrent)==null?void 0:n.sn)===((a=this.fragPrevious)==null?void 0:a.sn)&&(this.loadedmetadata=!0,this.seekToStartPos()),this.tick())}seekToStartPos(){}_handleFragmentLoadComplete(t){const{transmuxer:e}=this;if(!e)return;const{frag:i,part:s,partsLoaded:n}=t,a=!n||n.length===0||n.some(l=>!l),o=new Vn(i.level,i.sn,i.stats.chunkCount+1,0,s?s.index:-1,!a);e.flush(o)}_handleFragmentLoadProgress(t){}_doFragLoad(t,e,i=null,s){var n;const a=e==null?void 0:e.details;if(!this.levels||!a)throw new Error(`frag load aborted, missing level${a?"":" detail"}s`);let o=null;if(t.encrypted&&!((n=t.decryptdata)!=null&&n.key)?(this.log(`Loading key for ${t.sn} of [${a.startSN}-${a.endSN}], ${this.logPrefix==="[stream-controller]"?"level":"track"} ${t.level}`),this.state=B.KEY_LOADING,this.fragCurrent=t,o=this.keyLoader.load(t).then(c=>{if(!this.fragContextChanged(c.frag))return this.hls.trigger(m.KEY_LOADED,c),this.state===B.KEY_LOADING&&(this.state=B.IDLE),c}),this.hls.trigger(m.KEY_LOADING,{frag:t}),this.fragCurrent===null&&(o=Promise.reject(new Error("frag load aborted, context changed in KEY_LOADING")))):!t.encrypted&&a.encryptedFragments.length&&this.keyLoader.loadClear(t,a.encryptedFragments),i=Math.max(t.start,i||0),this.config.lowLatencyMode&&t.sn!=="initSegment"){const c=a.partList;if(c&&s){i>t.end&&a.fragmentHint&&(t=a.fragmentHint);const d=this.getNextPart(c,t,i);if(d>-1){const u=c[d];this.log(`Loading part sn: ${t.sn} p: ${u.index} cc: ${t.cc} of playlist [${a.startSN}-${a.endSN}] parts [0-${d}-${c.length-1}] ${this.logPrefix==="[stream-controller]"?"level":"track"}: ${t.level}, target: ${parseFloat(i.toFixed(3))}`),this.nextLoadPosition=u.start+u.duration,this.state=B.FRAG_LOADING;let f;return o?f=o.then(p=>!p||this.fragContextChanged(p.frag)?null:this.doFragPartsLoad(t,u,e,s)).catch(p=>this.handleFragLoadError(p)):f=this.doFragPartsLoad(t,u,e,s).catch(p=>this.handleFragLoadError(p)),this.hls.trigger(m.FRAG_LOADING,{frag:t,part:u,targetBufferTime:i}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):f}else if(!t.url||this.loadedEndOfParts(c,i))return Promise.resolve(null)}}this.log(`Loading fragment ${t.sn} cc: ${t.cc} ${a?"of ["+a.startSN+"-"+a.endSN+"] ":""}${this.logPrefix==="[stream-controller]"?"level":"track"}: ${t.level}, target: ${parseFloat(i.toFixed(3))}`),q(t.sn)&&!this.bitrateTest&&(this.nextLoadPosition=t.start+t.duration),this.state=B.FRAG_LOADING;const l=this.config.progressive;let h;return l&&o?h=o.then(c=>!c||this.fragContextChanged(c==null?void 0:c.frag)?null:this.fragmentLoader.load(t,s)).catch(c=>this.handleFragLoadError(c)):h=Promise.all([this.fragmentLoader.load(t,l?s:void 0),o]).then(([c])=>(!l&&c&&s&&s(c),c)).catch(c=>this.handleFragLoadError(c)),this.hls.trigger(m.FRAG_LOADING,{frag:t,targetBufferTime:i}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):h}doFragPartsLoad(t,e,i,s){return new Promise((n,a)=>{var o;const l=[],h=(o=i.details)==null?void 0:o.partList,c=d=>{this.fragmentLoader.loadPart(t,d,s).then(u=>{l[d.index]=u;const f=u.part;this.hls.trigger(m.FRAG_LOADED,u);const p=hh(i,t.sn,d.index+1)||ch(h,t.sn,d.index+1);if(p)c(p);else return n({frag:t,part:f,partsLoaded:l})}).catch(a)};c(e)})}handleFragLoadError(t){if("data"in t){const e=t.data;t.data&&e.details===$.INTERNAL_ABORTED?this.handleFragLoadAborted(e.frag,e.part):this.hls.trigger(m.ERROR,e)}else this.hls.trigger(m.ERROR,{type:Q.OTHER_ERROR,details:$.INTERNAL_EXCEPTION,err:t,error:t,fatal:!0});return null}_handleTransmuxerFlush(t){const e=this.getCurrentContext(t);if(!e||this.state!==B.PARSING){!this.fragCurrent&&this.state!==B.STOPPED&&this.state!==B.ERROR&&(this.state=B.IDLE);return}const{frag:i,part:s,level:n}=e,a=self.performance.now();i.stats.parsing.end=a,s&&(s.stats.parsing.end=a),this.updateLevelTiming(i,s,n,t.partial)}getCurrentContext(t){const{levels:e,fragCurrent:i}=this,{level:s,sn:n,part:a}=t;if(!(e!=null&&e[s]))return this.warn(`Levels object was unset while buffering fragment ${n} of level ${s}. The current chunk will not be buffered.`),null;const o=e[s],l=a>-1?hh(o,n,a):null,h=l?l.fragment:ug(o,n,i);return h?(i&&i!==h&&(h.stats=i.stats),{frag:h,part:l,level:o}):null}bufferFragmentData(t,e,i,s,n){var a;if(!t||this.state!==B.PARSING)return;const{data1:o,data2:l}=t;let h=o;if(o&&l&&(h=fi(o,l)),!((a=h)!=null&&a.length))return;const c={type:t.type,frag:e,part:i,chunkMeta:s,parent:e.type,data:h};if(this.hls.trigger(m.BUFFER_APPENDING,c),t.dropped&&t.independent&&!i){if(n)return;this.flushBufferGap(e)}}flushBufferGap(t){const e=this.media;if(!e)return;if(!Et.isBuffered(e,e.currentTime)){this.flushMainBuffer(0,t.start);return}const i=e.currentTime,s=Et.bufferInfo(e,i,0),n=t.duration,a=Math.min(this.config.maxFragLookUpTolerance*2,n*.25),o=Math.max(Math.min(t.start-a,s.end-a),i+a);t.start-o>a&&this.flushMainBuffer(o,t.start)}getFwdBufferInfo(t,e){const i=this.getLoadPosition();return q(i)?this.getFwdBufferInfoAtPos(t,i,e):null}getFwdBufferInfoAtPos(t,e,i){const{config:{maxBufferHole:s}}=this,n=Et.bufferInfo(t,e,s);if(n.len===0&&n.nextStart!==void 0){const a=this.fragmentTracker.getBufferedFrag(e,i);if(a&&n.nextStart<a.end)return Et.bufferInfo(t,e,Math.max(n.nextStart,s))}return n}getMaxBufferLength(t){const{config:e}=this;let i;return t?i=Math.max(8*e.maxBufferSize/t,e.maxBufferLength):i=e.maxBufferLength,Math.min(i,e.maxMaxBufferLength)}reduceMaxBufferLength(t){const e=this.config,i=t||e.maxBufferLength;return e.maxMaxBufferLength>=i?(e.maxMaxBufferLength/=2,this.warn(`Reduce max buffer length to ${e.maxMaxBufferLength}s`),!0):!1}getAppendedFrag(t,e=Z.MAIN){const i=this.fragmentTracker.getAppendedFrag(t,Z.MAIN);return i&&"fragment"in i?i.fragment:i}getNextFragment(t,e){const i=e.fragments,s=i.length;if(!s)return null;const{config:n}=this,a=i[0].start;let o;if(e.live){const l=n.initialLiveManifestSize;if(s<l)return this.warn(`Not enough fragments to start playback (have: ${s}, need: ${l})`),null;!e.PTSKnown&&!this.startFragRequested&&this.startPosition===-1&&(o=this.getInitialLiveFragment(e,i),this.startPosition=o?this.hls.liveSyncPosition||o.start:t)}else t<=a&&(o=i[0]);if(!o){const l=n.lowLatencyMode?e.partEnd:e.fragmentEnd;o=this.getFragmentAtPosition(t,l,e)}return this.mapToInitFragWhenRequired(o)}isLoopLoading(t,e){const i=this.fragmentTracker.getState(t);return(i===$t.OK||i===$t.PARTIAL&&!!t.gap)&&this.nextLoadPosition>e}getNextFragmentLoopLoading(t,e,i,s,n){const a=t.gap,o=this.getNextFragment(this.nextLoadPosition,e);if(o===null)return o;if(t=o,a&&t&&!t.gap&&i.nextStart){const l=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,i.nextStart,s);if(l!==null&&i.len+l.len>=n)return this.log(`buffer full after gaps in "${s}" playlist starting at sn: ${t.sn}`),null}return t}mapToInitFragWhenRequired(t){return t!=null&&t.initSegment&&!(t!=null&&t.initSegment.data)&&!this.bitrateTest?t.initSegment:t}getNextPart(t,e,i){let s=-1,n=!1,a=!0;for(let o=0,l=t.length;o<l;o++){const h=t[o];if(a=a&&!h.independent,s>-1&&i<h.start)break;const c=h.loaded;c?s=-1:(n||h.independent||a)&&h.fragment===e&&(s=o),n=c}return s}loadedEndOfParts(t,e){const i=t[t.length-1];return i&&e>i.start&&i.loaded}getInitialLiveFragment(t,e){const i=this.fragPrevious;let s=null;if(i){if(t.hasProgramDateTime&&(this.log(`Live playlist, switching playlist, load frag with same PDT: ${i.programDateTime}`),s=pg(e,i.endProgramDateTime,this.config.maxFragLookUpTolerance)),!s){const n=i.sn+1;if(n>=t.startSN&&n<=t.endSN){const a=e[n-t.startSN];i.cc===a.cc&&(s=a,this.log(`Live playlist, switching playlist, load frag with next SN: ${s.sn}`))}s||(s=mg(e,i.cc),s&&this.log(`Live playlist, switching playlist, load frag with same CC: ${s.sn}`))}}else{const n=this.hls.liveSyncPosition;n!==null&&(s=this.getFragmentAtPosition(n,this.bitrateTest?t.fragmentEnd:t.edge,t))}return s}getFragmentAtPosition(t,e,i){const{config:s}=this;let{fragPrevious:n}=this,{fragments:a,endSN:o}=i;const{fragmentHint:l}=i,h=s.maxFragLookUpTolerance,c=i.partList,d=!!(s.lowLatencyMode&&c!=null&&c.length&&l);d&&l&&!this.bitrateTest&&(a=a.concat(l),o=l.sn);let u;if(t<e){const f=t>e-h?0:h;u=As(n,a,t,f)}else u=a[a.length-1];if(u){const f=u.sn-i.startSN,p=this.fragmentTracker.getState(u);if((p===$t.OK||p===$t.PARTIAL&&u.gap)&&(n=u),n&&u.sn===n.sn&&(!d||c[0].fragment.sn>u.sn)&&n&&u.level===n.level){const g=a[f+1];u.sn<o&&this.fragmentTracker.getState(g)!==$t.OK?u=g:u=null}}return u}synchronizeToLiveEdge(t){const{config:e,media:i}=this;if(!i)return;const s=this.hls.liveSyncPosition,n=i.currentTime,a=t.fragments[0].start,o=t.edge,l=n>=a-e.maxFragLookUpTolerance&&n<=o;if(s!==null&&i.duration>s&&(n<s||!l)){const h=e.liveMaxLatencyDuration!==void 0?e.liveMaxLatencyDuration:e.liveMaxLatencyDurationCount*t.targetduration;(!l&&i.readyState<4||n<o-h)&&(this.loadedmetadata||(this.nextLoadPosition=s),i.readyState&&(this.warn(`Playback: ${n.toFixed(3)} is located too far from the end of live sliding playlist: ${o}, reset currentTime to : ${s.toFixed(3)}`),i.currentTime=s))}}alignPlaylists(t,e){const{levels:i,levelLastLoaded:s,fragPrevious:n}=this,a=s!==null?i[s]:null,o=t.fragments.length;if(!o)return this.warn("No fragments in live playlist"),0;const l=t.fragments[0].start,h=!e,c=t.alignedSliding&&q(l);if(h||!c&&!l){kg(n,a,t);const d=t.fragments[0].start;return this.log(`Live playlist sliding: ${d.toFixed(2)} start-sn: ${e?e.startSN:"na"}->${t.startSN} prev-sn: ${n?n.sn:"na"} fragments: ${o}`),d}return l}waitForCdnTuneIn(t){return t.live&&t.canBlockReload&&t.partTarget&&t.tuneInGoal>Math.max(t.partHoldBack,t.partTarget*3)}setStartPosition(t,e){let i=this.startPosition;if(i<e&&(i=-1),i===-1||this.lastCurrentTime===-1){const s=this.startTimeOffset!==null,n=s?this.startTimeOffset:t.startTimeOffset;n!==null&&q(n)?(i=e+n,n<0&&(i+=t.totalduration),i=Math.min(Math.max(e,i),e+t.totalduration),this.log(`Start time offset ${n} found in ${s?"multivariant":"media"} playlist, adjust startPosition to ${i}`),this.startPosition=i):t.live?i=this.hls.liveSyncPosition||e:this.startPosition=i=0,this.lastCurrentTime=i}this.nextLoadPosition=i}getLoadPosition(){const{media:t}=this;let e=0;return this.loadedmetadata&&t?e=t.currentTime:this.nextLoadPosition&&(e=this.nextLoadPosition),e}handleFragLoadAborted(t,e){this.transmuxer&&t.sn!=="initSegment"&&t.stats.aborted&&(this.warn(`Fragment ${t.sn}${e?" part "+e.index:""} of level ${t.level} was aborted`),this.resetFragmentLoading(t))}resetFragmentLoading(t){(!this.fragCurrent||!this.fragContextChanged(t)&&this.state!==B.FRAG_LOADING_WAITING_RETRY)&&(this.state=B.IDLE)}onFragmentOrKeyLoadError(t,e){if(e.chunkMeta&&!e.frag){const d=this.getCurrentContext(e.chunkMeta);d&&(e.frag=d.frag)}const i=e.frag;if(!i||i.type!==t||!this.levels)return;if(this.fragContextChanged(i)){var s;this.warn(`Frag load error must match current frag to retry ${i.url} > ${(s=this.fragCurrent)==null?void 0:s.url}`);return}const n=e.details===$.FRAG_GAP;n&&this.fragmentTracker.fragBuffered(i,!0);const a=e.errorAction,{action:o,retryCount:l=0,retryConfig:h}=a||{};if(a&&o===Gt.RetryRequest&&h){var c;this.resetStartWhenNotLoaded((c=this.levelLastLoaded)!=null?c:i.level);const d=Un(h,l);this.warn(`Fragment ${i.sn} of ${t} ${i.level} errored with ${e.details}, retrying loading ${l+1}/${h.maxNumRetry} in ${d}ms`),a.resolved=!0,this.retryDate=self.performance.now()+d,this.state=B.FRAG_LOADING_WAITING_RETRY}else h&&a?(this.resetFragmentErrors(t),l<h.maxNumRetry?n||(a.resolved=!0):_.warn(`${e.details} reached or exceeded max retry (${l})`)):(a==null?void 0:a.action)===Gt.SendAlternateToPenaltyBox?this.state=B.WAITING_LEVEL:this.state=B.ERROR;this.tickImmediate()}reduceLengthAndFlushBuffer(t){if(this.state===B.PARSING||this.state===B.PARSED){const e=t.parent,i=this.getFwdBufferInfo(this.mediaBuffer,e),s=i&&i.len>.5;s&&this.reduceMaxBufferLength(i.len);const n=!s;return n&&this.warn(`Buffer full error while media.currentTime is not buffered, flush ${e} buffer`),t.frag&&(this.fragmentTracker.removeFragment(t.frag),this.nextLoadPosition=t.frag.start),this.resetLoadingState(),n}return!1}resetFragmentErrors(t){t===Z.AUDIO&&(this.fragCurrent=null),this.loadedmetadata||(this.startFragRequested=!1),this.state!==B.STOPPED&&(this.state=B.IDLE)}afterBufferFlushed(t,e,i){if(!t)return;const s=Et.getBuffered(t);this.fragmentTracker.detectEvictedFragments(e,s,i),this.state===B.ENDED&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state=B.IDLE}resetStartWhenNotLoaded(t){if(!this.loadedmetadata){this.startFragRequested=!1;const e=this.levels?this.levels[t].details:null;e!=null&&e.live?(this.startPosition=-1,this.setStartPosition(e,0),this.resetLoadingState()):this.nextLoadPosition=this.startPosition}}resetWhenMissingContext(t){var e;this.warn(`The loading context changed while buffering fragment ${t.sn} of level ${t.level}. This chunk will not be buffered.`),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded((e=this.levelLastLoaded)!=null?e:t.level),this.resetLoadingState()}removeUnbufferedFrags(t=0){this.fragmentTracker.removeFragmentsInRange(t,1/0,this.playlistType,!1,!0)}updateLevelTiming(t,e,i,s){var n;const a=i.details;if(!a){this.warn("level.details undefined");return}if(Object.keys(t.elementaryStreams).reduce((o,l)=>{const h=t.elementaryStreams[l];if(h){const c=h.endPTS-h.startPTS;if(c<=0)return this.warn(`Could not parse fragment ${t.sn} ${l} duration reliably (${c})`),o||!1;const d=s?0:oh(a,t,h.startPTS,h.endPTS,h.startDTS,h.endDTS);return this.hls.trigger(m.LEVEL_PTS_UPDATED,{details:a,level:i,drift:d,type:l,frag:t,start:h.startPTS,end:h.endPTS}),!0}return o},!1))i.fragmentError=0;else if(((n=this.transmuxer)==null?void 0:n.error)===null){const o=new Error(`Found no media in fragment ${t.sn} of level ${t.level} resetting transmuxer to fallback to playlist timing`);if(i.fragmentError===0&&(i.fragmentError++,t.gap=!0,this.fragmentTracker.removeFragment(t),this.fragmentTracker.fragBuffered(t,!0)),this.warn(o.message),this.hls.trigger(m.ERROR,{type:Q.MEDIA_ERROR,details:$.FRAG_PARSING_ERROR,fatal:!1,error:o,frag:t,reason:`Found no media in msn ${t.sn} of level "${i.url}"`}),!this.hls)return;this.resetTransmuxer()}this.state=B.PARSED,this.hls.trigger(m.FRAG_PARSED,{frag:t,part:e})}resetTransmuxer(){this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null)}recoverWorkerError(t){if(t.event==="demuxerWorker"){var e,i,s;this.fragmentTracker.removeAllFragments(),this.resetTransmuxer(),this.resetStartWhenNotLoaded((e=(i=this.levelLastLoaded)!=null?i:(s=this.fragCurrent)==null?void 0:s.level)!=null?e:0),this.resetLoadingState()}}set state(t){const e=this._state;e!==t&&(this._state=t,this.log(`${e}->${t}`))}get state(){return this._state}}function Th(){return self.SourceBuffer||self.WebKitSourceBuffer}function Fg(){const r=lr();if(!r)return!1;const t=Th(),e=r&&typeof r.isTypeSupported=="function"&&r.isTypeSupported('video/mp4; codecs="avc1.42E01E,mp4a.40.2"'),i=!t||t.prototype&&typeof t.prototype.appendBuffer=="function"&&typeof t.prototype.remove=="function";return!!e&&!!i}function Ng(){var r;const t=Th();return typeof(t==null||(r=t.prototype)==null?void 0:r.changeType)=="function"}function Ug(){return typeof __HLS_WORKER_BUNDLE__=="function"}function Bg(){const r=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(r);return{worker:new self.Worker(t),objectURL:t}}function Hg(r){const t=new self.URL(r,self.location.href).href;return{worker:new self.Worker(t),scriptURL:t}}function Re(r="",t=9e4){return{type:r,id:-1,pid:-1,inputTimeScale:t,sequenceNumber:-1,samples:[],dropped:0}}class Ah{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(t,e,i,s){this._id3Track={type:"id3",id:3,pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0}}resetTimeStamp(t){this.initPTS=t,this.resetContiguity()}resetContiguity(){this.basePTS=null,this.lastPTS=null,this.frameIndex=0}canParse(t,e){return!1}appendFrame(t,e,i){}demux(t,e){this.cachedData&&(t=fi(this.cachedData,t),this.cachedData=null);let i=rr(t,0),s=i?i.length:0,n;const a=this._audioTrack,o=this._id3Track,l=i?wp(i):void 0,h=t.length;for((this.basePTS===null||this.frameIndex===0&&q(l))&&(this.basePTS=Gg(l,e,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:ve.audioId3,duration:Number.POSITIVE_INFINITY});s<h;){if(this.canParse(t,s)){const c=this.appendFrame(a,t,s);c?(this.frameIndex++,this.lastPTS=c.sample.pts,s+=c.length,n=s):s=h}else Ap(t,s)?(i=rr(t,s),o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:i,type:ve.audioId3,duration:Number.POSITIVE_INFINITY}),s+=i.length,n=s):s++;if(s===h&&n!==h){const c=ui(t,n);this.cachedData?this.cachedData=fi(this.cachedData,c):this.cachedData=c}}return{audioTrack:a,videoTrack:Re(),id3Track:o,textTrack:Re()}}demuxSampleAes(t,e,i){return Promise.reject(new Error(`[${this}] This demuxer does not support Sample-AES decryption`))}flush(t){const e=this.cachedData;return e&&(this.cachedData=null,this.demux(e,0)),{audioTrack:this._audioTrack,videoTrack:Re(),id3Track:this._id3Track,textTrack:Re()}}destroy(){}}const Gg=(r,t,e)=>{if(q(r))return r*90;const i=e?e.baseTime*9e4/e.timescale:0;return t*9e4+i};function Vg(r,t,e,i){let s,n,a,o;const l=navigator.userAgent.toLowerCase(),h=i,c=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350];s=((t[e+2]&192)>>>6)+1;const d=(t[e+2]&60)>>>2;if(d>c.length-1){r.trigger(m.ERROR,{type:Q.MEDIA_ERROR,details:$.FRAG_PARSING_ERROR,fatal:!0,reason:`invalid ADTS sampling index:${d}`});return}return a=(t[e+2]&1)<<2,a|=(t[e+3]&192)>>>6,_.log(`manifest codec:${i}, ADTS type:${s}, samplingIndex:${d}`),/firefox/i.test(l)?d>=6?(s=5,o=new Array(4),n=d-3):(s=2,o=new Array(2),n=d):l.indexOf("android")!==-1?(s=2,o=new Array(2),n=d):(s=5,o=new Array(4),i&&(i.indexOf("mp4a.40.29")!==-1||i.indexOf("mp4a.40.5")!==-1)||!i&&d>=6?n=d-3:((i&&i.indexOf("mp4a.40.2")!==-1&&(d>=6&&a===1||/vivaldi/i.test(l))||!i&&a===1)&&(s=2,o=new Array(2)),n=d)),o[0]=s<<3,o[0]|=(d&14)>>1,o[1]|=(d&1)<<7,o[1]|=a<<3,s===5&&(o[1]|=(n&14)>>1,o[2]=(n&1)<<7,o[2]|=8,o[3]=0),{config:o,samplerate:c[d],channelCount:a,codec:"mp4a.40."+s,manifestCodec:h}}function wh(r,t){return r[t]===255&&(r[t+1]&246)===240}function Sh(r,t){return r[t+1]&1?7:9}function Yn(r,t){return(r[t+3]&3)<<11|r[t+4]<<3|(r[t+5]&224)>>>5}function Kg(r,t){return t+5<r.length}function gr(r,t){return t+1<r.length&&wh(r,t)}function jg(r,t){return Kg(r,t)&&wh(r,t)&&Yn(r,t)<=r.length-t}function Wg(r,t){if(gr(r,t)){const e=Sh(r,t);if(t+e>=r.length)return!1;const i=Yn(r,t);if(i<=e)return!1;const s=t+i;return s===r.length||gr(r,s)}return!1}function Lh(r,t,e,i,s){if(!r.samplerate){const n=Vg(t,e,i,s);if(!n)return;r.config=n.config,r.samplerate=n.samplerate,r.channelCount=n.channelCount,r.codec=n.codec,r.manifestCodec=n.manifestCodec,_.log(`parsed codec:${r.codec}, rate:${n.samplerate}, channels:${n.channelCount}`)}}function Rh(r){return 9216e4/r}function Yg(r,t){const e=Sh(r,t);if(t+e<=r.length){const i=Yn(r,t)-e;if(i>0)return{headerLength:e,frameLength:i}}}function _h(r,t,e,i,s){const n=Rh(r.samplerate),a=i+s*n,o=Yg(t,e);let l;if(o){const{frameLength:c,headerLength:d}=o,u=d+c,f=Math.max(0,e+u-t.length);f?(l=new Uint8Array(u-d),l.set(t.subarray(e+d,t.length),0)):l=t.subarray(e+d,e+u);const p={unit:l,pts:a};return f||r.samples.push(p),{sample:p,length:u,missing:f}}const h=t.length-e;return l=new Uint8Array(h),l.set(t.subarray(e,t.length),0),{sample:{unit:l,pts:a},length:h,missing:-1}}class zg extends Ah{constructor(t,e){super(),this.observer=void 0,this.config=void 0,this.observer=t,this.config=e}resetInitSegment(t,e,i,s){super.resetInitSegment(t,e,i,s),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:e,duration:s,inputTimeScale:9e4,dropped:0}}static probe(t){if(!t)return!1;let e=(rr(t,0)||[]).length;for(let i=t.length;e<i;e++)if(Wg(t,e))return _.log("ADTS sync word found !"),!0;return!1}canParse(t,e){return jg(t,e)}appendFrame(t,e,i){Lh(t,this.observer,e,i,t.manifestCodec);const s=_h(t,e,i,this.basePTS,this.frameIndex);if(s&&s.missing===0)return s}}const qg=/\/emsg[-/]ID3/i;class Xg{constructor(t,e){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=e}resetTimeStamp(){}resetInitSegment(t,e,i,s){const n=this.videoTrack=Re("video",1),a=this.audioTrack=Re("audio",1),o=this.txtTrack=Re("text",1);if(this.id3Track=Re("id3",1),this.timeOffset=0,!(t!=null&&t.byteLength))return;const l=Ul(t);if(l.video){const{id:h,timescale:c,codec:d}=l.video;n.id=h,n.timescale=o.timescale=c,n.codec=d}if(l.audio){const{id:h,timescale:c,codec:d}=l.audio;a.id=h,a.timescale=c,a.codec=d}o.id=Ml.text,n.sampleDuration=0,n.duration=a.duration=s}resetContiguity(){this.remainderData=null}static probe(t){return t=t.length>16384?t.subarray(0,16384):t,ot(t,["moof"]).length>0}demux(t,e){this.timeOffset=e;let i=t;const s=this.videoTrack,n=this.txtTrack;if(this.config.progressive){this.remainderData&&(i=fi(this.remainderData,t));const o=Np(i);this.remainderData=o.remainder,s.samples=o.valid||new Uint8Array}else s.samples=i;const a=this.extractID3Track(s,e);return n.samples=Hl(e,s),{videoTrack:s,audioTrack:this.audioTrack,id3Track:a,textTrack:this.txtTrack}}flush(){const t=this.timeOffset,e=this.videoTrack,i=this.txtTrack;e.samples=this.remainderData||new Uint8Array,this.remainderData=null;const s=this.extractID3Track(e,this.timeOffset);return i.samples=Hl(t,e),{videoTrack:e,audioTrack:Re(),id3Track:s,textTrack:Re()}}extractID3Track(t,e){const i=this.id3Track;if(t.samples.length){const s=ot(t.samples,["emsg"]);s&&s.forEach(n=>{const a=Hp(n);if(qg.test(a.schemeIdUri)){const o=q(a.presentationTime)?a.presentationTime/a.timeScale:e+a.presentationTimeDelta/a.timeScale;let l=a.eventDuration===4294967295?Number.POSITIVE_INFINITY:a.eventDuration/a.timeScale;l<=.001&&(l=Number.POSITIVE_INFINITY);const h=a.payload;i.samples.push({data:h,len:h.byteLength,dts:o,pts:o,type:ve.emsg,duration:l})}})}return i}demuxSampleAes(t,e,i){return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"))}destroy(){}}let mr=null;const Qg=[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],Zg=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],Jg=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],tm=[0,1,1,4];function kh(r,t,e,i,s){if(e+24>t.length)return;const n=Ih(t,e);if(n&&e+n.frameLength<=t.length){const a=n.samplesPerFrame*9e4/n.sampleRate,o=i+s*a,l={unit:t.subarray(e,e+n.frameLength),pts:o,dts:o};return r.config=[],r.channelCount=n.channelCount,r.samplerate=n.sampleRate,r.samples.push(l),{sample:l,length:n.frameLength,missing:0}}}function Ih(r,t){const e=r[t+1]>>3&3,i=r[t+1]>>1&3,s=r[t+2]>>4&15,n=r[t+2]>>2&3;if(e!==1&&s!==0&&s!==15&&n!==3){const a=r[t+2]>>1&1,o=r[t+3]>>6,l=e===3?3-i:i===3?3:4,h=Qg[l*14+s-1]*1e3,c=Zg[(e===3?0:e===2?1:2)*3+n],d=o===3?1:2,u=Jg[e][i],f=tm[i],p=u*8*f,g=Math.floor(u*h/c+a)*f;if(mr===null){const v=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);mr=v?parseInt(v[1]):0}return mr&&mr<=87&&i===2&&h>=224e3&&o===0&&(r[t+3]=r[t+3]|128),{sampleRate:c,channelCount:d,frameLength:g,samplesPerFrame:p}}}function zn(r,t){return r[t]===255&&(r[t+1]&224)===224&&(r[t+1]&6)!==0}function Ch(r,t){return t+1<r.length&&zn(r,t)}function em(r,t){return zn(r,t)&&4<=r.length-t}function im(r,t){if(t+1<r.length&&zn(r,t)){const e=Ih(r,t);let i=4;e!=null&&e.frameLength&&(i=e.frameLength);const s=t+i;return s===r.length||Ch(r,s)}return!1}class Dh{constructor(t){this.data=void 0,this.bytesAvailable=void 0,this.word=void 0,this.bitsAvailable=void 0,this.data=t,this.bytesAvailable=t.byteLength,this.word=0,this.bitsAvailable=0}loadWord(){const t=this.data,e=this.bytesAvailable,i=t.byteLength-e,s=new Uint8Array(4),n=Math.min(4,e);if(n===0)throw new Error("no bytes available");s.set(t.subarray(i,i+n)),this.word=new DataView(s.buffer).getUint32(0),this.bitsAvailable=n*8,this.bytesAvailable-=n}skipBits(t){let e;t=Math.min(t,this.bytesAvailable*8+this.bitsAvailable),this.bitsAvailable>t?(this.word<<=t,this.bitsAvailable-=t):(t-=this.bitsAvailable,e=t>>3,t-=e<<3,this.bytesAvailable-=e,this.loadWord(),this.word<<=t,this.bitsAvailable-=t)}readBits(t){let e=Math.min(this.bitsAvailable,t);const i=this.word>>>32-e;if(t>32&&_.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=e,this.bitsAvailable>0)this.word<<=e;else if(this.bytesAvailable>0)this.loadWord();else throw new Error("no bits available");return e=t-e,e>0&&this.bitsAvailable?i<<e|this.readBits(e):i}skipLZ(){let t;for(t=0;t<this.bitsAvailable;++t)if(this.word&2147483648>>>t)return this.word<<=t,this.bitsAvailable-=t,t;return this.loadWord(),t+this.skipLZ()}skipUEG(){this.skipBits(1+this.skipLZ())}skipEG(){this.skipBits(1+this.skipLZ())}readUEG(){const t=this.skipLZ();return this.readBits(t+1)-1}readEG(){const t=this.readUEG();return 1&t?1+t>>>1:-1*(t>>>1)}readBoolean(){return this.readBits(1)===1}readUByte(){return this.readBits(8)}readUShort(){return this.readBits(16)}readUInt(){return this.readBits(32)}skipScalingList(t){let e=8,i=8,s;for(let n=0;n<t;n++)i!==0&&(s=this.readEG(),i=(e+s+256)%256),e=i===0?e:i}readSPS(){let t=0,e=0,i=0,s=0,n,a,o;const l=this.readUByte.bind(this),h=this.readBits.bind(this),c=this.readUEG.bind(this),d=this.readBoolean.bind(this),u=this.skipBits.bind(this),f=this.skipEG.bind(this),p=this.skipUEG.bind(this),g=this.skipScalingList.bind(this);l();const v=l();if(h(5),u(3),l(),p(),v===100||v===110||v===122||v===244||v===44||v===83||v===86||v===118||v===128){const R=c();if(R===3&&u(1),p(),p(),u(1),d())for(a=R!==3?8:12,o=0;o<a;o++)d()&&(o<6?g(16):g(64))}p();const E=c();if(E===0)c();else if(E===1)for(u(1),f(),f(),n=c(),o=0;o<n;o++)f();p(),u(1);const A=c(),L=c(),y=h(1);y===0&&u(1),u(1),d()&&(t=c(),e=c(),i=c(),s=c());let S=[1,1];if(d()&&d())switch(l()){case 1:S=[1,1];break;case 2:S=[12,11];break;case 3:S=[10,11];break;case 4:S=[16,11];break;case 5:S=[40,33];break;case 6:S=[24,11];break;case 7:S=[20,11];break;case 8:S=[32,11];break;case 9:S=[80,33];break;case 10:S=[18,11];break;case 11:S=[15,11];break;case 12:S=[64,33];break;case 13:S=[160,99];break;case 14:S=[4,3];break;case 15:S=[3,2];break;case 16:S=[2,1];break;case 255:{S=[l()<<8|l(),l()<<8|l()];break}}return{width:Math.ceil((A+1)*16-t*2-e*2),height:(2-y)*(L+1)*16-(y?2:4)*(i+s),pixelRatio:S}}readSliceType(){return this.readUByte(),this.readUEG(),this.readUEG()}}class sm{constructor(t,e,i){this.keyData=void 0,this.decrypter=void 0,this.keyData=i,this.decrypter=new jn(e,{removePKCS7Padding:!1})}decryptBuffer(t){return this.decrypter.decrypt(t,this.keyData.key.buffer,this.keyData.iv.buffer)}decryptAacSample(t,e,i){const s=t[e].unit;if(s.length<=16)return;const n=s.subarray(16,s.length-s.length%16),a=n.buffer.slice(n.byteOffset,n.byteOffset+n.length);this.decryptBuffer(a).then(o=>{const l=new Uint8Array(o);s.set(l,16),this.decrypter.isSync()||this.decryptAacSamples(t,e+1,i)})}decryptAacSamples(t,e,i){for(;;e++){if(e>=t.length){i();return}if(!(t[e].unit.length<32)&&(this.decryptAacSample(t,e,i),!this.decrypter.isSync()))return}}getAvcEncryptedData(t){const e=Math.floor((t.length-48)/160)*16+16,i=new Int8Array(e);let s=0;for(let n=32;n<t.length-16;n+=160,s+=16)i.set(t.subarray(n,n+16),s);return i}getAvcDecryptedUnit(t,e){const i=new Uint8Array(e);let s=0;for(let n=32;n<t.length-16;n+=160,s+=16)t.set(i.subarray(s,s+16),n);return t}decryptAvcSample(t,e,i,s,n){const a=Vl(n.data),o=this.getAvcEncryptedData(a);this.decryptBuffer(o.buffer).then(l=>{n.data=this.getAvcDecryptedUnit(a,l),this.decrypter.isSync()||this.decryptAvcSamples(t,e,i+1,s)})}decryptAvcSamples(t,e,i,s){if(t instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;e++,i=0){if(e>=t.length){s();return}const n=t[e].units;for(;!(i>=n.length);i++){const a=n[i];if(!(a.data.length<=48||a.type!==1&&a.type!==5)&&(this.decryptAvcSample(t,e,i,s,a),!this.decrypter.isSync()))return}}}}const Vt=188;class je{constructor(t,e,i){this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.sampleAes=null,this.pmtParsed=!1,this.audioCodec=void 0,this.videoCodec=void 0,this._duration=0,this._pmtId=-1,this._avcTrack=void 0,this._audioTrack=void 0,this._id3Track=void 0,this._txtTrack=void 0,this.aacOverFlow=null,this.avcSample=null,this.remainderData=null,this.observer=t,this.config=e,this.typeSupported=i}static probe(t){const e=je.syncOffset(t);return e>0&&_.warn(`MPEG2-TS detected but first sync word found @ offset ${e}`),e!==-1}static syncOffset(t){const e=t.length;let i=Math.min(Vt*5,t.length-Vt)+1,s=0;for(;s<i;){let n=!1,a=-1,o=0;for(let l=s;l<e;l+=Vt)if(t[l]===71){if(o++,a===-1&&(a=l,a!==0&&(i=Math.min(a+Vt*99,t.length-Vt)+1)),n||(n=qn(t,l)===0),n&&o>1&&(a===0&&o>2||l+Vt>i))return a}else{if(o)return-1;break}s++}return-1}static createTrack(t,e){return{container:t==="video"||t==="audio"?"video/mp2t":void 0,type:t,id:Ml[t],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:t==="audio"?e:void 0}}resetInitSegment(t,e,i,s){this.pmtParsed=!1,this._pmtId=-1,this._avcTrack=je.createTrack("video"),this._audioTrack=je.createTrack("audio",s),this._id3Track=je.createTrack("id3"),this._txtTrack=je.createTrack("text"),this._audioTrack.segmentCodec="aac",this.aacOverFlow=null,this.avcSample=null,this.remainderData=null,this.audioCodec=e,this.videoCodec=i,this._duration=s}resetTimeStamp(){}resetContiguity(){const{_audioTrack:t,_avcTrack:e,_id3Track:i}=this;t&&(t.pesData=null),e&&(e.pesData=null),i&&(i.pesData=null),this.aacOverFlow=null,this.avcSample=null,this.remainderData=null}demux(t,e,i=!1,s=!1){i||(this.sampleAes=null);let n;const a=this._avcTrack,o=this._audioTrack,l=this._id3Track,h=this._txtTrack;let c=a.pid,d=a.pesData,u=o.pid,f=l.pid,p=o.pesData,g=l.pesData,v=null,E=this.pmtParsed,A=this._pmtId,L=t.length;if(this.remainderData&&(t=fi(this.remainderData,t),L=t.length,this.remainderData=null),L<Vt&&!s)return this.remainderData=t,{audioTrack:o,videoTrack:a,id3Track:l,textTrack:h};const y=Math.max(0,je.syncOffset(t));L-=(L-y)%Vt,L<t.byteLength&&!s&&(this.remainderData=new Uint8Array(t.buffer,L,t.buffer.byteLength-L));let S=0;for(let C=y;C<L;C+=Vt)if(t[C]===71){const M=!!(t[C+1]&64),D=qn(t,C),I=(t[C+3]&48)>>4;let G;if(I>1){if(G=C+5+t[C+4],G===C+Vt)continue}else G=C+4;switch(D){case c:M&&(d&&(n=Ci(d))&&this.parseAVCPES(a,h,n,!1),d={data:[],size:0}),d&&(d.data.push(t.subarray(G,C+Vt)),d.size+=C+Vt-G);break;case u:if(M){if(p&&(n=Ci(p)))switch(o.segmentCodec){case"aac":this.parseAACPES(o,n);break;case"mp3":this.parseMPEGPES(o,n);break}p={data:[],size:0}}p&&(p.data.push(t.subarray(G,C+Vt)),p.size+=C+Vt-G);break;case f:M&&(g&&(n=Ci(g))&&this.parseID3PES(l,n),g={data:[],size:0}),g&&(g.data.push(t.subarray(G,C+Vt)),g.size+=C+Vt-G);break;case 0:M&&(G+=t[G]+1),A=this._pmtId=rm(t,G);break;case A:{M&&(G+=t[G]+1);const F=nm(t,G,this.typeSupported,i);c=F.avc,c>0&&(a.pid=c),u=F.audio,u>0&&(o.pid=u,o.segmentCodec=F.segmentCodec),f=F.id3,f>0&&(l.pid=f),v!==null&&!E&&(_.warn(`MPEG-TS PMT found at ${C} after unknown PID '${v}'. Backtracking to sync byte @${y} to parse all TS packets.`),v=null,C=y-188),E=this.pmtParsed=!0;break}case 17:case 8191:break;default:v=D;break}}else S++;if(S>0){const C=new Error(`Found ${S} TS packet/s that do not start with 0x47`);this.observer.emit(m.ERROR,m.ERROR,{type:Q.MEDIA_ERROR,details:$.FRAG_PARSING_ERROR,fatal:!1,error:C,reason:C.message})}a.pesData=d,o.pesData=p,l.pesData=g;const R={audioTrack:o,videoTrack:a,id3Track:l,textTrack:h};return s&&this.extractRemainingSamples(R),R}flush(){const{remainderData:t}=this;this.remainderData=null;let e;return t?e=this.demux(t,-1,!1,!0):e={videoTrack:this._avcTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(e),this.sampleAes?this.decrypt(e,this.sampleAes):e}extractRemainingSamples(t){const{audioTrack:e,videoTrack:i,id3Track:s,textTrack:n}=t,a=i.pesData,o=e.pesData,l=s.pesData;let h;if(a&&(h=Ci(a))?(this.parseAVCPES(i,n,h,!0),i.pesData=null):i.pesData=a,o&&(h=Ci(o))){switch(e.segmentCodec){case"aac":this.parseAACPES(e,h);break;case"mp3":this.parseMPEGPES(e,h);break}e.pesData=null}else o!=null&&o.size&&_.log("last AAC PES packet truncated,might overlap between fragments"),e.pesData=o;l&&(h=Ci(l))?(this.parseID3PES(s,h),s.pesData=null):s.pesData=l}demuxSampleAes(t,e,i){const s=this.demux(t,i,!0,!this.config.progressive),n=this.sampleAes=new sm(this.observer,this.config,e);return this.decrypt(s,n)}decrypt(t,e){return new Promise(i=>{const{audioTrack:s,videoTrack:n}=t;s.samples&&s.segmentCodec==="aac"?e.decryptAacSamples(s.samples,0,()=>{n.samples?e.decryptAvcSamples(n.samples,0,0,()=>{i(t)}):i(t)}):n.samples&&e.decryptAvcSamples(n.samples,0,0,()=>{i(t)})})}destroy(){this._duration=0}parseAVCPES(t,e,i,s){const n=this.parseAVCNALu(t,i.data);let a=this.avcSample,o,l=!1;i.data=null,a&&n.length&&!t.audFound&&(ws(a,t),a=this.avcSample=vr(!1,i.pts,i.dts,"")),n.forEach(h=>{var c;switch(h.type){case 1:{let u=!1;o=!0;const f=h.data;if(l&&f.length>4){const p=new Dh(f).readSliceType();(p===2||p===4||p===7||p===9)&&(u=!0)}if(u){var d;(d=a)!=null&&d.frame&&!a.key&&(ws(a,t),a=this.avcSample=null)}a||(a=this.avcSample=vr(!0,i.pts,i.dts,"")),a.frame=!0,a.key=u;break}case 5:o=!0,(c=a)!=null&&c.frame&&!a.key&&(ws(a,t),a=this.avcSample=null),a||(a=this.avcSample=vr(!0,i.pts,i.dts,"")),a.key=!0,a.frame=!0;break;case 6:{o=!0,Gl(h.data,1,i.pts,e.samples);break}case 7:if(o=!0,l=!0,!t.sps){const u=h.data,f=new Dh(u).readSPS();t.width=f.width,t.height=f.height,t.pixelRatio=f.pixelRatio,t.sps=[u],t.duration=this._duration;const p=u.subarray(1,4);let g="avc1.";for(let v=0;v<3;v++){let E=p[v].toString(16);E.length<2&&(E="0"+E),g+=E}t.codec=g}break;case 8:o=!0,t.pps||(t.pps=[h.data]);break;case 9:o=!1,t.audFound=!0,a&&ws(a,t),a=this.avcSample=vr(!1,i.pts,i.dts,"");break;case 12:o=!0;break;default:o=!1,a&&(a.debug+="unknown NAL "+h.type+" ");break}a&&o&&a.units.push(h)}),s&&a&&(ws(a,t),this.avcSample=null)}getLastNalUnit(t){var e;let i=this.avcSample,s;if((!i||i.units.length===0)&&(i=t[t.length-1]),(e=i)!=null&&e.units){const n=i.units;s=n[n.length-1]}return s}parseAVCNALu(t,e){const i=e.byteLength;let s=t.naluState||0;const n=s,a=[];let o=0,l,h,c,d=-1,u=0;for(s===-1&&(d=0,u=e[0]&31,s=0,o=1);o<i;){if(l=e[o++],!s){s=l?0:1;continue}if(s===1){s=l?0:2;continue}if(!l)s=3;else if(l===1){if(d>=0){const f={data:e.subarray(d,o-s-1),type:u};a.push(f)}else{const f=this.getLastNalUnit(t.samples);if(f&&(n&&o<=4-n&&f.state&&(f.data=f.data.subarray(0,f.data.byteLength-n)),h=o-s-1,h>0)){const p=new Uint8Array(f.data.byteLength+h);p.set(f.data,0),p.set(e.subarray(0,h),f.data.byteLength),f.data=p,f.state=0}}o<i?(c=e[o]&31,d=o,u=c,s=0):s=-1}else s=0}if(d>=0&&s>=0){const f={data:e.subarray(d,i),type:u,state:s};a.push(f)}if(a.length===0){const f=this.getLastNalUnit(t.samples);if(f){const p=new Uint8Array(f.data.byteLength+e.byteLength);p.set(f.data,0),p.set(e,f.data.byteLength),f.data=p}}return t.naluState=s,a}parseAACPES(t,e){let i=0;const s=this.aacOverFlow;let n=e.data;if(s){this.aacOverFlow=null;const d=s.missing,u=s.sample.unit.byteLength;if(d===-1){const f=new Uint8Array(u+n.byteLength);f.set(s.sample.unit,0),f.set(n,u),n=f}else{const f=u-d;s.sample.unit.set(n.subarray(0,d),f),t.samples.push(s.sample),i=s.missing}}let a,o;for(a=i,o=n.length;a<o-1&&!gr(n,a);a++);if(a!==i){let d;const u=a<o-1;u?d=`AAC PES did not start with ADTS header,offset:${a}`:d="No ADTS header found in AAC PES";const f=new Error(d);if(_.warn(`parsing error: ${d}`),this.observer.emit(m.ERROR,m.ERROR,{type:Q.MEDIA_ERROR,details:$.FRAG_PARSING_ERROR,fatal:!1,levelRetry:u,error:f,reason:d}),!u)return}Lh(t,this.observer,n,a,this.audioCodec);let l;if(e.pts!==void 0)l=e.pts;else if(s){const d=Rh(t.samplerate);l=s.sample.pts+d}else{_.warn("[tsdemuxer]: AAC PES unknown PTS");return}let h=0,c;for(;a<o;)if(c=_h(t,n,a,l,h),a+=c.length,c.missing){this.aacOverFlow=c;break}else for(h++;a<o-1&&!gr(n,a);a++);}parseMPEGPES(t,e){const i=e.data,s=i.length;let n=0,a=0;const o=e.pts;if(o===void 0){_.warn("[tsdemuxer]: MPEG PES unknown PTS");return}for(;a<s;)if(Ch(i,a)){const l=kh(t,i,a,o,n);if(l)a+=l.length,n++;else break}else a++}parseID3PES(t,e){if(e.pts===void 0){_.warn("[tsdemuxer]: ID3 PES unknown PTS");return}const i=Dt({},e,{type:this._avcTrack?ve.emsg:ve.audioId3,duration:Number.POSITIVE_INFINITY});t.samples.push(i)}}function vr(r,t,e,i){return{key:r,frame:!1,pts:t,dts:e,units:[],debug:i,length:0}}function qn(r,t){return((r[t+1]&31)<<8)+r[t+2]}function rm(r,t){return(r[t+10]&31)<<8|r[t+11]}function nm(r,t,e,i){const s={audio:-1,avc:-1,id3:-1,segmentCodec:"aac"},n=(r[t+1]&15)<<8|r[t+2],a=t+3+n-4,o=(r[t+10]&15)<<8|r[t+11];for(t+=12+o;t<a;){const l=qn(r,t);switch(r[t]){case 207:if(!i){_.log("ADTS AAC with AES-128-CBC frame encryption found in unencrypted stream");break}case 15:s.audio===-1&&(s.audio=l);break;case 21:s.id3===-1&&(s.id3=l);break;case 219:if(!i){_.log("H.264 with AES-128-CBC slice encryption found in unencrypted stream");break}case 27:s.avc===-1&&(s.avc=l);break;case 3:case 4:e.mpeg!==!0&&e.mp3!==!0?_.log("MPEG audio found, not supported in this browser"):s.audio===-1&&(s.audio=l,s.segmentCodec="mp3");break;case 36:_.warn("Unsupported HEVC stream type found");break}t+=((r[t+3]&15)<<8|r[t+4])+5}return s}function Ci(r){let t=0,e,i,s,n,a;const o=r.data;if(!r||r.size===0)return null;for(;o[0].length<19&&o.length>1;){const l=new Uint8Array(o[0].length+o[1].length);l.set(o[0]),l.set(o[1],o[0].length),o[0]=l,o.splice(1,1)}if(e=o[0],(e[0]<<16)+(e[1]<<8)+e[2]===1){if(i=(e[4]<<8)+e[5],i&&i>r.size-6)return null;const l=e[7];l&192&&(n=(e[9]&14)*536870912+(e[10]&255)*4194304+(e[11]&254)*16384+(e[12]&255)*128+(e[13]&254)/2,l&64?(a=(e[14]&14)*536870912+(e[15]&255)*4194304+(e[16]&254)*16384+(e[17]&255)*128+(e[18]&254)/2,n-a>54e5&&(_.warn(`${Math.round((n-a)/9e4)}s delta between PTS and DTS, align them`),n=a)):a=n),s=e[8];let h=s+9;if(r.size<=h)return null;r.size-=h;const c=new Uint8Array(r.size);for(let d=0,u=o.length;d<u;d++){e=o[d];let f=e.byteLength;if(h)if(h>f){h-=f;continue}else e=e.subarray(h),f-=h,h=0;c.set(e,t),t+=f}return i&&(i-=s+3),{data:c,pts:n,dts:a,len:i}}return null}function ws(r,t){if(r.units.length&&r.frame){if(r.pts===void 0){const e=t.samples,i=e.length;if(i){const s=e[i-1];r.pts=s.pts,r.dts=s.dts}else{t.dropped++;return}}t.samples.push(r)}r.debug.length&&_.log(r.pts+"/"+r.dts+":"+r.debug)}class am extends Ah{resetInitSegment(t,e,i,s){super.resetInitSegment(t,e,i,s),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:e,duration:s,inputTimeScale:9e4,dropped:0}}static probe(t){if(!t)return!1;let e=(rr(t,0)||[]).length;for(let i=t.length;e<i;e++)if(im(t,e))return _.log("MPEG Audio sync word found !"),!0;return!1}canParse(t,e){return em(t,e)}appendFrame(t,e,i){if(this.basePTS!==null)return kh(t,e,i,this.basePTS,this.frameIndex)}}class xh{static getSilentFrame(t,e){switch(t){case"mp4a.40.2":if(e===1)return new Uint8Array([0,200,0,128,35,128]);if(e===2)return new Uint8Array([33,0,73,144,2,25,0,35,128]);if(e===3)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,142]);if(e===4)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,128,44,128,8,2,56]);if(e===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(e===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(e===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(e===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(e===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}}}const We=Math.pow(2,32)-1;class x{static init(){x.types={avc1:[],avcC:[],btrt:[],dinf:[],dref:[],esds:[],ftyp:[],hdlr:[],mdat:[],mdhd:[],mdia:[],mfhd:[],minf:[],moof:[],moov:[],mp4a:[],".mp3":[],mvex:[],mvhd:[],pasp:[],sdtp:[],stbl:[],stco:[],stsc:[],stsd:[],stsz:[],stts:[],tfdt:[],tfhd:[],traf:[],trak:[],trun:[],trex:[],tkhd:[],vmhd:[],smhd:[]};let t;for(t in x.types)x.types.hasOwnProperty(t)&&(x.types[t]=[t.charCodeAt(0),t.charCodeAt(1),t.charCodeAt(2),t.charCodeAt(3)]);const e=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]);x.HDLR_TYPES={video:e,audio:i};const s=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]);x.STTS=x.STSC=x.STCO=n,x.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),x.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),x.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),x.STSD=new Uint8Array([0,0,0,0,0,0,0,1]);const a=new Uint8Array([105,115,111,109]),o=new Uint8Array([97,118,99,49]),l=new Uint8Array([0,0,0,1]);x.FTYP=x.box(x.types.ftyp,a,l,a,o),x.DINF=x.box(x.types.dinf,x.box(x.types.dref,s))}static box(t,...e){let i=8,s=e.length;const n=s;for(;s--;)i+=e[s].byteLength;const 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(t,4),s=0,i=8;s<n;s++)a.set(e[s],i),i+=e[s].byteLength;return a}static hdlr(t){return x.box(x.types.hdlr,x.HDLR_TYPES[t])}static mdat(t){return x.box(x.types.mdat,t)}static mdhd(t,e){e*=t;const i=Math.floor(e/(We+1)),s=Math.floor(e%(We+1));return x.box(x.types.mdhd,new Uint8Array([1,0,0,0,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,i>>24,i>>16&255,i>>8&255,i&255,s>>24,s>>16&255,s>>8&255,s&255,85,196,0,0]))}static mdia(t){return x.box(x.types.mdia,x.mdhd(t.timescale,t.duration),x.hdlr(t.type),x.minf(t))}static mfhd(t){return x.box(x.types.mfhd,new Uint8Array([0,0,0,0,t>>24,t>>16&255,t>>8&255,t&255]))}static minf(t){return t.type==="audio"?x.box(x.types.minf,x.box(x.types.smhd,x.SMHD),x.DINF,x.stbl(t)):x.box(x.types.minf,x.box(x.types.vmhd,x.VMHD),x.DINF,x.stbl(t))}static moof(t,e,i){return x.box(x.types.moof,x.mfhd(t),x.traf(i,e))}static moov(t){let e=t.length;const i=[];for(;e--;)i[e]=x.trak(t[e]);return x.box.apply(null,[x.types.moov,x.mvhd(t[0].timescale,t[0].duration)].concat(i).concat(x.mvex(t)))}static mvex(t){let e=t.length;const i=[];for(;e--;)i[e]=x.trex(t[e]);return x.box.apply(null,[x.types.mvex,...i])}static mvhd(t,e){e*=t;const i=Math.floor(e/(We+1)),s=Math.floor(e%(We+1)),n=new Uint8Array([1,0,0,0,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,i>>24,i>>16&255,i>>8&255,i&255,s>>24,s>>16&255,s>>8&255,s&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 x.box(x.types.mvhd,n)}static sdtp(t){const e=t.samples||[],i=new Uint8Array(4+e.length);let s,n;for(s=0;s<e.length;s++)n=e[s].flags,i[s+4]=n.dependsOn<<4|n.isDependedOn<<2|n.hasRedundancy;return x.box(x.types.sdtp,i)}static stbl(t){return x.box(x.types.stbl,x.stsd(t),x.box(x.types.stts,x.STTS),x.box(x.types.stsc,x.STSC),x.box(x.types.stsz,x.STSZ),x.box(x.types.stco,x.STCO))}static avc1(t){let e=[],i=[],s,n,a;for(s=0;s<t.sps.length;s++)n=t.sps[s],a=n.byteLength,e.push(a>>>8&255),e.push(a&255),e=e.concat(Array.prototype.slice.call(n));for(s=0;s<t.pps.length;s++)n=t.pps[s],a=n.byteLength,i.push(a>>>8&255),i.push(a&255),i=i.concat(Array.prototype.slice.call(n));const o=x.box(x.types.avcC,new Uint8Array([1,e[3],e[4],e[5],255,224|t.sps.length].concat(e).concat([t.pps.length]).concat(i))),l=t.width,h=t.height,c=t.pixelRatio[0],d=t.pixelRatio[1];return x.box(x.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,h>>8&255,h&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,x.box(x.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),x.box(x.types.pasp,new Uint8Array([c>>24,c>>16&255,c>>8&255,c&255,d>>24,d>>16&255,d>>8&255,d&255])))}static esds(t){const e=t.config.length;return new Uint8Array([0,0,0,0,3,23+e,0,1,0,4,15+e,64,21,0,0,0,0,0,0,0,0,0,0,0,5].concat([e]).concat(t.config).concat([6,1,2]))}static mp4a(t){const e=t.samplerate;return x.box(x.types.mp4a,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,t.channelCount,0,16,0,0,0,0,e>>8&255,e&255,0,0]),x.box(x.types.esds,x.esds(t)))}static mp3(t){const e=t.samplerate;return x.box(x.types[".mp3"],new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,t.channelCount,0,16,0,0,0,0,e>>8&255,e&255,0,0]))}static stsd(t){return t.type==="audio"?t.segmentCodec==="mp3"&&t.codec==="mp3"?x.box(x.types.stsd,x.STSD,x.mp3(t)):x.box(x.types.stsd,x.STSD,x.mp4a(t)):x.box(x.types.stsd,x.STSD,x.avc1(t))}static tkhd(t){const e=t.id,i=t.duration*t.timescale,s=t.width,n=t.height,a=Math.floor(i/(We+1)),o=Math.floor(i%(We+1));return x.box(x.types.tkhd,new Uint8Array([1,0,0,7,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,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,s>>8&255,s&255,0,0,n>>8&255,n&255,0,0]))}static traf(t,e){const i=x.sdtp(t),s=t.id,n=Math.floor(e/(We+1)),a=Math.floor(e%(We+1));return x.box(x.types.traf,x.box(x.types.tfhd,new Uint8Array([0,0,0,0,s>>24,s>>16&255,s>>8&255,s&255])),x.box(x.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])),x.trun(t,i.length+16+20+8+16+8+8),i)}static trak(t){return t.duration=t.duration||4294967295,x.box(x.types.trak,x.tkhd(t),x.mdia(t))}static trex(t){const e=t.id;return x.box(x.types.trex,new Uint8Array([0,0,0,0,e>>24,e>>16&255,e>>8&255,e&255,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))}static trun(t,e){const i=t.samples||[],s=i.length,n=12+16*s,a=new Uint8Array(n);let o,l,h,c,d,u;for(e+=8+n,a.set([t.type==="video"?1:0,0,15,1,s>>>24&255,s>>>16&255,s>>>8&255,s&255,e>>>24&255,e>>>16&255,e>>>8&255,e&255],0),o=0;o<s;o++)l=i[o],h=l.duration,c=l.size,d=l.flags,u=l.cts,a.set([h>>>24&255,h>>>16&255,h>>>8&255,h&255,c>>>24&255,c>>>16&255,c>>>8&255,c&255,d.isLeading<<2|d.dependsOn,d.isDependedOn<<6|d.hasRedundancy<<4|d.paddingValue<<1|d.isNonSync,d.degradPrio&61440,d.degradPrio&15,u>>>24&255,u>>>16&255,u>>>8&255,u&255],12+16*o);return x.box(x.types.trun,a)}static initSegment(t){x.types||x.init();const e=x.moov(t),i=new Uint8Array(x.FTYP.byteLength+e.byteLength);return i.set(x.FTYP),i.set(e,x.FTYP.byteLength),i}}x.types=void 0,x.HDLR_TYPES=void 0,x.STTS=void 0,x.STSC=void 0,x.STCO=void 0,x.STSZ=void 0,x.VMHD=void 0,x.SMHD=void 0,x.STSD=void 0,x.FTYP=void 0,x.DINF=void 0;const Ph=9e4;function Xn(r,t,e=1,i=!1){const s=r*t*e;return i?Math.round(s):s}function om(r,t,e=1,i=!1){return Xn(r,t,1/e,i)}function Ss(r,t=!1){return Xn(r,1e3,1/Ph,t)}function lm(r,t=1){return Xn(r,Ph,1/t)}const hm=10*1e3,Oh=1024,cm=1152;let yr=null,Qn=null;class Zn{constructor(t,e,i,s=""){if(this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.ISGenerated=!1,this._initPTS=null,this._initDTS=null,this.nextAvcDts=null,this.nextAudioPts=null,this.videoSampleDuration=null,this.isAudioContiguous=!1,this.isVideoContiguous=!1,this.observer=t,this.config=e,this.typeSupported=i,this.ISGenerated=!1,yr===null){const n=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);yr=n?parseInt(n[1]):0}if(Qn===null){const n=navigator.userAgent.match(/Safari\/(\d+)/i);Qn=n?parseInt(n[1]):0}}destroy(){}resetTimeStamp(t){_.log("[mp4-remuxer]: initPTS & initDTS reset"),this._initPTS=this._initDTS=t}resetNextTimestamp(){_.log("[mp4-remuxer]: reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1}resetInitSegment(){_.log("[mp4-remuxer]: ISGenerated flag reset"),this.ISGenerated=!1}getVideoStartPts(t){let e=!1;const i=t.reduce((s,n)=>{const a=n.pts-s;return a<-4294967296?(e=!0,ue(s,n.pts)):a>0?s:n.pts},t[0].pts);return e&&_.debug("PTS rollover detected"),i}remux(t,e,i,s,n,a,o,l){let h,c,d,u,f,p,g=n,v=n;const E=t.pid>-1,A=e.pid>-1,L=e.samples.length,y=t.samples.length>0,S=o&&L>0||L>1;if((!E||y)&&(!A||S)||this.ISGenerated||o){this.ISGenerated||(d=this.generateIS(t,e,n,a));const R=this.isVideoContiguous;let C=-1,M;if(S&&(C=dm(e.samples),!R&&this.config.forceKeyFrameOnDiscontinuity))if(p=!0,C>0){_.warn(`[mp4-remuxer]: Dropped ${C} out of ${L} video samples due to a missing keyframe`);const D=this.getVideoStartPts(e.samples);e.samples=e.samples.slice(C),e.dropped+=C,v+=(e.samples[0].pts-D)/e.inputTimeScale,M=v}else C===-1&&(_.warn(`[mp4-remuxer]: No keyframe found out of ${L} video samples`),p=!1);if(this.ISGenerated){if(y&&S){const D=this.getVideoStartPts(e.samples),I=(ue(t.samples[0].pts,D)-D)/e.inputTimeScale;g+=Math.max(0,I),v+=Math.max(0,-I)}if(y){if(t.samplerate||(_.warn("[mp4-remuxer]: regenerate InitSegment as audio detected"),d=this.generateIS(t,e,n,a)),c=this.remuxAudio(t,g,this.isAudioContiguous,a,A||S||l===Z.AUDIO?v:void 0),S){const D=c?c.endPTS-c.startPTS:0;e.inputTimeScale||(_.warn("[mp4-remuxer]: regenerate InitSegment as video detected"),d=this.generateIS(t,e,n,a)),h=this.remuxVideo(e,v,R,D)}}else S&&(h=this.remuxVideo(e,v,R,0));h&&(h.firstKeyFrame=C,h.independent=C!==-1,h.firstKeyFramePTS=M)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(i.samples.length&&(f=$h(i,n,this._initPTS,this._initDTS)),s.samples.length&&(u=Mh(s,n,this._initPTS))),{audio:c,video:h,initSegment:d,independent:p,text:u,id3:f}}generateIS(t,e,i,s){const n=t.samples,a=e.samples,o=this.typeSupported,l={},h=this._initPTS;let c=!h||s,d="audio/mp4",u,f,p;if(c&&(u=f=1/0),t.config&&n.length){switch(t.timescale=t.samplerate,t.segmentCodec){case"mp3":o.mpeg?(d="audio/mpeg",t.codec=""):o.mp3&&(t.codec="mp3");break}l.audio={id:"audio",container:d,codec:t.codec,initSegment:t.segmentCodec==="mp3"&&o.mpeg?new Uint8Array(0):x.initSegment([t]),metadata:{channelCount:t.channelCount}},c&&(p=t.inputTimeScale,!h||p!==h.timescale?u=f=n[0].pts-Math.round(p*i):c=!1)}if(e.sps&&e.pps&&a.length&&(e.timescale=e.inputTimeScale,l.video={id:"main",container:"video/mp4",codec:e.codec,initSegment:x.initSegment([e]),metadata:{width:e.width,height:e.height}},c))if(p=e.inputTimeScale,!h||p!==h.timescale){const g=this.getVideoStartPts(a),v=Math.round(p*i);f=Math.min(f,ue(a[0].dts,g)-v),u=Math.min(u,g-v)}else c=!1;if(Object.keys(l).length)return this.ISGenerated=!0,c?(this._initPTS={baseTime:u,timescale:p},this._initDTS={baseTime:f,timescale:p}):u=p=void 0,{tracks:l,initPTS:u,timescale:p}}remuxVideo(t,e,i,s){const n=t.inputTimeScale,a=t.samples,o=[],l=a.length,h=this._initPTS;let c=this.nextAvcDts,d=8,u=this.videoSampleDuration,f,p,g=Number.POSITIVE_INFINITY,v=Number.NEGATIVE_INFINITY,E=!1;if(!i||c===null){const b=e*n,T=a[0].pts-ue(a[0].dts,a[0].pts);c=b-T}const A=h.baseTime*n/h.timescale;for(let b=0;b<l;b++){const T=a[b];T.pts=ue(T.pts-A,c),T.dts=ue(T.dts-A,c),T.dts<a[b>0?b-1:b].dts&&(E=!0)}E&&a.sort(function(b,T){const k=b.dts-T.dts,N=b.pts-T.pts;return k||N}),f=a[0].dts,p=a[a.length-1].dts;const L=p-f,y=L?Math.round(L/(l-1)):u||t.inputTimeScale/30;if(i){const b=f-c,T=b>y,k=b<-1;if((T||k)&&(T?_.warn(`AVC: ${Ss(b,!0)} ms (${b}dts) hole between fragments detected, filling it`):_.warn(`AVC: ${Ss(-b,!0)} ms (${b}dts) overlapping between fragments detected`),!k||c>=a[0].pts)){f=c;const N=a[0].pts-b;a[0].dts=f,a[0].pts=N,_.log(`Video: First PTS/DTS adjusted: ${Ss(N,!0)}/${Ss(f,!0)}, delta: ${Ss(b,!0)} ms`)}}f=Math.max(0,f);let S=0,R=0;for(let b=0;b<l;b++){const T=a[b],k=T.units,N=k.length;let U=0;for(let K=0;K<N;K++)U+=k[K].data.length;R+=U,S+=N,T.length=U,T.dts=Math.max(T.dts,f),g=Math.min(T.pts,g),v=Math.max(T.pts,v)}p=a[l-1].dts;const C=R+4*S+8;let M;try{M=new Uint8Array(C)}catch(b){this.observer.emit(m.ERROR,m.ERROR,{type:Q.MUX_ERROR,details:$.REMUX_ALLOC_ERROR,fatal:!1,error:b,bytes:C,reason:`fail allocating video mdat ${C}`});return}const D=new DataView(M.buffer);D.setUint32(0,C),M.set(x.types.mdat,4);let I=!1,G=Number.POSITIVE_INFINITY,F=Number.POSITIVE_INFINITY,V=Number.NEGATIVE_INFINITY,z=Number.NEGATIVE_INFINITY;for(let b=0;b<l;b++){const T=a[b],k=T.units;let N=0;for(let W=0,X=k.length;W<X;W++){const lt=k[W],rt=lt.data,at=lt.data.byteLength;D.setUint32(d,at),d+=4,M.set(rt,d),d+=at,N+=4+at}let U;if(b<l-1)u=a[b+1].dts-T.dts,U=a[b+1].pts-T.pts;else{const W=this.config,X=b>0?T.dts-a[b-1].dts:y;if(U=b>0?T.pts-a[b-1].pts:y,W.stretchShortVideoTrack&&this.nextAudioPts!==null){const lt=Math.floor(W.maxBufferHole*n),rt=(s?g+s*n:this.nextAudioPts)-T.pts;rt>lt?(u=rt-X,u<0?u=X:I=!0,_.log(`[mp4-remuxer]: It is approximately ${rt/90} ms to the next segment; using duration ${u/90} ms for the last video frame.`)):u=X}else u=X}const K=Math.round(T.pts-T.dts);G=Math.min(G,u),V=Math.max(V,u),F=Math.min(F,U),z=Math.max(z,U),o.push(new Fh(T.key,u,N,K))}if(o.length){if(yr){if(yr<70){const b=o[0].flags;b.dependsOn=2,b.isNonSync=0}}else if(Qn&&z-F<V-G&&y/V<.025&&o[0].cts===0){_.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");let b=f;for(let T=0,k=o.length;T<k;T++){const N=b+o[T].duration,U=b+o[T].cts;if(T<k-1){const K=N+o[T+1].cts;o[T].duration=K-U}else o[T].duration=T?o[T-1].duration:y;o[T].cts=0,b=N}}}u=I||!u?y:u,this.nextAvcDts=c=p+u,this.videoSampleDuration=u,this.isVideoContiguous=!0;const w=x.moof(t.sequenceNumber++,f,Dt({},t,{samples:o})),P="video",H={data1:w,data2:M,startPTS:g/n,endPTS:(v+u)/n,startDTS:f/n,endDTS:c/n,type:P,hasAudio:!1,hasVideo:!0,nb:o.length,dropped:t.dropped};return t.samples=[],t.dropped=0,H}remuxAudio(t,e,i,s,n){const a=t.inputTimeScale,o=t.samplerate?t.samplerate:a,l=a/o,h=t.segmentCodec==="aac"?Oh:cm,c=h*l,d=this._initPTS,u=t.segmentCodec==="mp3"&&this.typeSupported.mpeg,f=[],p=n!==void 0;let g=t.samples,v=u?0:8,E=this.nextAudioPts||-1;const A=e*a,L=d.baseTime*a/d.timescale;if(this.isAudioContiguous=i=i||g.length&&E>0&&(s&&Math.abs(A-E)<9e3||Math.abs(ue(g[0].pts-L,A)-E)<20*c),g.forEach(function(w){w.pts=ue(w.pts-L,A)}),!i||E<0){if(g=g.filter(w=>w.pts>=0),!g.length)return;n===0?E=0:s&&!p?E=Math.max(0,A):E=g[0].pts}if(t.segmentCodec==="aac"){const w=this.config.maxAudioFramesDrift;for(let P=0,H=E;P<g.length;P++){const b=g[P],T=b.pts,k=T-H,N=Math.abs(1e3*k/a);if(k<=-w*c&&p)P===0&&(_.warn(`Audio frame @ ${(T/a).toFixed(3)}s overlaps nextAudioPts by ${Math.round(1e3*k/a)} ms.`),this.nextAudioPts=E=H=T);else if(k>=w*c&&N<hm&&p){let U=Math.round(k/c);H=T-U*c,H<0&&(U--,H+=c),P===0&&(this.nextAudioPts=E=H),_.warn(`[mp4-remuxer]: Injecting ${U} audio frame @ ${(H/a).toFixed(3)}s due to ${Math.round(1e3*k/a)} ms gap.`);for(let K=0;K<U;K++){const W=Math.max(H,0);let X=xh.getSilentFrame(t.manifestCodec||t.codec,t.channelCount);X||(_.log("[mp4-remuxer]: Unable to get silent frame for given audio codec; duplicating last frame instead."),X=b.unit.subarray()),g.splice(P,0,{unit:X,pts:W}),H+=c,P++}}b.pts=H,H+=c}}let y=null,S=null,R,C=0,M=g.length;for(;M--;)C+=g[M].unit.byteLength;for(let w=0,P=g.length;w<P;w++){const H=g[w],b=H.unit;let T=H.pts;if(S!==null){const N=f[w-1];N.duration=Math.round((T-S)/l)}else if(i&&t.segmentCodec==="aac"&&(T=E),y=T,C>0){C+=v;try{R=new Uint8Array(C)}catch(N){this.observer.emit(m.ERROR,m.ERROR,{type:Q.MUX_ERROR,details:$.REMUX_ALLOC_ERROR,fatal:!1,error:N,bytes:C,reason:`fail allocating audio mdat ${C}`});return}u||(new DataView(R.buffer).setUint32(0,C),R.set(x.types.mdat,4))}else return;R.set(b,v);const k=b.byteLength;v+=k,f.push(new Fh(!0,h,k,0)),S=T}const D=f.length;if(!D)return;const I=f[f.length-1];this.nextAudioPts=E=S+l*I.duration;const G=u?new Uint8Array(0):x.moof(t.sequenceNumber++,y/l,Dt({},t,{samples:f}));t.samples=[];const F=y/a,V=E/a,z={data1:G,data2:R,startPTS:F,endPTS:V,startDTS:F,endDTS:V,type:"audio",hasAudio:!0,hasVideo:!1,nb:D};return this.isAudioContiguous=!0,z}remuxEmptyAudio(t,e,i,s){const n=t.inputTimeScale,a=t.samplerate?t.samplerate:n,o=n/a,l=this.nextAudioPts,h=this._initDTS,c=h.baseTime*9e4/h.timescale,d=(l!==null?l:s.startDTS*n)+c,u=s.endDTS*n+c,f=o*Oh,p=Math.ceil((u-d)/f),g=xh.getSilentFrame(t.manifestCodec||t.codec,t.channelCount);if(_.warn("[mp4-remuxer]: remux empty Audio"),!g){_.trace("[mp4-remuxer]: Unable to remuxEmptyAudio since we were unable to get a silent frame for given audio codec");return}const v=[];for(let E=0;E<p;E++){const A=d+E*f;v.push({unit:g,pts:A,dts:A})}return t.samples=v,this.remuxAudio(t,e,i,!1)}}function ue(r,t){let e;if(t===null)return r;for(t<r?e=-8589934592:e=8589934592;Math.abs(r-t)>4294967296;)r+=e;return r}function dm(r){for(let t=0;t<r.length;t++)if(r[t].key)return t;return-1}function $h(r,t,e,i){const s=r.samples.length;if(!s)return;const n=r.inputTimeScale;for(let o=0;o<s;o++){const l=r.samples[o];l.pts=ue(l.pts-e.baseTime*n/e.timescale,t*n)/n,l.dts=ue(l.dts-i.baseTime*n/i.timescale,t*n)/n}const a=r.samples;return r.samples=[],{samples:a}}function Mh(r,t,e){const i=r.samples.length;if(!i)return;const s=r.inputTimeScale;for(let a=0;a<i;a++){const o=r.samples[a];o.pts=ue(o.pts-e.baseTime*s/e.timescale,t*s)/s}r.samples.sort((a,o)=>a.pts-o.pts);const n=r.samples;return r.samples=[],{samples:n}}class Fh{constructor(t,e,i,s){this.size=void 0,this.duration=void 0,this.cts=void 0,this.flags=void 0,this.duration=e,this.size=i,this.cts=s,this.flags=new um(t)}}class um{constructor(t){this.isLeading=0,this.isDependedOn=0,this.hasRedundancy=0,this.degradPrio=0,this.dependsOn=1,this.isNonSync=1,this.dependsOn=t?2:1,this.isNonSync=t?0:1}}class fm{constructor(){this.emitInitSegment=!1,this.audioCodec=void 0,this.videoCodec=void 0,this.initData=void 0,this.initPTS=null,this.initTracks=void 0,this.lastEndTime=null}destroy(){}resetTimeStamp(t){this.initPTS=t,this.lastEndTime=null}resetNextTimestamp(){this.lastEndTime=null}resetInitSegment(t,e,i,s){this.audioCodec=e,this.videoCodec=i,this.generateInitSegment(Pp(t,s)),this.emitInitSegment=!0}generateInitSegment(t){let{audioCodec:e,videoCodec:i}=this;if(!(t!=null&&t.byteLength)){this.initTracks=void 0,this.initData=void 0;return}const s=this.initData=Ul(t);e||(e=Nh(s.audio,mt.AUDIO)),i||(i=Nh(s.video,mt.VIDEO));const n={};s.audio&&s.video?n.audiovideo={container:"video/mp4",codec:e+","+i,initSegment:t,id:"main"}:s.audio?n.audio={container:"audio/mp4",codec:e,initSegment:t,id:"audio"}:s.video?n.video={container:"video/mp4",codec:i,initSegment:t,id:"main"}:_.warn("[passthrough-remuxer.ts]: initSegment does not contain moov or trak boxes."),this.initTracks=n}remux(t,e,i,s,n,a){var o,l;let{initPTS:h,lastEndTime:c}=this;const d={audio:void 0,video:void 0,text:s,id3:i,initSegment:void 0};q(c)||(c=this.lastEndTime=n||0);const u=e.samples;if(!(u!=null&&u.length))return d;const f={initPTS:void 0,timescale:1};let p=this.initData;if((o=p)!=null&&o.length||(this.generateInitSegment(u),p=this.initData),!((l=p)!=null&&l.length))return _.warn("[passthrough-remuxer.ts]: Failed to generate initSegment."),d;this.emitInitSegment&&(f.tracks=this.initTracks,this.emitInitSegment=!1);const g=$p(u,p),v=Op(p,u),E=v===null?n:v;(pm(h,E,n,g)||f.timescale!==h.timescale&&a)&&(f.initPTS=E-n,h&&h.timescale===1&&_.warn(`Adjusting initPTS by ${f.initPTS-h.baseTime}`),this.initPTS=h={baseTime:f.initPTS,timescale:1});const A=t?E-h.baseTime/h.timescale:c,L=A+g;Fp(p,u,h.baseTime/h.timescale),g>0?this.lastEndTime=L:(_.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const y=!!p.audio,S=!!p.video;let R="";y&&(R+="audio"),S&&(R+="video");const C={data1:u,startPTS:A,startDTS:A,endPTS:L,endDTS:L,type:R,hasAudio:y,hasVideo:S,nb:1,dropped:0};return d.audio=C.type==="audio"?C:void 0,d.video=C.type!=="audio"?C:void 0,d.initSegment=f,d.id3=$h(i,n,h,h),s.samples.length&&(d.text=Mh(s,n,h)),d}}function pm(r,t,e,i){if(r===null)return!0;const s=Math.max(i,1),n=t-r.baseTime/r.timescale;return Math.abs(n-e)>s}function Nh(r,t){const e=r==null?void 0:r.codec;return e&&e.length>4?e:e==="hvc1"||e==="hev1"?"hvc1.1.6.L120.90":e==="av01"?"av01.0.04M.08":e==="avc1"||t===mt.VIDEO?"avc1.42e01e":"mp4a.40.5"}let Me;try{Me=self.performance.now.bind(self.performance)}catch{_.debug("Unable to use Performance API on this environment"),Me=typeof self<"u"&&self.Date.now}const Jn=[{demux:Xg,remux:fm},{demux:je,remux:Zn},{demux:zg,remux:Zn},{demux:am,remux:Zn}];class Uh{constructor(t,e,i,s,n){this.async=!1,this.observer=void 0,this.typeSupported=void 0,this.config=void 0,this.vendor=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=t,this.typeSupported=e,this.config=i,this.vendor=s,this.id=n}configure(t){this.transmuxConfig=t,this.decrypter&&this.decrypter.reset()}push(t,e,i,s){const n=i.transmuxing;n.executeStart=Me();let a=new Uint8Array(t);const{currentTransmuxState:o,transmuxConfig:l}=this;s&&(this.currentTransmuxState=s);const{contiguous:h,discontinuity:c,trackSwitch:d,accurateTimeOffset:u,timeOffset:f,initSegmentChange:p}=s||o,{audioCodec:g,videoCodec:v,defaultInitPts:E,duration:A,initSegmentData:L}=l,y=gm(a,e);if(y&&y.method==="AES-128"){const M=this.getDecrypter();if(M.isSync()){let D=M.softwareDecrypt(a,y.key.buffer,y.iv.buffer);if(i.part>-1&&(D=M.flush()),!D)return n.executeEnd=Me(),ta(i);a=new Uint8Array(D)}else return this.decryptionPromise=M.webCryptoDecrypt(a,y.key.buffer,y.iv.buffer).then(D=>{const I=this.push(D,null,i);return this.decryptionPromise=null,I}),this.decryptionPromise}const S=this.needsProbing(c,d);if(S){const M=this.configureTransmuxer(a);if(M)return _.warn(`[transmuxer] ${M.message}`),this.observer.emit(m.ERROR,m.ERROR,{type:Q.MEDIA_ERROR,details:$.FRAG_PARSING_ERROR,fatal:!1,error:M,reason:M.message}),n.executeEnd=Me(),ta(i)}(c||d||p||S)&&this.resetInitSegment(L,g,v,A,e),(c||p||S)&&this.resetInitialTimestamp(E),h||this.resetContiguity();const R=this.transmux(a,y,f,u,i),C=this.currentTransmuxState;return C.contiguous=!0,C.discontinuity=!1,C.trackSwitch=!1,n.executeEnd=Me(),R}flush(t){const e=t.transmuxing;e.executeStart=Me();const{decrypter:i,currentTransmuxState:s,decryptionPromise:n}=this;if(n)return n.then(()=>this.flush(t));const a=[],{timeOffset:o}=s;if(i){const d=i.flush();d&&a.push(this.push(d,null,t))}const{demuxer:l,remuxer:h}=this;if(!l||!h)return e.executeEnd=Me(),[ta(t)];const c=l.flush(o);return Er(c)?c.then(d=>(this.flushRemux(a,d,t),a)):(this.flushRemux(a,c,t),a)}flushRemux(t,e,i){const{audioTrack:s,videoTrack:n,id3Track:a,textTrack:o}=e,{accurateTimeOffset:l,timeOffset:h}=this.currentTransmuxState;_.log(`[transmuxer.ts]: Flushed fragment ${i.sn}${i.part>-1?" p: "+i.part:""} of level ${i.level}`);const c=this.remuxer.remux(s,n,a,o,h,l,!0,this.id);t.push({remuxResult:c,chunkMeta:i}),i.transmuxing.executeEnd=Me()}resetInitialTimestamp(t){const{demuxer:e,remuxer:i}=this;!e||!i||(e.resetTimeStamp(t),i.resetTimeStamp(t))}resetContiguity(){const{demuxer:t,remuxer:e}=this;!t||!e||(t.resetContiguity(),e.resetNextTimestamp())}resetInitSegment(t,e,i,s,n){const{demuxer:a,remuxer:o}=this;!a||!o||(a.resetInitSegment(t,e,i,s),o.resetInitSegment(t,e,i,n))}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)}transmux(t,e,i,s,n){let a;return e&&e.method==="SAMPLE-AES"?a=this.transmuxSampleAes(t,e,i,s,n):a=this.transmuxUnencrypted(t,i,s,n),a}transmuxUnencrypted(t,e,i,s){const{audioTrack:n,videoTrack:a,id3Track:o,textTrack:l}=this.demuxer.demux(t,e,!1,!this.config.progressive);return{remuxResult:this.remuxer.remux(n,a,o,l,e,i,!1,this.id),chunkMeta:s}}transmuxSampleAes(t,e,i,s,n){return this.demuxer.demuxSampleAes(t,e,i).then(a=>({remuxResult:this.remuxer.remux(a.audioTrack,a.videoTrack,a.id3Track,a.textTrack,i,s,!1,this.id),chunkMeta:n}))}configureTransmuxer(t){const{config:e,observer:i,typeSupported:s,vendor:n}=this;let a;for(let d=0,u=Jn.length;d<u;d++)if(Jn[d].demux.probe(t)){a=Jn[d];break}if(!a)return new Error("Failed to find demuxer by probing fragment data");const o=this.demuxer,l=this.remuxer,h=a.remux,c=a.demux;(!l||!(l instanceof h))&&(this.remuxer=new h(i,e,s,n)),(!o||!(o instanceof c))&&(this.demuxer=new c(i,e,s),this.probe=c.probe)}needsProbing(t,e){return!this.demuxer||!this.remuxer||t||e}getDecrypter(){let t=this.decrypter;return t||(t=this.decrypter=new jn(this.config)),t}}function gm(r,t){let e=null;return r.byteLength>0&&t!=null&&t.key!=null&&t.iv!==null&&t.method!=null&&(e=t),e}const ta=r=>({remuxResult:{},chunkMeta:r});function Er(r){return"then"in r&&r.then instanceof Function}class mm{constructor(t,e,i,s,n){this.audioCodec=void 0,this.videoCodec=void 0,this.initSegmentData=void 0,this.duration=void 0,this.defaultInitPts=void 0,this.audioCodec=t,this.videoCodec=e,this.initSegmentData=i,this.duration=s,this.defaultInitPts=n||null}}class vm{constructor(t,e,i,s,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=t,this.contiguous=e,this.accurateTimeOffset=i,this.trackSwitch=s,this.timeOffset=n,this.initSegmentChange=a}}var Bh={exports:{}};(function(r){var t=Object.prototype.hasOwnProperty,e="~";function i(){}Object.create&&(i.prototype=Object.create(null),new i().__proto__||(e=!1));function s(l,h,c){this.fn=l,this.context=h,this.once=c||!1}function n(l,h,c,d,u){if(typeof c!="function")throw new TypeError("The listener must be a function");var f=new s(c,d||l,u),p=e?e+h:h;return l._events[p]?l._events[p].fn?l._events[p]=[l._events[p],f]:l._events[p].push(f):(l._events[p]=f,l._eventsCount++),l}function a(l,h){--l._eventsCount===0?l._events=new i:delete l._events[h]}function o(){this._events=new i,this._eventsCount=0}o.prototype.eventNames=function(){var l=[],h,c;if(this._eventsCount===0)return l;for(c in h=this._events)t.call(h,c)&&l.push(e?c.slice(1):c);return Object.getOwnPropertySymbols?l.concat(Object.getOwnPropertySymbols(h)):l},o.prototype.listeners=function(l){var h=e?e+l:l,c=this._events[h];if(!c)return[];if(c.fn)return[c.fn];for(var d=0,u=c.length,f=new Array(u);d<u;d++)f[d]=c[d].fn;return f},o.prototype.listenerCount=function(l){var h=e?e+l:l,c=this._events[h];return c?c.fn?1:c.length:0},o.prototype.emit=function(l,h,c,d,u,f){var p=e?e+l:l;if(!this._events[p])return!1;var g=this._events[p],v=arguments.length,E,A;if(g.fn){switch(g.once&&this.removeListener(l,g.fn,void 0,!0),v){case 1:return g.fn.call(g.context),!0;case 2:return g.fn.call(g.context,h),!0;case 3:return g.fn.call(g.context,h,c),!0;case 4:return g.fn.call(g.context,h,c,d),!0;case 5:return g.fn.call(g.context,h,c,d,u),!0;case 6:return g.fn.call(g.context,h,c,d,u,f),!0}for(A=1,E=new Array(v-1);A<v;A++)E[A-1]=arguments[A];g.fn.apply(g.context,E)}else{var L=g.length,y;for(A=0;A<L;A++)switch(g[A].once&&this.removeListener(l,g[A].fn,void 0,!0),v){case 1:g[A].fn.call(g[A].context);break;case 2:g[A].fn.call(g[A].context,h);break;case 3:g[A].fn.call(g[A].context,h,c);break;case 4:g[A].fn.call(g[A].context,h,c,d);break;default:if(!E)for(y=1,E=new Array(v-1);y<v;y++)E[y-1]=arguments[y];g[A].fn.apply(g[A].context,E)}}return!0},o.prototype.on=function(l,h,c){return n(this,l,h,c,!1)},o.prototype.once=function(l,h,c){return n(this,l,h,c,!0)},o.prototype.removeListener=function(l,h,c,d){var u=e?e+l:l;if(!this._events[u])return this;if(!h)return a(this,u),this;var f=this._events[u];if(f.fn)f.fn===h&&(!d||f.once)&&(!c||f.context===c)&&a(this,u);else{for(var p=0,g=[],v=f.length;p<v;p++)(f[p].fn!==h||d&&!f[p].once||c&&f[p].context!==c)&&g.push(f[p]);g.length?this._events[u]=g.length===1?g[0]:g:a(this,u)}return this},o.prototype.removeAllListeners=function(l){var h;return l?(h=e?e+l:l,this._events[h]&&a(this,h)):(this._events=new i,this._eventsCount=0),this},o.prototype.off=o.prototype.removeListener,o.prototype.addListener=o.prototype.on,o.prefixed=e,o.EventEmitter=o,r.exports=o})(Bh);var ym=Bh.exports,ea=sp(ym);const ia=lr()||{isTypeSupported:()=>!1};class Hh{constructor(t,e,i,s){this.error=null,this.hls=void 0,this.id=void 0,this.observer=void 0,this.frag=null,this.part=null,this.useWorker=void 0,this.workerContext=null,this.onwmsg=void 0,this.transmuxer=null,this.onTransmuxComplete=void 0,this.onFlush=void 0;const n=t.config;this.hls=t,this.id=e,this.useWorker=!!n.enableWorker,this.onTransmuxComplete=i,this.onFlush=s;const a=(h,c)=>{c=c||{},c.frag=this.frag,c.id=this.id,h===m.ERROR&&(this.error=c.error),this.hls.trigger(h,c)};this.observer=new ea,this.observer.on(m.FRAG_DECRYPTED,a),this.observer.on(m.ERROR,a);const o={mp4:ia.isTypeSupported("video/mp4"),mpeg:ia.isTypeSupported("audio/mpeg"),mp3:ia.isTypeSupported('audio/mp4; codecs="mp3"')},l=navigator.vendor;if(this.useWorker&&typeof Worker<"u"&&(n.workerPath||Ug())){try{n.workerPath?(_.log(`loading Web Worker ${n.workerPath} for "${e}"`),this.workerContext=Hg(n.workerPath)):(_.log(`injecting Web Worker for "${e}"`),this.workerContext=Bg()),this.onwmsg=c=>this.onWorkerMessage(c);const{worker:h}=this.workerContext;h.addEventListener("message",this.onwmsg),h.onerror=c=>{const d=new Error(`${c.message} (${c.filename}:${c.lineno})`);n.enableWorker=!1,_.warn(`Error in "${e}" Web Worker, fallback to inline`),this.hls.trigger(m.ERROR,{type:Q.OTHER_ERROR,details:$.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:d})},h.postMessage({cmd:"init",typeSupported:o,vendor:l,id:e,config:JSON.stringify(n)})}catch(h){_.warn(`Error setting up "${e}" Web Worker, fallback to inline`,h),this.resetWorker(),this.error=null,this.transmuxer=new Uh(this.observer,o,n,l,e)}return}this.transmuxer=new Uh(this.observer,o,n,l,e)}resetWorker(){if(this.workerContext){const{worker:t,objectURL:e}=this.workerContext;e&&self.URL.revokeObjectURL(e),t.removeEventListener("message",this.onwmsg),t.onerror=null,t.terminate(),this.workerContext=null}}destroy(){if(this.workerContext)this.resetWorker(),this.onwmsg=void 0;else{const e=this.transmuxer;e&&(e.destroy(),this.transmuxer=null)}const t=this.observer;t&&t.removeAllListeners(),this.frag=null,this.observer=null,this.hls=null}push(t,e,i,s,n,a,o,l,h,c){var d,u;h.transmuxing.start=self.performance.now();const{transmuxer:f}=this,p=a?a.start:n.start,g=n.decryptdata,v=this.frag,E=!(v&&n.cc===v.cc),A=!(v&&h.level===v.level),L=v?h.sn-v.sn:-1,y=this.part?h.part-this.part.index:-1,S=L===0&&h.id>1&&h.id===(v==null?void 0:v.stats.chunkCount),R=!A&&(L===1||L===0&&(y===1||S&&y<=0)),C=self.performance.now();(A||L||n.stats.parsing.start===0)&&(n.stats.parsing.start=C),a&&(y||!R)&&(a.stats.parsing.start=C);const M=!(v&&((d=n.initSegment)==null?void 0:d.url)===((u=v.initSegment)==null?void 0:u.url)),D=new vm(E,R,l,A,p,M);if(!R||E||M){_.log(`[transmuxer-interface, ${n.type}]: Starting new transmux session for sn: ${h.sn} p: ${h.part} level: ${h.level} id: ${h.id}
160
149
  discontinuity: ${E}
161
- trackSwitch: ${T}
162
- contiguous: ${S}
150
+ trackSwitch: ${A}
151
+ contiguous: ${R}
163
152
  accurateTimeOffset: ${l}
164
153
  timeOffset: ${p}
165
- initSegmentChange: ${D}`);const I=new Km(i,s,e,o,d);this.configureTransmuxer(I)}if(this.frag=n,this.part=a,this.workerContext)this.workerContext.worker.postMessage({cmd:"demux",data:t,decryptdata:g,chunkMeta:h,state:_},t instanceof ArrayBuffer?[t]:[]);else if(f){const I=f.push(t,g,h,_);Er(I)?(f.async=!0,I.then(N=>{this.handleTransmuxComplete(N)}).catch(N=>{this.transmuxerError(N,h,"transmuxer-interface push error")})):(f.async=!1,this.handleTransmuxComplete(I))}}flush(t){t.transmuxing.start=self.performance.now();const{transmuxer:e}=this;if(this.workerContext)this.workerContext.worker.postMessage({cmd:"flush",chunkMeta:t});else if(e){let i=e.flush(t);Er(i)||e.async?(Er(i)||(i=Promise.resolve(i)),i.then(s=>{this.handleFlushResult(s,t)}).catch(s=>{this.transmuxerError(s,t,"transmuxer-interface flush error")})):this.handleFlushResult(i,t)}}transmuxerError(t,e,i){this.hls&&(this.error=t,this.hls.trigger(m.ERROR,{type:W.MEDIA_ERROR,details:x.FRAG_PARSING_ERROR,chunkMeta:e,fatal:!1,error:t,err:t,reason:i}))}handleFlushResult(t,e){t.forEach(i=>{this.handleTransmuxComplete(i)}),this.onFlush(e)}onWorkerMessage(t){const e=t.data,i=this.hls;switch(e.event){case"init":{var s;const n=(s=this.workerContext)==null?void 0:s.objectURL;n&&self.URL.revokeObjectURL(n);break}case"transmuxComplete":{this.handleTransmuxComplete(e.data);break}case"flush":{this.onFlush(e.data);break}case"workerLog":L[e.data.logType]&&L[e.data.logType](e.data.message);break;default:{e.data=e.data||{},e.data.frag=this.frag,e.data.id=this.id,i.trigger(e.event,e.data);break}}}configureTransmuxer(t){const{transmuxer:e}=this;this.workerContext?this.workerContext.worker.postMessage({cmd:"configure",config:t}):e&&e.configure(t)}handleTransmuxComplete(t){t.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(t)}}const Ym=250,ma=2,zm=.1,qm=.05;class Xm{constructor(t,e,i,s){this.config=void 0,this.media=null,this.fragmentTracker=void 0,this.hls=void 0,this.nudgeRetry=0,this.stallReported=!1,this.stalled=null,this.moved=!1,this.seeking=!1,this.config=t,this.media=e,this.fragmentTracker=i,this.hls=s}destroy(){this.media=null,this.hls=this.fragmentTracker=null}poll(t,e){const{config:i,media:s,stalled:n}=this;if(s===null)return;const{currentTime:a,seeking:o}=s,l=this.seeking&&!o,h=!this.seeking&&o;if(this.seeking=o,a!==t){if(this.moved=!0,n!==null){if(this.stallReported){const E=self.performance.now()-n;L.warn(`playback not stuck anymore @${a}, after ${Math.round(E)}ms`),this.stallReported=!1}this.stalled=null,this.nudgeRetry=0}return}if(h||l){this.stalled=null;return}if(s.paused&&!o||s.ended||s.playbackRate===0||!lt.getBuffered(s).length)return;const d=lt.bufferInfo(s,a,0),c=d.len>0,u=d.nextStart||0;if(!c&&!u)return;if(o){const E=d.len>ma,T=!u||e&&e.start<=a||u-a>ma&&!this.fragmentTracker.getPartialFragment(a);if(E||T)return;this.moved=!1}if(!this.moved&&this.stalled!==null){var f;const E=Math.max(u,d.start||0)-a,T=this.hls.levels?this.hls.levels[this.hls.currentLevel]:null,A=!(T==null||(f=T.details)==null)&&f.live?T.details.targetduration*2:ma,y=this.fragmentTracker.getPartialFragment(a);if(E>0&&(E<=A||y)){this._trySkipBufferHole(y);return}}const p=self.performance.now();if(n===null){this.stalled=p;return}const g=p-n;if(!o&&g>=Ym&&(this._reportStall(d),!this.media))return;const v=lt.bufferInfo(s,a,i.maxBufferHole);this._tryFixBufferStall(v,g)}_tryFixBufferStall(t,e){const{config:i,fragmentTracker:s,media:n}=this;if(n===null)return;const a=n.currentTime,o=s.getPartialFragment(a);o&&(this._trySkipBufferHole(o)||!this.media)||(t.len>i.maxBufferHole||t.nextStart&&t.nextStart-a<i.maxBufferHole)&&e>i.highBufferWatchdogPeriod*1e3&&(L.warn("Trying to nudge playhead over buffer-hole"),this.stalled=null,this._tryNudgeBuffer())}_reportStall(t){const{hls:e,media:i,stallReported:s}=this;if(!s&&i){this.stallReported=!0;const n=new Error(`Playback stalling at @${i.currentTime} due to low buffer (${JSON.stringify(t)})`);L.warn(n.message),e.trigger(m.ERROR,{type:W.MEDIA_ERROR,details:x.BUFFER_STALLED_ERROR,fatal:!1,error:n,buffer:t.len})}}_trySkipBufferHole(t){const{config:e,hls:i,media:s}=this;if(s===null)return 0;const n=s.currentTime,a=lt.bufferInfo(s,n,0),o=n<a.start?a.start:a.nextStart;if(o){const l=a.len<=e.maxBufferHole,h=a.len>0&&a.len<1&&s.readyState<3,d=o-n;if(d>0&&(l||h)){if(d>e.maxBufferHole){const{fragmentTracker:u}=this;let f=!1;if(n===0){const p=u.getAppendedFrag(0,Y.MAIN);p&&o<p.end&&(f=!0)}if(!f){const p=t||u.getAppendedFrag(n,Y.MAIN);if(p){let g=!1,v=p.end;for(;v<o;){const E=u.getPartialFragment(v);if(E)v+=E.duration;else{g=!0;break}}if(g)return 0}}}const c=Math.max(o+qm,n+zm);if(L.warn(`skipping hole, adjusting currentTime from ${n} to ${c}`),this.moved=!0,this.stalled=null,s.currentTime=c,t&&!t.gap){const u=new Error(`fragment loaded with buffer holes, seeking from ${n} to ${c}`);i.trigger(m.ERROR,{type:W.MEDIA_ERROR,details:x.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:u,reason:u.message,frag:t})}return c}}return 0}_tryNudgeBuffer(){const{config:t,hls:e,media:i,nudgeRetry:s}=this;if(i===null)return;const n=i.currentTime;if(this.nudgeRetry++,s<t.nudgeMaxRetry){const a=n+(s+1)*t.nudgeOffset,o=new Error(`Nudging 'currentTime' from ${n} to ${a}`);L.warn(o.message),i.currentTime=a,e.trigger(m.ERROR,{type:W.MEDIA_ERROR,details:x.BUFFER_NUDGE_ON_STALL,error:o,fatal:!1})}else{const a=new Error(`Playhead still not moving while enough data buffered @${n} after ${t.nudgeMaxRetry} nudges`);L.error(a.message),e.trigger(m.ERROR,{type:W.MEDIA_ERROR,details:x.BUFFER_STALLED_ERROR,error:a,fatal:!0})}}}const Qm=100;class Zm extends na{constructor(t,e,i){super(t,e,i,"[stream-controller]",Y.MAIN),this.audioCodecSwap=!1,this.gapController=null,this.level=-1,this._forceStartLoad=!1,this.altAudio=!1,this.audioOnly=!1,this.fragPlaying=null,this.onvplaying=null,this.onvseeked=null,this.fragLastKbps=0,this.couldBacktrack=!1,this.backtrackFragment=null,this.audioCodecSwitch=!1,this.videoBuffer=null,this._registerListeners()}_registerListeners(){const{hls:t}=this;t.on(m.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(m.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(m.MANIFEST_LOADING,this.onManifestLoading,this),t.on(m.MANIFEST_PARSED,this.onManifestParsed,this),t.on(m.LEVEL_LOADING,this.onLevelLoading,this),t.on(m.LEVEL_LOADED,this.onLevelLoaded,this),t.on(m.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),t.on(m.ERROR,this.onError,this),t.on(m.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on(m.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),t.on(m.BUFFER_CREATED,this.onBufferCreated,this),t.on(m.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on(m.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(m.FRAG_BUFFERED,this.onFragBuffered,this)}_unregisterListeners(){const{hls:t}=this;t.off(m.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(m.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(m.MANIFEST_LOADING,this.onManifestLoading,this),t.off(m.MANIFEST_PARSED,this.onManifestParsed,this),t.off(m.LEVEL_LOADED,this.onLevelLoaded,this),t.off(m.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),t.off(m.ERROR,this.onError,this),t.off(m.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off(m.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),t.off(m.BUFFER_CREATED,this.onBufferCreated,this),t.off(m.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off(m.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(m.FRAG_BUFFERED,this.onFragBuffered,this)}onHandlerDestroying(){this._unregisterListeners(),this.onMediaDetaching()}startLoad(t){if(this.levels){const{lastCurrentTime:e,hls:i}=this;if(this.stopLoad(),this.setInterval(Qm),this.level=-1,!this.startFragRequested){let s=i.startLevel;s===-1&&(i.config.testBandwidth&&this.levels.length>1?(s=0,this.bitrateTest=!0):s=i.nextAutoLevel),this.level=i.nextLoadLevel=s,this.loadedmetadata=!1}e>0&&t===-1&&(this.log(`Override startPosition with lastCurrentTime @${e.toFixed(3)}`),t=e),this.state=$.IDLE,this.nextLoadPosition=this.startPosition=this.lastCurrentTime=t,this.tick()}else this._forceStartLoad=!0,this.state=$.STOPPED}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case $.WAITING_LEVEL:{var t;const{levels:i,level:s}=this,n=i==null||(t=i[s])==null?void 0:t.details;if(n&&(!n.live||this.levelLastLoaded===this.level)){if(this.waitForCdnTuneIn(n))break;this.state=$.IDLE;break}else if(this.hls.nextLoadLevel!==this.level){this.state=$.IDLE;break}break}case $.FRAG_LOADING_WAITING_RETRY:{var e;const i=self.performance.now(),s=this.retryDate;(!s||i>=s||(e=this.media)!=null&&e.seeking)&&(this.resetStartWhenNotLoaded(this.level),this.state=$.IDLE)}break}this.state===$.IDLE&&this.doTickIdle(),this.onTickEnd()}onTickEnd(){super.onTickEnd(),this.checkBuffer(),this.checkFragmentChanged()}doTickIdle(){const{hls:t,levelLastLoaded:e,levels:i,media:s}=this,{config:n,nextLoadLevel:a}=t;if(e===null||!s&&(this.startFragRequested||!n.startFragPrefetch)||this.altAudio&&this.audioOnly||!(i!=null&&i[a]))return;const o=i[a],l=this.getMainFwdBufferInfo();if(l===null)return;const h=this.getLevelDetails();if(h&&this._streamEnded(l,h)){const v={};this.altAudio&&(v.type="video"),this.hls.trigger(m.BUFFER_EOS,v),this.state=$.ENDED;return}t.loadLevel!==a&&t.manualLevel===-1&&this.log(`Adapting to level ${a} from level ${this.level}`),this.level=t.nextLoadLevel=a;const d=o.details;if(!d||this.state===$.WAITING_LEVEL||d.live&&this.levelLastLoaded!==a){this.level=a,this.state=$.WAITING_LEVEL;return}const c=l.len,u=this.getMaxBufferLength(o.maxBitrate);if(c>=u)return;this.backtrackFragment&&this.backtrackFragment.start>l.end&&(this.backtrackFragment=null);const f=this.backtrackFragment?this.backtrackFragment.start:l.end;let p=this.getNextFragment(f,d);if(this.couldBacktrack&&!this.fragPrevious&&p&&p.sn!=="initSegment"&&this.fragmentTracker.getState(p)!==Lt.OK){var g;const v=((g=this.backtrackFragment)!=null?g:p).sn-d.startSN,E=d.fragments[v-1];E&&p.cc===E.cc&&(p=E,this.fragmentTracker.removeFragment(E))}else this.backtrackFragment&&l.len&&(this.backtrackFragment=null);if(p&&this.isLoopLoading(p,f)){if(!p.gap){const v=this.audioOnly&&!this.altAudio?at.AUDIO:at.VIDEO,E=(v===at.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;E&&this.afterBufferFlushed(E,v,Y.MAIN)}p=this.getNextFragmentLoopLoading(p,d,l,Y.MAIN,u)}p&&(p.initSegment&&!p.initSegment.data&&!this.bitrateTest&&(p=p.initSegment),this.loadFragment(p,o,f))}loadFragment(t,e,i){const s=this.fragmentTracker.getState(t);this.fragCurrent=t,s===Lt.NOT_LOADED||s===Lt.PARTIAL?t.sn==="initSegment"?this._loadInitSegment(t,e):this.bitrateTest?(this.log(`Fragment ${t.sn} of level ${t.level} is being downloaded to test bitrate and will not be buffered`),this._loadBitrateTestFrag(t,e)):(this.startFragRequested=!0,super.loadFragment(t,e,i)):this.clearTrackerIfNeeded(t)}getBufferedFrag(t){return this.fragmentTracker.getBufferedFrag(t,Y.MAIN)}followingBufferedFrag(t){return t?this.getBufferedFrag(t.end+.5):null}immediateLevelSwitch(){this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY)}nextLevelSwitch(){const{levels:t,media:e}=this;if(e!=null&&e.readyState){let i;const s=this.getAppendedFrag(e.currentTime);s&&s.start>1&&this.flushMainBuffer(0,s.start-1);const n=this.getLevelDetails();if(n!=null&&n.live){const o=this.getMainFwdBufferInfo();if(!o||o.len<n.targetduration*2)return}if(!e.paused&&t){const o=this.hls.nextLoadLevel,l=t[o],h=this.fragLastKbps;h&&this.fragCurrent?i=this.fragCurrent.duration*l.maxBitrate/(1e3*h)+1:i=0}else i=0;const a=this.getBufferedFrag(e.currentTime+i);if(a){const o=this.followingBufferedFrag(a);if(o){this.abortCurrentFrag();const l=o.maxStartPTS?o.maxStartPTS:o.start,h=o.duration,d=Math.max(a.end,l+Math.min(Math.max(h-this.config.maxFragLookUpTolerance,h*.5),h*.75));this.flushMainBuffer(d,Number.POSITIVE_INFINITY)}}}}abortCurrentFrag(){const t=this.fragCurrent;switch(this.fragCurrent=null,this.backtrackFragment=null,t&&(t.abortRequests(),this.fragmentTracker.removeFragment(t)),this.state){case $.KEY_LOADING:case $.FRAG_LOADING:case $.FRAG_LOADING_WAITING_RETRY:case $.PARSING:case $.PARSED:this.state=$.IDLE;break}this.nextLoadPosition=this.getLoadPosition()}flushMainBuffer(t,e){super.flushMainBuffer(t,e,this.altAudio?"video":null)}onMediaAttached(t,e){super.onMediaAttached(t,e);const i=e.media;this.onvplaying=this.onMediaPlaying.bind(this),this.onvseeked=this.onMediaSeeked.bind(this),i.addEventListener("playing",this.onvplaying),i.addEventListener("seeked",this.onvseeked),this.gapController=new Xm(this.config,i,this.fragmentTracker,this.hls)}onMediaDetaching(){const{media:t}=this;t&&this.onvplaying&&this.onvseeked&&(t.removeEventListener("playing",this.onvplaying),t.removeEventListener("seeked",this.onvseeked),this.onvplaying=this.onvseeked=null,this.videoBuffer=null),this.fragPlaying=null,this.gapController&&(this.gapController.destroy(),this.gapController=null),super.onMediaDetaching()}onMediaPlaying(){this.tick()}onMediaSeeked(){const t=this.media,e=t?t.currentTime:null;j(e)&&this.log(`Media seeked to ${e.toFixed(3)}`);const i=this.getMainFwdBufferInfo();if(i===null||i.len===0){this.warn(`Main forward buffer length on "seeked" event ${i?i.len:"empty"})`);return}this.tick()}onManifestLoading(){this.log("Trigger BUFFER_RESET"),this.hls.trigger(m.BUFFER_RESET,void 0),this.fragmentTracker.removeAllFragments(),this.couldBacktrack=!1,this.startPosition=this.lastCurrentTime=0,this.levels=this.fragPlaying=this.backtrackFragment=null,this.altAudio=this.audioOnly=!1}onManifestParsed(t,e){let i=!1,s=!1,n;e.levels.forEach(a=>{n=a.audioCodec,n&&(n.indexOf("mp4a.40.2")!==-1&&(i=!0),n.indexOf("mp4a.40.5")!==-1&&(s=!0))}),this.audioCodecSwitch=i&&s&&!um(),this.audioCodecSwitch&&this.log("Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC"),this.levels=e.levels,this.startFragRequested=!1}onLevelLoading(t,e){const{levels:i}=this;if(!i||this.state!==$.IDLE)return;const s=i[e.level];(!s.details||s.details.live&&this.levelLastLoaded!==e.level||this.waitForCdnTuneIn(s.details))&&(this.state=$.WAITING_LEVEL)}onLevelLoaded(t,e){var i;const{levels:s}=this,n=e.level,a=e.details,o=a.totalduration;if(!s){this.warn(`Levels were reset while loading level ${n}`);return}this.log(`Level ${n} loaded [${a.startSN},${a.endSN}]${a.lastPartSn?`[part-${a.lastPartSn}-${a.lastPartIndex}]`:""}, cc [${a.startCC}, ${a.endCC}] duration:${o}`);const l=s[n],h=this.fragCurrent;h&&(this.state===$.FRAG_LOADING||this.state===$.FRAG_LOADING_WAITING_RETRY)&&(h.level!==e.level||h.urlId!==l.urlId)&&h.loader&&this.abortCurrentFrag();let d=0;if(a.live||(i=l.details)!=null&&i.live){if(this.checkLiveUpdate(a),a.deltaUpdateFailed)return;d=this.alignPlaylists(a,l.details)}if(l.details=a,this.levelLastLoaded=n,this.hls.trigger(m.LEVEL_UPDATED,{details:a,level:n}),this.state===$.WAITING_LEVEL){if(this.waitForCdnTuneIn(a))return;this.state=$.IDLE}this.startFragRequested?a.live&&this.synchronizeToLiveEdge(a):this.setStartPosition(a,d),this.tick()}_handleFragmentLoadProgress(t){var e;const{frag:i,part:s,payload:n}=t,{levels:a}=this;if(!a){this.warn(`Levels were reset while fragment load was in progress. Fragment ${i.sn} of level ${i.level} will not be buffered`);return}const o=a[i.level],l=o.details;if(!l){this.warn(`Dropping fragment ${i.sn} of level ${i.level} after level details were reset`),this.fragmentTracker.removeFragment(i);return}const h=o.videoCodec,d=l.PTSKnown||!l.live,c=(e=i.initSegment)==null?void 0:e.data,u=this._getAudioCodec(o),f=this.transmuxer=this.transmuxer||new hd(this.hls,Y.MAIN,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),p=s?s.index:-1,g=p!==-1,v=new ia(i.level,i.sn,i.stats.chunkCount,n.byteLength,p,g),E=this.initPTS[i.cc];f.push(n,c,u,h,i,s,l.totalduration,d,v,E)}onAudioTrackSwitching(t,e){const i=this.altAudio;if(!e.url){if(this.mediaBuffer!==this.media){this.log("Switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;const n=this.fragCurrent;n&&(this.log("Switching to main audio track, cancel main fragment load"),n.abortRequests(),this.fragmentTracker.removeFragment(n)),this.resetTransmuxer(),this.resetLoadingState()}else this.audioOnly&&this.resetTransmuxer();const s=this.hls;i&&(s.trigger(m.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null}),this.fragmentTracker.removeAllFragments()),s.trigger(m.AUDIO_TRACK_SWITCHED,e)}}onAudioTrackSwitched(t,e){const i=e.id,s=!!this.hls.audioTracks[i].url;if(s){const n=this.videoBuffer;n&&this.mediaBuffer!==n&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=n)}this.altAudio=s,this.tick()}onBufferCreated(t,e){const i=e.tracks;let s,n,a=!1;for(const o in i){const l=i[o];if(l.id==="main"){if(n=o,s=l,o==="video"){const h=i[o];h&&(this.videoBuffer=h.buffer)}}else a=!0}a&&s?(this.log(`Alternate track found, use ${n}.buffered to schedule main fragment loading`),this.mediaBuffer=s.buffer):this.mediaBuffer=this.media}onFragBuffered(t,e){const{frag:i,part:s}=e;if(i&&i.type!==Y.MAIN)return;if(this.fragContextChanged(i)){this.warn(`Fragment ${i.sn}${s?" p: "+s.index:""} of level ${i.level} finished buffering, but was aborted. state: ${this.state}`),this.state===$.PARSED&&(this.state=$.IDLE);return}const n=s?s.stats:i.stats;this.fragLastKbps=Math.round(8*n.total/(n.buffering.end-n.loading.first)),i.sn!=="initSegment"&&(this.fragPrevious=i),this.fragBufferedComplete(i,s)}onError(t,e){var i;if(e.fatal){this.state=$.ERROR;return}switch(e.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(Y.MAIN,e);break;case x.LEVEL_LOAD_ERROR:case x.LEVEL_LOAD_TIMEOUT:case x.LEVEL_PARSING_ERROR:!e.levelRetry&&this.state===$.WAITING_LEVEL&&((i=e.context)==null?void 0:i.type)===rt.LEVEL&&(this.state=$.IDLE);break;case x.BUFFER_FULL_ERROR:if(!e.parent||e.parent!=="main")return;this.reduceLengthAndFlushBuffer(e)&&this.flushMainBuffer(0,Number.POSITIVE_INFINITY);break;case x.INTERNAL_EXCEPTION:this.recoverWorkerError(e);break}}checkBuffer(){const{media:t,gapController:e}=this;if(!(!t||!e||!t.readyState)){if(this.loadedmetadata||!lt.getBuffered(t).length){const i=this.state!==$.IDLE?this.fragCurrent:null;e.poll(this.lastCurrentTime,i)}this.lastCurrentTime=t.currentTime}}onFragLoadEmergencyAborted(){this.state=$.IDLE,this.loadedmetadata||(this.startFragRequested=!1,this.nextLoadPosition=this.startPosition),this.tickImmediate()}onBufferFlushed(t,{type:e}){if(e!==at.AUDIO||this.audioOnly&&!this.altAudio){const i=(e===at.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;this.afterBufferFlushed(i,e,Y.MAIN)}}onLevelsUpdated(t,e){this.levels=e.levels}swapAudioCodec(){this.audioCodecSwap=!this.audioCodecSwap}seekToStartPos(){const{media:t}=this;if(!t)return;const e=t.currentTime;let i=this.startPosition;if(i>=0&&e<i){if(t.seeking){this.log(`could not seek to ${i}, already seeking at ${e}`);return}const s=lt.getBuffered(t),n=(s.length?s.start(0):0)-i;n>0&&(n<this.config.maxBufferHole||n<this.config.maxFragLookUpTolerance)&&(this.log(`adjusting start position by ${n} to match buffer start`),i+=n,this.startPosition=i),this.log(`seek to target start position ${i} from current time ${e}`),t.currentTime=i}}_getAudioCodec(t){let e=this.config.defaultAudioCodec||t.audioCodec;return this.audioCodecSwap&&e&&(this.log("Swapping audio codec"),e.indexOf("mp4a.40.5")!==-1?e="mp4a.40.2":e="mp4a.40.5"),e}_loadBitrateTestFrag(t,e){t.bitrateTest=!0,this._doFragLoad(t,e).then(i=>{const{hls:s}=this;if(!i||this.fragContextChanged(t))return;e.fragmentError=0,this.state=$.IDLE,this.startFragRequested=!1,this.bitrateTest=!1;const n=t.stats;n.parsing.start=n.parsing.end=n.buffering.start=n.buffering.end=self.performance.now(),s.trigger(m.FRAG_LOADED,i),t.bitrateTest=!1})}_handleTransmuxComplete(t){var e;const i="main",{hls:s}=this,{remuxResult:n,chunkMeta:a}=t,o=this.getCurrentContext(a);if(!o){this.resetWhenMissingContext(a);return}const{frag:l,part:h,level:d}=o,{video:c,text:u,id3:f,initSegment:p}=n,{details:g}=d,v=this.altAudio?void 0:n.audio;if(this.fragContextChanged(l)){this.fragmentTracker.removeFragment(l);return}if(this.state=$.PARSING,p){if(p!=null&&p.tracks){const A=l.initSegment||l;this._bufferInitSegment(d,p.tracks,A,a),s.trigger(m.FRAG_PARSING_INIT_SEGMENT,{frag:A,id:i,tracks:p.tracks})}const E=p.initPTS,T=p.timescale;j(E)&&(this.initPTS[l.cc]={baseTime:E,timescale:T},s.trigger(m.INIT_PTS_FOUND,{frag:l,id:i,initPTS:E,timescale:T}))}if(c&&g&&l.sn!=="initSegment"){const E=g.fragments[l.sn-1-g.startSN],T=l.sn===g.startSN,A=!E||l.cc>E.cc;if(n.independent!==!1){const{startPTS:y,endPTS:b,startDTS:S,endDTS:R}=c;if(h)h.elementaryStreams[c.type]={startPTS:y,endPTS:b,startDTS:S,endDTS:R};else if(c.firstKeyFrame&&c.independent&&a.id===1&&!A&&(this.couldBacktrack=!0),c.dropped&&c.independent){const D=this.getMainFwdBufferInfo(),_=(D?D.end:this.getLoadPosition())+this.config.maxBufferHole,I=c.firstKeyFramePTS?c.firstKeyFramePTS:y;if(!T&&_<I-this.config.maxBufferHole&&!A){this.backtrack(l);return}else A&&(l.gap=!0);l.setElementaryStreamInfo(c.type,l.start,b,l.start,R,!0)}l.setElementaryStreamInfo(c.type,y,b,S,R),this.backtrackFragment&&(this.backtrackFragment=l),this.bufferFragmentData(c,l,h,a,T||A)}else if(T||A)l.gap=!0;else{this.backtrack(l);return}}if(v){const{startPTS:E,endPTS:T,startDTS:A,endDTS:y}=v;h&&(h.elementaryStreams[at.AUDIO]={startPTS:E,endPTS:T,startDTS:A,endDTS:y}),l.setElementaryStreamInfo(at.AUDIO,E,T,A,y),this.bufferFragmentData(v,l,h,a)}if(g&&f!=null&&(e=f.samples)!=null&&e.length){const E={id:i,frag:l,details:g,samples:f.samples};s.trigger(m.FRAG_PARSING_METADATA,E)}if(g&&u){const E={id:i,frag:l,details:g,samples:u.samples};s.trigger(m.FRAG_PARSING_USERDATA,E)}}_bufferInitSegment(t,e,i,s){if(this.state!==$.PARSING)return;this.audioOnly=!!e.audio&&!e.video,this.altAudio&&!this.audioOnly&&delete e.audio;const{audio:n,video:a,audiovideo:o}=e;if(n){let l=t.audioCodec;const h=navigator.userAgent.toLowerCase();this.audioCodecSwitch&&(l&&(l.indexOf("mp4a.40.5")!==-1?l="mp4a.40.2":l="mp4a.40.5"),n.metadata.channelCount!==1&&h.indexOf("firefox")===-1&&(l="mp4a.40.5")),h.indexOf("android")!==-1&&n.container!=="audio/mpeg"&&(l="mp4a.40.2",this.log(`Android: force audio codec to ${l}`)),t.audioCodec&&t.audioCodec!==l&&this.log(`Swapping manifest audio codec "${t.audioCodec}" for "${l}"`),n.levelCodec=l,n.id="main",this.log(`Init audio buffer, container:${n.container}, codecs[selected/level/parsed]=[${l||""}/${t.audioCodec||""}/${n.codec}]`)}a&&(a.levelCodec=t.videoCodec,a.id="main",this.log(`Init video buffer, container:${a.container}, codecs[level/parsed]=[${t.videoCodec||""}/${a.codec}]`)),o&&this.log(`Init audiovideo buffer, container:${o.container}, codecs[level/parsed]=[${t.attrs.CODECS||""}/${o.codec}]`),this.hls.trigger(m.BUFFER_CODECS,e),Object.keys(e).forEach(l=>{const h=e[l].initSegment;h!=null&&h.byteLength&&this.hls.trigger(m.BUFFER_APPENDING,{type:l,data:h,frag:i,part:null,chunkMeta:s,parent:i.type})}),this.tick()}getMainFwdBufferInfo(){return this.getFwdBufferInfo(this.mediaBuffer?this.mediaBuffer:this.media,Y.MAIN)}backtrack(t){this.couldBacktrack=!0,this.backtrackFragment=t,this.resetTransmuxer(),this.flushBufferGap(t),this.fragmentTracker.removeFragment(t),this.fragPrevious=null,this.nextLoadPosition=t.start,this.state=$.IDLE}checkFragmentChanged(){const t=this.media;let e=null;if(t&&t.readyState>1&&t.seeking===!1){const i=t.currentTime;if(lt.isBuffered(t,i)?e=this.getAppendedFrag(i):lt.isBuffered(t,i+.1)&&(e=this.getAppendedFrag(i+.1)),e){this.backtrackFragment=null;const s=this.fragPlaying,n=e.level;(!s||e.sn!==s.sn||s.level!==n||e.urlId!==s.urlId)&&(this.fragPlaying=e,this.hls.trigger(m.FRAG_CHANGED,{frag:e}),(!s||s.level!==n)&&this.hls.trigger(m.LEVEL_SWITCHED,{level:n}))}}}get nextLevel(){const t=this.nextBufferedFrag;return t?t.level:-1}get currentFrag(){const t=this.media;return t?this.fragPlaying||this.getAppendedFrag(t.currentTime):null}get currentProgramDateTime(){const t=this.media;if(t){const e=t.currentTime,i=this.currentFrag;if(i&&j(e)&&j(i.programDateTime)){const s=i.programDateTime+(e-i.start)*1e3;return new Date(s)}}return null}get currentLevel(){const t=this.currentFrag;return t?t.level:-1}get nextBufferedFrag(){const t=this.currentFrag;return t?this.followingBufferedFrag(t):null}get forceStartLoad(){return this._forceStartLoad}}class Si{constructor(t,e=0,i=0){this.halfLife=void 0,this.alpha_=void 0,this.estimate_=void 0,this.totalWeight_=void 0,this.halfLife=t,this.alpha_=t?Math.exp(Math.log(.5)/t):0,this.estimate_=e,this.totalWeight_=i}sample(t,e){const i=Math.pow(this.alpha_,t);this.estimate_=e*(1-i)+i*this.estimate_,this.totalWeight_+=t}getTotalWeight(){return this.totalWeight_}getEstimate(){if(this.alpha_){const t=1-Math.pow(this.alpha_,this.totalWeight_);if(t)return this.estimate_/t}return this.estimate_}}class Jm{constructor(t,e,i,s=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 Si(t),this.fast_=new Si(e),this.defaultTTFB_=s,this.ttfb_=new Si(t)}update(t,e){const{slow_:i,fast_:s,ttfb_:n}=this;i.halfLife!==t&&(this.slow_=new Si(t,i.getEstimate(),i.getTotalWeight())),s.halfLife!==e&&(this.fast_=new Si(e,s.getEstimate(),s.getTotalWeight())),n.halfLife!==t&&(this.ttfb_=new Si(t,n.getEstimate(),n.getTotalWeight()))}sample(t,e){t=Math.max(t,this.minDelayMs_);const i=8*e,s=t/1e3,n=i/s;this.fast_.sample(s,n),this.slow_.sample(s,n)}sampleTTFB(t){const e=t/1e3,i=Math.sqrt(2)*Math.exp(-Math.pow(e,2)/2);this.ttfb_.sample(i,Math.max(t,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_}destroy(){}}class tv{constructor(t){this.hls=void 0,this.lastLevelLoadSec=0,this.lastLoadedFragLevel=0,this._nextAutoLevel=-1,this.timer=-1,this.onCheck=this._abandonRulesCheck.bind(this),this.fragCurrent=null,this.partCurrent=null,this.bitrateTestDelay=0,this.bwEstimator=void 0,this.hls=t;const e=t.config;this.bwEstimator=new Jm(e.abrEwmaSlowVoD,e.abrEwmaFastVoD,e.abrEwmaDefaultEstimate),this.registerListeners()}registerListeners(){const{hls:t}=this;t.on(m.FRAG_LOADING,this.onFragLoading,this),t.on(m.FRAG_LOADED,this.onFragLoaded,this),t.on(m.FRAG_BUFFERED,this.onFragBuffered,this),t.on(m.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(m.LEVEL_LOADED,this.onLevelLoaded,this)}unregisterListeners(){const{hls:t}=this;t.off(m.FRAG_LOADING,this.onFragLoading,this),t.off(m.FRAG_LOADED,this.onFragLoaded,this),t.off(m.FRAG_BUFFERED,this.onFragBuffered,this),t.off(m.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(m.LEVEL_LOADED,this.onLevelLoaded,this)}destroy(){this.unregisterListeners(),this.clearTimer(),this.hls=this.onCheck=null,this.fragCurrent=this.partCurrent=null}onFragLoading(t,e){var i;const s=e.frag;this.ignoreFragment(s)||(this.fragCurrent=s,this.partCurrent=(i=e.part)!=null?i:null,this.clearTimer(),this.timer=self.setInterval(this.onCheck,100))}onLevelSwitching(t,e){this.clearTimer()}getTimeToLoadFrag(t,e,i,s){const n=t+i/e,a=s?this.lastLevelLoadSec:0;return n+a}onLevelLoaded(t,e){const i=this.hls.config,{total:s,bwEstimate:n}=e.stats;j(s)&&j(n)&&(this.lastLevelLoadSec=8*s/n),e.details.live?this.bwEstimator.update(i.abrEwmaSlowLive,i.abrEwmaFastLive):this.bwEstimator.update(i.abrEwmaSlowVoD,i.abrEwmaFastVoD)}_abandonRulesCheck(){const{fragCurrent:t,partCurrent:e,hls:i}=this,{autoLevelEnabled:s,media:n}=i;if(!t||!n)return;const a=performance.now(),o=e?e.stats:t.stats,l=e?e.duration:t.duration,h=a-o.loading.start;if(o.aborted||o.loaded&&o.loaded===o.total||t.level===0){this.clearTimer(),this._nextAutoLevel=-1;return}if(!s||n.paused||!n.playbackRate||!n.readyState)return;const d=i.mainForwardBufferInfo;if(d===null)return;const c=this.bwEstimator.getEstimateTTFB(),u=Math.abs(n.playbackRate);if(h<=Math.max(c,1e3*(l/(u*2))))return;const f=d.len/u;if(f>=2*l/u)return;const p=o.loading.first?o.loading.first-o.loading.start:-1,g=o.loaded&&p>-1,v=this.bwEstimator.getEstimate(),{levels:E,minAutoLevel:T}=i,A=E[t.level],y=o.total||Math.max(o.loaded,Math.round(l*A.maxBitrate/8));let b=h-p;b<1&&g&&(b=Math.min(h,o.loaded*8/v));const S=g?o.loaded*1e3/b:0,R=S?(y-o.loaded)/S:y*8/v+c/1e3;if(R<=f)return;const D=S?S*8:v;let _=Number.POSITIVE_INFINITY,I;for(I=t.level-1;I>T;I--){const N=E[I].maxBitrate;if(_=this.getTimeToLoadFrag(c/1e3,D,l*N,!E[I].details),_<f)break}_>=R||_>l*10||(i.nextLoadLevel=I,g?this.bwEstimator.sample(h-Math.min(c,p),o.loaded):this.bwEstimator.sampleTTFB(h),this.clearTimer(),L.warn(`[abr] Fragment ${t.sn}${e?" part "+e.index:""} of level ${t.level} is loading too slowly;
154
+ initSegmentChange: ${M}`);const I=new mm(i,s,e,o,c);this.configureTransmuxer(I)}if(this.frag=n,this.part=a,this.workerContext)this.workerContext.worker.postMessage({cmd:"demux",data:t,decryptdata:g,chunkMeta:h,state:D},t instanceof ArrayBuffer?[t]:[]);else if(f){const I=f.push(t,g,h,D);Er(I)?(f.async=!0,I.then(G=>{this.handleTransmuxComplete(G)}).catch(G=>{this.transmuxerError(G,h,"transmuxer-interface push error")})):(f.async=!1,this.handleTransmuxComplete(I))}}flush(t){t.transmuxing.start=self.performance.now();const{transmuxer:e}=this;if(this.workerContext)this.workerContext.worker.postMessage({cmd:"flush",chunkMeta:t});else if(e){let i=e.flush(t);Er(i)||e.async?(Er(i)||(i=Promise.resolve(i)),i.then(s=>{this.handleFlushResult(s,t)}).catch(s=>{this.transmuxerError(s,t,"transmuxer-interface flush error")})):this.handleFlushResult(i,t)}}transmuxerError(t,e,i){this.hls&&(this.error=t,this.hls.trigger(m.ERROR,{type:Q.MEDIA_ERROR,details:$.FRAG_PARSING_ERROR,chunkMeta:e,fatal:!1,error:t,err:t,reason:i}))}handleFlushResult(t,e){t.forEach(i=>{this.handleTransmuxComplete(i)}),this.onFlush(e)}onWorkerMessage(t){const e=t.data,i=this.hls;switch(e.event){case"init":{var s;const n=(s=this.workerContext)==null?void 0:s.objectURL;n&&self.URL.revokeObjectURL(n);break}case"transmuxComplete":{this.handleTransmuxComplete(e.data);break}case"flush":{this.onFlush(e.data);break}case"workerLog":_[e.data.logType]&&_[e.data.logType](e.data.message);break;default:{e.data=e.data||{},e.data.frag=this.frag,e.data.id=this.id,i.trigger(e.event,e.data);break}}}configureTransmuxer(t){const{transmuxer:e}=this;this.workerContext?this.workerContext.worker.postMessage({cmd:"configure",config:t}):e&&e.configure(t)}handleTransmuxComplete(t){t.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(t)}}const Em=250,sa=2,bm=.1,Tm=.05;class Am{constructor(t,e,i,s){this.config=void 0,this.media=null,this.fragmentTracker=void 0,this.hls=void 0,this.nudgeRetry=0,this.stallReported=!1,this.stalled=null,this.moved=!1,this.seeking=!1,this.config=t,this.media=e,this.fragmentTracker=i,this.hls=s}destroy(){this.media=null,this.hls=this.fragmentTracker=null}poll(t,e){const{config:i,media:s,stalled:n}=this;if(s===null)return;const{currentTime:a,seeking:o}=s,l=this.seeking&&!o,h=!this.seeking&&o;if(this.seeking=o,a!==t){if(this.moved=!0,n!==null){if(this.stallReported){const E=self.performance.now()-n;_.warn(`playback not stuck anymore @${a}, after ${Math.round(E)}ms`),this.stallReported=!1}this.stalled=null,this.nudgeRetry=0}return}if(h||l){this.stalled=null;return}if(s.paused&&!o||s.ended||s.playbackRate===0||!Et.getBuffered(s).length)return;const c=Et.bufferInfo(s,a,0),d=c.len>0,u=c.nextStart||0;if(!d&&!u)return;if(o){const E=c.len>sa,A=!u||e&&e.start<=a||u-a>sa&&!this.fragmentTracker.getPartialFragment(a);if(E||A)return;this.moved=!1}if(!this.moved&&this.stalled!==null){var f;const E=Math.max(u,c.start||0)-a,A=this.hls.levels?this.hls.levels[this.hls.currentLevel]:null,L=!(A==null||(f=A.details)==null)&&f.live?A.details.targetduration*2:sa,y=this.fragmentTracker.getPartialFragment(a);if(E>0&&(E<=L||y)){this._trySkipBufferHole(y);return}}const p=self.performance.now();if(n===null){this.stalled=p;return}const g=p-n;if(!o&&g>=Em&&(this._reportStall(c),!this.media))return;const v=Et.bufferInfo(s,a,i.maxBufferHole);this._tryFixBufferStall(v,g)}_tryFixBufferStall(t,e){const{config:i,fragmentTracker:s,media:n}=this;if(n===null)return;const a=n.currentTime,o=s.getPartialFragment(a);o&&(this._trySkipBufferHole(o)||!this.media)||(t.len>i.maxBufferHole||t.nextStart&&t.nextStart-a<i.maxBufferHole)&&e>i.highBufferWatchdogPeriod*1e3&&(_.warn("Trying to nudge playhead over buffer-hole"),this.stalled=null,this._tryNudgeBuffer())}_reportStall(t){const{hls:e,media:i,stallReported:s}=this;if(!s&&i){this.stallReported=!0;const n=new Error(`Playback stalling at @${i.currentTime} due to low buffer (${JSON.stringify(t)})`);_.warn(n.message),e.trigger(m.ERROR,{type:Q.MEDIA_ERROR,details:$.BUFFER_STALLED_ERROR,fatal:!1,error:n,buffer:t.len})}}_trySkipBufferHole(t){const{config:e,hls:i,media:s}=this;if(s===null)return 0;const n=s.currentTime,a=Et.bufferInfo(s,n,0),o=n<a.start?a.start:a.nextStart;if(o){const l=a.len<=e.maxBufferHole,h=a.len>0&&a.len<1&&s.readyState<3,c=o-n;if(c>0&&(l||h)){if(c>e.maxBufferHole){const{fragmentTracker:u}=this;let f=!1;if(n===0){const p=u.getAppendedFrag(0,Z.MAIN);p&&o<p.end&&(f=!0)}if(!f){const p=t||u.getAppendedFrag(n,Z.MAIN);if(p){let g=!1,v=p.end;for(;v<o;){const E=u.getPartialFragment(v);if(E)v+=E.duration;else{g=!0;break}}if(g)return 0}}}const d=Math.max(o+Tm,n+bm);if(_.warn(`skipping hole, adjusting currentTime from ${n} to ${d}`),this.moved=!0,this.stalled=null,s.currentTime=d,t&&!t.gap){const u=new Error(`fragment loaded with buffer holes, seeking from ${n} to ${d}`);i.trigger(m.ERROR,{type:Q.MEDIA_ERROR,details:$.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:u,reason:u.message,frag:t})}return d}}return 0}_tryNudgeBuffer(){const{config:t,hls:e,media:i,nudgeRetry:s}=this;if(i===null)return;const n=i.currentTime;if(this.nudgeRetry++,s<t.nudgeMaxRetry){const a=n+(s+1)*t.nudgeOffset,o=new Error(`Nudging 'currentTime' from ${n} to ${a}`);_.warn(o.message),i.currentTime=a,e.trigger(m.ERROR,{type:Q.MEDIA_ERROR,details:$.BUFFER_NUDGE_ON_STALL,error:o,fatal:!1})}else{const a=new Error(`Playhead still not moving while enough data buffered @${n} after ${t.nudgeMaxRetry} nudges`);_.error(a.message),e.trigger(m.ERROR,{type:Q.MEDIA_ERROR,details:$.BUFFER_STALLED_ERROR,error:a,fatal:!0})}}}const wm=100;class Sm extends Wn{constructor(t,e,i){super(t,e,i,"[stream-controller]",Z.MAIN),this.audioCodecSwap=!1,this.gapController=null,this.level=-1,this._forceStartLoad=!1,this.altAudio=!1,this.audioOnly=!1,this.fragPlaying=null,this.onvplaying=null,this.onvseeked=null,this.fragLastKbps=0,this.couldBacktrack=!1,this.backtrackFragment=null,this.audioCodecSwitch=!1,this.videoBuffer=null,this._registerListeners()}_registerListeners(){const{hls:t}=this;t.on(m.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(m.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(m.MANIFEST_LOADING,this.onManifestLoading,this),t.on(m.MANIFEST_PARSED,this.onManifestParsed,this),t.on(m.LEVEL_LOADING,this.onLevelLoading,this),t.on(m.LEVEL_LOADED,this.onLevelLoaded,this),t.on(m.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),t.on(m.ERROR,this.onError,this),t.on(m.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on(m.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),t.on(m.BUFFER_CREATED,this.onBufferCreated,this),t.on(m.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on(m.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(m.FRAG_BUFFERED,this.onFragBuffered,this)}_unregisterListeners(){const{hls:t}=this;t.off(m.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(m.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(m.MANIFEST_LOADING,this.onManifestLoading,this),t.off(m.MANIFEST_PARSED,this.onManifestParsed,this),t.off(m.LEVEL_LOADED,this.onLevelLoaded,this),t.off(m.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),t.off(m.ERROR,this.onError,this),t.off(m.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off(m.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),t.off(m.BUFFER_CREATED,this.onBufferCreated,this),t.off(m.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off(m.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(m.FRAG_BUFFERED,this.onFragBuffered,this)}onHandlerDestroying(){this._unregisterListeners(),this.onMediaDetaching()}startLoad(t){if(this.levels){const{lastCurrentTime:e,hls:i}=this;if(this.stopLoad(),this.setInterval(wm),this.level=-1,!this.startFragRequested){let s=i.startLevel;s===-1&&(i.config.testBandwidth&&this.levels.length>1?(s=0,this.bitrateTest=!0):s=i.nextAutoLevel),this.level=i.nextLoadLevel=s,this.loadedmetadata=!1}e>0&&t===-1&&(this.log(`Override startPosition with lastCurrentTime @${e.toFixed(3)}`),t=e),this.state=B.IDLE,this.nextLoadPosition=this.startPosition=this.lastCurrentTime=t,this.tick()}else this._forceStartLoad=!0,this.state=B.STOPPED}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case B.WAITING_LEVEL:{var t;const{levels:i,level:s}=this,n=i==null||(t=i[s])==null?void 0:t.details;if(n&&(!n.live||this.levelLastLoaded===this.level)){if(this.waitForCdnTuneIn(n))break;this.state=B.IDLE;break}else if(this.hls.nextLoadLevel!==this.level){this.state=B.IDLE;break}break}case B.FRAG_LOADING_WAITING_RETRY:{var e;const i=self.performance.now(),s=this.retryDate;(!s||i>=s||(e=this.media)!=null&&e.seeking)&&(this.resetStartWhenNotLoaded(this.level),this.state=B.IDLE)}break}this.state===B.IDLE&&this.doTickIdle(),this.onTickEnd()}onTickEnd(){super.onTickEnd(),this.checkBuffer(),this.checkFragmentChanged()}doTickIdle(){const{hls:t,levelLastLoaded:e,levels:i,media:s}=this,{config:n,nextLoadLevel:a}=t;if(e===null||!s&&(this.startFragRequested||!n.startFragPrefetch)||this.altAudio&&this.audioOnly||!(i!=null&&i[a]))return;const o=i[a],l=this.getMainFwdBufferInfo();if(l===null)return;const h=this.getLevelDetails();if(h&&this._streamEnded(l,h)){const v={};this.altAudio&&(v.type="video"),this.hls.trigger(m.BUFFER_EOS,v),this.state=B.ENDED;return}t.loadLevel!==a&&t.manualLevel===-1&&this.log(`Adapting to level ${a} from level ${this.level}`),this.level=t.nextLoadLevel=a;const c=o.details;if(!c||this.state===B.WAITING_LEVEL||c.live&&this.levelLastLoaded!==a){this.level=a,this.state=B.WAITING_LEVEL;return}const d=l.len,u=this.getMaxBufferLength(o.maxBitrate);if(d>=u)return;this.backtrackFragment&&this.backtrackFragment.start>l.end&&(this.backtrackFragment=null);const f=this.backtrackFragment?this.backtrackFragment.start:l.end;let p=this.getNextFragment(f,c);if(this.couldBacktrack&&!this.fragPrevious&&p&&p.sn!=="initSegment"&&this.fragmentTracker.getState(p)!==$t.OK){var g;const v=((g=this.backtrackFragment)!=null?g:p).sn-c.startSN,E=c.fragments[v-1];E&&p.cc===E.cc&&(p=E,this.fragmentTracker.removeFragment(E))}else this.backtrackFragment&&l.len&&(this.backtrackFragment=null);if(p&&this.isLoopLoading(p,f)){if(!p.gap){const v=this.audioOnly&&!this.altAudio?mt.AUDIO:mt.VIDEO,E=(v===mt.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;E&&this.afterBufferFlushed(E,v,Z.MAIN)}p=this.getNextFragmentLoopLoading(p,c,l,Z.MAIN,u)}p&&(p.initSegment&&!p.initSegment.data&&!this.bitrateTest&&(p=p.initSegment),this.loadFragment(p,o,f))}loadFragment(t,e,i){const s=this.fragmentTracker.getState(t);this.fragCurrent=t,s===$t.NOT_LOADED||s===$t.PARTIAL?t.sn==="initSegment"?this._loadInitSegment(t,e):this.bitrateTest?(this.log(`Fragment ${t.sn} of level ${t.level} is being downloaded to test bitrate and will not be buffered`),this._loadBitrateTestFrag(t,e)):(this.startFragRequested=!0,super.loadFragment(t,e,i)):this.clearTrackerIfNeeded(t)}getBufferedFrag(t){return this.fragmentTracker.getBufferedFrag(t,Z.MAIN)}followingBufferedFrag(t){return t?this.getBufferedFrag(t.end+.5):null}immediateLevelSwitch(){this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY)}nextLevelSwitch(){const{levels:t,media:e}=this;if(e!=null&&e.readyState){let i;const s=this.getAppendedFrag(e.currentTime);s&&s.start>1&&this.flushMainBuffer(0,s.start-1);const n=this.getLevelDetails();if(n!=null&&n.live){const o=this.getMainFwdBufferInfo();if(!o||o.len<n.targetduration*2)return}if(!e.paused&&t){const o=this.hls.nextLoadLevel,l=t[o],h=this.fragLastKbps;h&&this.fragCurrent?i=this.fragCurrent.duration*l.maxBitrate/(1e3*h)+1:i=0}else i=0;const a=this.getBufferedFrag(e.currentTime+i);if(a){const o=this.followingBufferedFrag(a);if(o){this.abortCurrentFrag();const l=o.maxStartPTS?o.maxStartPTS:o.start,h=o.duration,c=Math.max(a.end,l+Math.min(Math.max(h-this.config.maxFragLookUpTolerance,h*.5),h*.75));this.flushMainBuffer(c,Number.POSITIVE_INFINITY)}}}}abortCurrentFrag(){const t=this.fragCurrent;switch(this.fragCurrent=null,this.backtrackFragment=null,t&&(t.abortRequests(),this.fragmentTracker.removeFragment(t)),this.state){case B.KEY_LOADING:case B.FRAG_LOADING:case B.FRAG_LOADING_WAITING_RETRY:case B.PARSING:case B.PARSED:this.state=B.IDLE;break}this.nextLoadPosition=this.getLoadPosition()}flushMainBuffer(t,e){super.flushMainBuffer(t,e,this.altAudio?"video":null)}onMediaAttached(t,e){super.onMediaAttached(t,e);const i=e.media;this.onvplaying=this.onMediaPlaying.bind(this),this.onvseeked=this.onMediaSeeked.bind(this),i.addEventListener("playing",this.onvplaying),i.addEventListener("seeked",this.onvseeked),this.gapController=new Am(this.config,i,this.fragmentTracker,this.hls)}onMediaDetaching(){const{media:t}=this;t&&this.onvplaying&&this.onvseeked&&(t.removeEventListener("playing",this.onvplaying),t.removeEventListener("seeked",this.onvseeked),this.onvplaying=this.onvseeked=null,this.videoBuffer=null),this.fragPlaying=null,this.gapController&&(this.gapController.destroy(),this.gapController=null),super.onMediaDetaching()}onMediaPlaying(){this.tick()}onMediaSeeked(){const t=this.media,e=t?t.currentTime:null;q(e)&&this.log(`Media seeked to ${e.toFixed(3)}`);const i=this.getMainFwdBufferInfo();if(i===null||i.len===0){this.warn(`Main forward buffer length on "seeked" event ${i?i.len:"empty"})`);return}this.tick()}onManifestLoading(){this.log("Trigger BUFFER_RESET"),this.hls.trigger(m.BUFFER_RESET,void 0),this.fragmentTracker.removeAllFragments(),this.couldBacktrack=!1,this.startPosition=this.lastCurrentTime=0,this.levels=this.fragPlaying=this.backtrackFragment=null,this.altAudio=this.audioOnly=!1}onManifestParsed(t,e){let i=!1,s=!1,n;e.levels.forEach(a=>{n=a.audioCodec,n&&(n.indexOf("mp4a.40.2")!==-1&&(i=!0),n.indexOf("mp4a.40.5")!==-1&&(s=!0))}),this.audioCodecSwitch=i&&s&&!Ng(),this.audioCodecSwitch&&this.log("Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC"),this.levels=e.levels,this.startFragRequested=!1}onLevelLoading(t,e){const{levels:i}=this;if(!i||this.state!==B.IDLE)return;const s=i[e.level];(!s.details||s.details.live&&this.levelLastLoaded!==e.level||this.waitForCdnTuneIn(s.details))&&(this.state=B.WAITING_LEVEL)}onLevelLoaded(t,e){var i;const{levels:s}=this,n=e.level,a=e.details,o=a.totalduration;if(!s){this.warn(`Levels were reset while loading level ${n}`);return}this.log(`Level ${n} loaded [${a.startSN},${a.endSN}]${a.lastPartSn?`[part-${a.lastPartSn}-${a.lastPartIndex}]`:""}, cc [${a.startCC}, ${a.endCC}] duration:${o}`);const l=s[n],h=this.fragCurrent;h&&(this.state===B.FRAG_LOADING||this.state===B.FRAG_LOADING_WAITING_RETRY)&&(h.level!==e.level||h.urlId!==l.urlId)&&h.loader&&this.abortCurrentFrag();let c=0;if(a.live||(i=l.details)!=null&&i.live){if(this.checkLiveUpdate(a),a.deltaUpdateFailed)return;c=this.alignPlaylists(a,l.details)}if(l.details=a,this.levelLastLoaded=n,this.hls.trigger(m.LEVEL_UPDATED,{details:a,level:n}),this.state===B.WAITING_LEVEL){if(this.waitForCdnTuneIn(a))return;this.state=B.IDLE}this.startFragRequested?a.live&&this.synchronizeToLiveEdge(a):this.setStartPosition(a,c),this.tick()}_handleFragmentLoadProgress(t){var e;const{frag:i,part:s,payload:n}=t,{levels:a}=this;if(!a){this.warn(`Levels were reset while fragment load was in progress. Fragment ${i.sn} of level ${i.level} will not be buffered`);return}const o=a[i.level],l=o.details;if(!l){this.warn(`Dropping fragment ${i.sn} of level ${i.level} after level details were reset`),this.fragmentTracker.removeFragment(i);return}const h=o.videoCodec,c=l.PTSKnown||!l.live,d=(e=i.initSegment)==null?void 0:e.data,u=this._getAudioCodec(o),f=this.transmuxer=this.transmuxer||new Hh(this.hls,Z.MAIN,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),p=s?s.index:-1,g=p!==-1,v=new Vn(i.level,i.sn,i.stats.chunkCount,n.byteLength,p,g),E=this.initPTS[i.cc];f.push(n,d,u,h,i,s,l.totalduration,c,v,E)}onAudioTrackSwitching(t,e){const i=this.altAudio;if(!e.url){if(this.mediaBuffer!==this.media){this.log("Switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;const n=this.fragCurrent;n&&(this.log("Switching to main audio track, cancel main fragment load"),n.abortRequests(),this.fragmentTracker.removeFragment(n)),this.resetTransmuxer(),this.resetLoadingState()}else this.audioOnly&&this.resetTransmuxer();const s=this.hls;i&&(s.trigger(m.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null}),this.fragmentTracker.removeAllFragments()),s.trigger(m.AUDIO_TRACK_SWITCHED,e)}}onAudioTrackSwitched(t,e){const i=e.id,s=!!this.hls.audioTracks[i].url;if(s){const n=this.videoBuffer;n&&this.mediaBuffer!==n&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=n)}this.altAudio=s,this.tick()}onBufferCreated(t,e){const i=e.tracks;let s,n,a=!1;for(const o in i){const l=i[o];if(l.id==="main"){if(n=o,s=l,o==="video"){const h=i[o];h&&(this.videoBuffer=h.buffer)}}else a=!0}a&&s?(this.log(`Alternate track found, use ${n}.buffered to schedule main fragment loading`),this.mediaBuffer=s.buffer):this.mediaBuffer=this.media}onFragBuffered(t,e){const{frag:i,part:s}=e;if(i&&i.type!==Z.MAIN)return;if(this.fragContextChanged(i)){this.warn(`Fragment ${i.sn}${s?" p: "+s.index:""} of level ${i.level} finished buffering, but was aborted. state: ${this.state}`),this.state===B.PARSED&&(this.state=B.IDLE);return}const n=s?s.stats:i.stats;this.fragLastKbps=Math.round(8*n.total/(n.buffering.end-n.loading.first)),i.sn!=="initSegment"&&(this.fragPrevious=i),this.fragBufferedComplete(i,s)}onError(t,e){var i;if(e.fatal){this.state=B.ERROR;return}switch(e.details){case $.FRAG_GAP:case $.FRAG_PARSING_ERROR:case $.FRAG_DECRYPT_ERROR:case $.FRAG_LOAD_ERROR:case $.FRAG_LOAD_TIMEOUT:case $.KEY_LOAD_ERROR:case $.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(Z.MAIN,e);break;case $.LEVEL_LOAD_ERROR:case $.LEVEL_LOAD_TIMEOUT:case $.LEVEL_PARSING_ERROR:!e.levelRetry&&this.state===B.WAITING_LEVEL&&((i=e.context)==null?void 0:i.type)===ct.LEVEL&&(this.state=B.IDLE);break;case $.BUFFER_FULL_ERROR:if(!e.parent||e.parent!=="main")return;this.reduceLengthAndFlushBuffer(e)&&this.flushMainBuffer(0,Number.POSITIVE_INFINITY);break;case $.INTERNAL_EXCEPTION:this.recoverWorkerError(e);break}}checkBuffer(){const{media:t,gapController:e}=this;if(!(!t||!e||!t.readyState)){if(this.loadedmetadata||!Et.getBuffered(t).length){const i=this.state!==B.IDLE?this.fragCurrent:null;e.poll(this.lastCurrentTime,i)}this.lastCurrentTime=t.currentTime}}onFragLoadEmergencyAborted(){this.state=B.IDLE,this.loadedmetadata||(this.startFragRequested=!1,this.nextLoadPosition=this.startPosition),this.tickImmediate()}onBufferFlushed(t,{type:e}){if(e!==mt.AUDIO||this.audioOnly&&!this.altAudio){const i=(e===mt.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;this.afterBufferFlushed(i,e,Z.MAIN)}}onLevelsUpdated(t,e){this.levels=e.levels}swapAudioCodec(){this.audioCodecSwap=!this.audioCodecSwap}seekToStartPos(){const{media:t}=this;if(!t)return;const e=t.currentTime;let i=this.startPosition;if(i>=0&&e<i){if(t.seeking){this.log(`could not seek to ${i}, already seeking at ${e}`);return}const s=Et.getBuffered(t),n=(s.length?s.start(0):0)-i;n>0&&(n<this.config.maxBufferHole||n<this.config.maxFragLookUpTolerance)&&(this.log(`adjusting start position by ${n} to match buffer start`),i+=n,this.startPosition=i),this.log(`seek to target start position ${i} from current time ${e}`),t.currentTime=i}}_getAudioCodec(t){let e=this.config.defaultAudioCodec||t.audioCodec;return this.audioCodecSwap&&e&&(this.log("Swapping audio codec"),e.indexOf("mp4a.40.5")!==-1?e="mp4a.40.2":e="mp4a.40.5"),e}_loadBitrateTestFrag(t,e){t.bitrateTest=!0,this._doFragLoad(t,e).then(i=>{const{hls:s}=this;if(!i||this.fragContextChanged(t))return;e.fragmentError=0,this.state=B.IDLE,this.startFragRequested=!1,this.bitrateTest=!1;const n=t.stats;n.parsing.start=n.parsing.end=n.buffering.start=n.buffering.end=self.performance.now(),s.trigger(m.FRAG_LOADED,i),t.bitrateTest=!1})}_handleTransmuxComplete(t){var e;const i="main",{hls:s}=this,{remuxResult:n,chunkMeta:a}=t,o=this.getCurrentContext(a);if(!o){this.resetWhenMissingContext(a);return}const{frag:l,part:h,level:c}=o,{video:d,text:u,id3:f,initSegment:p}=n,{details:g}=c,v=this.altAudio?void 0:n.audio;if(this.fragContextChanged(l)){this.fragmentTracker.removeFragment(l);return}if(this.state=B.PARSING,p){if(p!=null&&p.tracks){const L=l.initSegment||l;this._bufferInitSegment(c,p.tracks,L,a),s.trigger(m.FRAG_PARSING_INIT_SEGMENT,{frag:L,id:i,tracks:p.tracks})}const E=p.initPTS,A=p.timescale;q(E)&&(this.initPTS[l.cc]={baseTime:E,timescale:A},s.trigger(m.INIT_PTS_FOUND,{frag:l,id:i,initPTS:E,timescale:A}))}if(d&&g&&l.sn!=="initSegment"){const E=g.fragments[l.sn-1-g.startSN],A=l.sn===g.startSN,L=!E||l.cc>E.cc;if(n.independent!==!1){const{startPTS:y,endPTS:S,startDTS:R,endDTS:C}=d;if(h)h.elementaryStreams[d.type]={startPTS:y,endPTS:S,startDTS:R,endDTS:C};else if(d.firstKeyFrame&&d.independent&&a.id===1&&!L&&(this.couldBacktrack=!0),d.dropped&&d.independent){const M=this.getMainFwdBufferInfo(),D=(M?M.end:this.getLoadPosition())+this.config.maxBufferHole,I=d.firstKeyFramePTS?d.firstKeyFramePTS:y;if(!A&&D<I-this.config.maxBufferHole&&!L){this.backtrack(l);return}else L&&(l.gap=!0);l.setElementaryStreamInfo(d.type,l.start,S,l.start,C,!0)}l.setElementaryStreamInfo(d.type,y,S,R,C),this.backtrackFragment&&(this.backtrackFragment=l),this.bufferFragmentData(d,l,h,a,A||L)}else if(A||L)l.gap=!0;else{this.backtrack(l);return}}if(v){const{startPTS:E,endPTS:A,startDTS:L,endDTS:y}=v;h&&(h.elementaryStreams[mt.AUDIO]={startPTS:E,endPTS:A,startDTS:L,endDTS:y}),l.setElementaryStreamInfo(mt.AUDIO,E,A,L,y),this.bufferFragmentData(v,l,h,a)}if(g&&f!=null&&(e=f.samples)!=null&&e.length){const E={id:i,frag:l,details:g,samples:f.samples};s.trigger(m.FRAG_PARSING_METADATA,E)}if(g&&u){const E={id:i,frag:l,details:g,samples:u.samples};s.trigger(m.FRAG_PARSING_USERDATA,E)}}_bufferInitSegment(t,e,i,s){if(this.state!==B.PARSING)return;this.audioOnly=!!e.audio&&!e.video,this.altAudio&&!this.audioOnly&&delete e.audio;const{audio:n,video:a,audiovideo:o}=e;if(n){let l=t.audioCodec;const h=navigator.userAgent.toLowerCase();this.audioCodecSwitch&&(l&&(l.indexOf("mp4a.40.5")!==-1?l="mp4a.40.2":l="mp4a.40.5"),n.metadata.channelCount!==1&&h.indexOf("firefox")===-1&&(l="mp4a.40.5")),h.indexOf("android")!==-1&&n.container!=="audio/mpeg"&&(l="mp4a.40.2",this.log(`Android: force audio codec to ${l}`)),t.audioCodec&&t.audioCodec!==l&&this.log(`Swapping manifest audio codec "${t.audioCodec}" for "${l}"`),n.levelCodec=l,n.id="main",this.log(`Init audio buffer, container:${n.container}, codecs[selected/level/parsed]=[${l||""}/${t.audioCodec||""}/${n.codec}]`)}a&&(a.levelCodec=t.videoCodec,a.id="main",this.log(`Init video buffer, container:${a.container}, codecs[level/parsed]=[${t.videoCodec||""}/${a.codec}]`)),o&&this.log(`Init audiovideo buffer, container:${o.container}, codecs[level/parsed]=[${t.attrs.CODECS||""}/${o.codec}]`),this.hls.trigger(m.BUFFER_CODECS,e),Object.keys(e).forEach(l=>{const h=e[l].initSegment;h!=null&&h.byteLength&&this.hls.trigger(m.BUFFER_APPENDING,{type:l,data:h,frag:i,part:null,chunkMeta:s,parent:i.type})}),this.tick()}getMainFwdBufferInfo(){return this.getFwdBufferInfo(this.mediaBuffer?this.mediaBuffer:this.media,Z.MAIN)}backtrack(t){this.couldBacktrack=!0,this.backtrackFragment=t,this.resetTransmuxer(),this.flushBufferGap(t),this.fragmentTracker.removeFragment(t),this.fragPrevious=null,this.nextLoadPosition=t.start,this.state=B.IDLE}checkFragmentChanged(){const t=this.media;let e=null;if(t&&t.readyState>1&&t.seeking===!1){const i=t.currentTime;if(Et.isBuffered(t,i)?e=this.getAppendedFrag(i):Et.isBuffered(t,i+.1)&&(e=this.getAppendedFrag(i+.1)),e){this.backtrackFragment=null;const s=this.fragPlaying,n=e.level;(!s||e.sn!==s.sn||s.level!==n||e.urlId!==s.urlId)&&(this.fragPlaying=e,this.hls.trigger(m.FRAG_CHANGED,{frag:e}),(!s||s.level!==n)&&this.hls.trigger(m.LEVEL_SWITCHED,{level:n}))}}}get nextLevel(){const t=this.nextBufferedFrag;return t?t.level:-1}get currentFrag(){const t=this.media;return t?this.fragPlaying||this.getAppendedFrag(t.currentTime):null}get currentProgramDateTime(){const t=this.media;if(t){const e=t.currentTime,i=this.currentFrag;if(i&&q(e)&&q(i.programDateTime)){const s=i.programDateTime+(e-i.start)*1e3;return new Date(s)}}return null}get currentLevel(){const t=this.currentFrag;return t?t.level:-1}get nextBufferedFrag(){const t=this.currentFrag;return t?this.followingBufferedFrag(t):null}get forceStartLoad(){return this._forceStartLoad}}class Di{constructor(t,e=0,i=0){this.halfLife=void 0,this.alpha_=void 0,this.estimate_=void 0,this.totalWeight_=void 0,this.halfLife=t,this.alpha_=t?Math.exp(Math.log(.5)/t):0,this.estimate_=e,this.totalWeight_=i}sample(t,e){const i=Math.pow(this.alpha_,t);this.estimate_=e*(1-i)+i*this.estimate_,this.totalWeight_+=t}getTotalWeight(){return this.totalWeight_}getEstimate(){if(this.alpha_){const t=1-Math.pow(this.alpha_,this.totalWeight_);if(t)return this.estimate_/t}return this.estimate_}}class Lm{constructor(t,e,i,s=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 Di(t),this.fast_=new Di(e),this.defaultTTFB_=s,this.ttfb_=new Di(t)}update(t,e){const{slow_:i,fast_:s,ttfb_:n}=this;i.halfLife!==t&&(this.slow_=new Di(t,i.getEstimate(),i.getTotalWeight())),s.halfLife!==e&&(this.fast_=new Di(e,s.getEstimate(),s.getTotalWeight())),n.halfLife!==t&&(this.ttfb_=new Di(t,n.getEstimate(),n.getTotalWeight()))}sample(t,e){t=Math.max(t,this.minDelayMs_);const i=8*e,s=t/1e3,n=i/s;this.fast_.sample(s,n),this.slow_.sample(s,n)}sampleTTFB(t){const e=t/1e3,i=Math.sqrt(2)*Math.exp(-Math.pow(e,2)/2);this.ttfb_.sample(i,Math.max(t,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_}destroy(){}}class Rm{constructor(t){this.hls=void 0,this.lastLevelLoadSec=0,this.lastLoadedFragLevel=0,this._nextAutoLevel=-1,this.timer=-1,this.onCheck=this._abandonRulesCheck.bind(this),this.fragCurrent=null,this.partCurrent=null,this.bitrateTestDelay=0,this.bwEstimator=void 0,this.hls=t;const e=t.config;this.bwEstimator=new Lm(e.abrEwmaSlowVoD,e.abrEwmaFastVoD,e.abrEwmaDefaultEstimate),this.registerListeners()}registerListeners(){const{hls:t}=this;t.on(m.FRAG_LOADING,this.onFragLoading,this),t.on(m.FRAG_LOADED,this.onFragLoaded,this),t.on(m.FRAG_BUFFERED,this.onFragBuffered,this),t.on(m.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(m.LEVEL_LOADED,this.onLevelLoaded,this)}unregisterListeners(){const{hls:t}=this;t.off(m.FRAG_LOADING,this.onFragLoading,this),t.off(m.FRAG_LOADED,this.onFragLoaded,this),t.off(m.FRAG_BUFFERED,this.onFragBuffered,this),t.off(m.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(m.LEVEL_LOADED,this.onLevelLoaded,this)}destroy(){this.unregisterListeners(),this.clearTimer(),this.hls=this.onCheck=null,this.fragCurrent=this.partCurrent=null}onFragLoading(t,e){var i;const s=e.frag;this.ignoreFragment(s)||(this.fragCurrent=s,this.partCurrent=(i=e.part)!=null?i:null,this.clearTimer(),this.timer=self.setInterval(this.onCheck,100))}onLevelSwitching(t,e){this.clearTimer()}getTimeToLoadFrag(t,e,i,s){const n=t+i/e,a=s?this.lastLevelLoadSec:0;return n+a}onLevelLoaded(t,e){const i=this.hls.config,{total:s,bwEstimate:n}=e.stats;q(s)&&q(n)&&(this.lastLevelLoadSec=8*s/n),e.details.live?this.bwEstimator.update(i.abrEwmaSlowLive,i.abrEwmaFastLive):this.bwEstimator.update(i.abrEwmaSlowVoD,i.abrEwmaFastVoD)}_abandonRulesCheck(){const{fragCurrent:t,partCurrent:e,hls:i}=this,{autoLevelEnabled:s,media:n}=i;if(!t||!n)return;const a=performance.now(),o=e?e.stats:t.stats,l=e?e.duration:t.duration,h=a-o.loading.start;if(o.aborted||o.loaded&&o.loaded===o.total||t.level===0){this.clearTimer(),this._nextAutoLevel=-1;return}if(!s||n.paused||!n.playbackRate||!n.readyState)return;const c=i.mainForwardBufferInfo;if(c===null)return;const d=this.bwEstimator.getEstimateTTFB(),u=Math.abs(n.playbackRate);if(h<=Math.max(d,1e3*(l/(u*2))))return;const f=c.len/u;if(f>=2*l/u)return;const p=o.loading.first?o.loading.first-o.loading.start:-1,g=o.loaded&&p>-1,v=this.bwEstimator.getEstimate(),{levels:E,minAutoLevel:A}=i,L=E[t.level],y=o.total||Math.max(o.loaded,Math.round(l*L.maxBitrate/8));let S=h-p;S<1&&g&&(S=Math.min(h,o.loaded*8/v));const R=g?o.loaded*1e3/S:0,C=R?(y-o.loaded)/R:y*8/v+d/1e3;if(C<=f)return;const M=R?R*8:v;let D=Number.POSITIVE_INFINITY,I;for(I=t.level-1;I>A;I--){const G=E[I].maxBitrate;if(D=this.getTimeToLoadFrag(d/1e3,M,l*G,!E[I].details),D<f)break}D>=C||D>l*10||(i.nextLoadLevel=I,g?this.bwEstimator.sample(h-Math.min(d,p),o.loaded):this.bwEstimator.sampleTTFB(h),this.clearTimer(),_.warn(`[abr] Fragment ${t.sn}${e?" part "+e.index:""} of level ${t.level} is loading too slowly;
166
155
  Time to underbuffer: ${f.toFixed(3)} s
167
- Estimated load time for current fragment: ${R.toFixed(3)} s
168
- Estimated load time for down switch fragment: ${_.toFixed(3)} s
156
+ Estimated load time for current fragment: ${C.toFixed(3)} s
157
+ Estimated load time for down switch fragment: ${D.toFixed(3)} s
169
158
  TTFB estimate: ${p}
170
- Current BW estimate: ${j(v)?(v/1024).toFixed(3):"Unknown"} Kb/s
159
+ Current BW estimate: ${q(v)?(v/1024).toFixed(3):"Unknown"} Kb/s
171
160
  New BW estimate: ${(this.bwEstimator.getEstimate()/1024).toFixed(3)} Kb/s
172
- Aborting and switching to level ${I}`),t.loader&&(this.fragCurrent=this.partCurrent=null,t.abortRequests()),i.trigger(m.FRAG_LOAD_EMERGENCY_ABORTED,{frag:t,part:e,stats:o}))}onFragLoaded(t,{frag:e,part:i}){const s=i?i.stats:e.stats;if(e.type===Y.MAIN&&this.bwEstimator.sampleTTFB(s.loading.first-s.loading.start),!this.ignoreFragment(e)){if(this.clearTimer(),this.lastLoadedFragLevel=e.level,this._nextAutoLevel=-1,this.hls.config.abrMaxWithRealBitrate){const n=i?i.duration:e.duration,a=this.hls.levels[e.level],o=(a.loaded?a.loaded.bytes:0)+s.loaded,l=(a.loaded?a.loaded.duration:0)+n;a.loaded={bytes:o,duration:l},a.realBitrate=Math.round(8*o/l)}if(e.bitrateTest){const n={stats:s,frag:e,part:i,id:e.type};this.onFragBuffered(m.FRAG_BUFFERED,n),e.bitrateTest=!1}}}onFragBuffered(t,e){const{frag:i,part:s}=e,n=s!=null&&s.stats.loaded?s.stats:i.stats;if(n.aborted||this.ignoreFragment(i))return;const 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.bwEstimator.getEstimate(),i.bitrateTest?this.bitrateTestDelay=a/1e3:this.bitrateTestDelay=0}ignoreFragment(t){return t.type!==Y.MAIN||t.sn==="initSegment"}clearTimer(){self.clearInterval(this.timer)}get nextAutoLevel(){const t=this._nextAutoLevel,e=this.bwEstimator;if(t!==-1&&!e.canEstimate())return t;let i=this.getNextABRAutoLevel();if(t!==-1){const s=this.hls.levels;if(s.length>Math.max(t,i)&&s[t].loadError<=s[i].loadError)return t}return t!==-1&&(i=Math.min(t,i)),i}getNextABRAutoLevel(){const{fragCurrent:t,partCurrent:e,hls:i}=this,{maxAutoLevel:s,config:n,minAutoLevel:a,media:o}=i,l=e?e.duration:t?t.duration:0,h=o&&o.playbackRate!==0?Math.abs(o.playbackRate):1,d=this.bwEstimator?this.bwEstimator.getEstimate():n.abrEwmaDefaultEstimate,c=i.mainForwardBufferInfo,u=(c?c.len:0)/h;let f=this.findBestLevel(d,a,s,u,n.abrBandWidthFactor,n.abrBandWidthUpFactor);if(f>=0)return f;L.trace(`[abr] ${u?"rebuffering expected":"buffer is empty"}, finding optimal quality level`);let p=l?Math.min(l,n.maxStarvationDelay):n.maxStarvationDelay,g=n.abrBandWidthFactor,v=n.abrBandWidthUpFactor;if(!u){const E=this.bitrateTestDelay;E&&(p=(l?Math.min(l,n.maxLoadingDelay):n.maxLoadingDelay)-E,L.trace(`[abr] bitrate test took ${Math.round(1e3*E)}ms, set first fragment max fetchDuration to ${Math.round(1e3*p)} ms`),g=v=1)}return f=this.findBestLevel(d,a,s,u+p,g,v),Math.max(f,0)}findBestLevel(t,e,i,s,n,a){var o;const{fragCurrent:l,partCurrent:h,lastLoadedFragLevel:d}=this,{levels:c}=this.hls,u=c[d],f=!!(u!=null&&(o=u.details)!=null&&o.live),p=u==null?void 0:u.codecSet,g=h?h.duration:l?l.duration:0,v=this.bwEstimator.getEstimateTTFB()/1e3;let E=e,T=-1;for(let A=i;A>=e;A--){const y=c[A];if(!y||p&&y.codecSet!==p){y&&(E=Math.min(A,E),T=Math.max(A,T));continue}T!==-1&&L.trace(`[abr] Skipped level(s) ${E}-${T} with CODECS:"${c[T].attrs.CODECS}"; not compatible with "${u.attrs.CODECS}"`);const b=y.details,S=(h?b==null?void 0:b.partTarget:b==null?void 0:b.averagetargetduration)||g;let R;A<=d?R=n*t:R=a*t;const D=c[A].maxBitrate,_=this.getTimeToLoadFrag(v,R,D*S,b===void 0);if(L.trace(`[abr] level:${A} adjustedbw-bitrate:${Math.round(R-D)} avgDuration:${S.toFixed(1)} maxFetchDuration:${s.toFixed(1)} fetchDuration:${_.toFixed(1)}`),R>D&&(_===0||!j(_)||f&&!this.bitrateTestDelay||_<s))return A}return-1}set nextAutoLevel(t){this._nextAutoLevel=t}}class dd{constructor(){this.chunks=[],this.dataLength=0}push(t){this.chunks.push(t),this.dataLength+=t.length}flush(){const{chunks:t,dataLength:e}=this;let i;if(t.length)t.length===1?i=t[0]:i=ev(t,e);else return new Uint8Array(0);return this.reset(),i}reset(){this.chunks.length=0,this.dataLength=0}}function ev(r,t){const e=new Uint8Array(t);let i=0;for(let s=0;s<r.length;s++){const n=r[s];e.set(n,i),i+=n.length}return e}const cd=100;class iv extends na{constructor(t,e,i){super(t,e,i,"[audio-stream-controller]",Y.AUDIO),this.videoBuffer=null,this.videoTrackCC=-1,this.waitingVideoCC=-1,this.bufferedTrack=null,this.switchingTrack=null,this.trackId=-1,this.waitingData=null,this.mainDetails=null,this.bufferFlushed=!1,this.cachedTrackLoadedData=null,this._registerListeners()}onHandlerDestroying(){this._unregisterListeners(),this.mainDetails=null,this.bufferedTrack=null,this.switchingTrack=null}_registerListeners(){const{hls:t}=this;t.on(m.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(m.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(m.MANIFEST_LOADING,this.onManifestLoading,this),t.on(m.LEVEL_LOADED,this.onLevelLoaded,this),t.on(m.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),t.on(m.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on(m.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.on(m.ERROR,this.onError,this),t.on(m.BUFFER_RESET,this.onBufferReset,this),t.on(m.BUFFER_CREATED,this.onBufferCreated,this),t.on(m.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on(m.INIT_PTS_FOUND,this.onInitPtsFound,this),t.on(m.FRAG_BUFFERED,this.onFragBuffered,this)}_unregisterListeners(){const{hls:t}=this;t.off(m.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(m.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(m.MANIFEST_LOADING,this.onManifestLoading,this),t.off(m.LEVEL_LOADED,this.onLevelLoaded,this),t.off(m.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),t.off(m.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off(m.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.off(m.ERROR,this.onError,this),t.off(m.BUFFER_RESET,this.onBufferReset,this),t.off(m.BUFFER_CREATED,this.onBufferCreated,this),t.off(m.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off(m.INIT_PTS_FOUND,this.onInitPtsFound,this),t.off(m.FRAG_BUFFERED,this.onFragBuffered,this)}onInitPtsFound(t,{frag:e,id:i,initPTS:s,timescale:n}){if(i==="main"){const a=e.cc;this.initPTS[e.cc]={baseTime:s,timescale:n},this.log(`InitPTS for cc: ${a} found from main: ${s}`),this.videoTrackCC=a,this.state===$.WAITING_INIT_PTS&&this.tick()}}startLoad(t){if(!this.levels){this.startPosition=t,this.state=$.STOPPED;return}const e=this.lastCurrentTime;this.stopLoad(),this.setInterval(cd),e>0&&t===-1?(this.log(`Override startPosition with lastCurrentTime @${e.toFixed(3)}`),t=e,this.state=$.IDLE):(this.loadedmetadata=!1,this.state=$.WAITING_TRACK),this.nextLoadPosition=this.startPosition=this.lastCurrentTime=t,this.tick()}doTick(){switch(this.state){case $.IDLE:this.doTickIdle();break;case $.WAITING_TRACK:{var t;const{levels:i,trackId:s}=this,n=i==null||(t=i[s])==null?void 0:t.details;if(n){if(this.waitForCdnTuneIn(n))break;this.state=$.WAITING_INIT_PTS}break}case $.FRAG_LOADING_WAITING_RETRY:{var e;const i=performance.now(),s=this.retryDate;(!s||i>=s||(e=this.media)!=null&&e.seeking)&&(this.log("RetryDate reached, switch back to IDLE state"),this.resetStartWhenNotLoaded(this.trackId),this.state=$.IDLE);break}case $.WAITING_INIT_PTS:{const i=this.waitingData;if(i){const{frag:s,part:n,cache:a,complete:o}=i;if(this.initPTS[s.cc]!==void 0){this.waitingData=null,this.waitingVideoCC=-1,this.state=$.FRAG_LOADING;const l=a.flush(),h={frag:s,part:n,payload:l,networkDetails:null};this._handleFragmentLoadProgress(h),o&&super._handleFragmentLoadComplete(h)}else if(this.videoTrackCC!==this.waitingVideoCC)this.log(`Waiting fragment cc (${s.cc}) cancelled because video is at cc ${this.videoTrackCC}`),this.clearWaitingFragment();else{const l=this.getLoadPosition(),h=lt.bufferInfo(this.mediaBuffer,l,this.config.maxBufferHole);Jn(h.end,this.config.maxFragLookUpTolerance,s)<0&&(this.log(`Waiting fragment cc (${s.cc}) @ ${s.start} cancelled because another fragment at ${h.end} is needed`),this.clearWaitingFragment())}}else this.state=$.IDLE}}this.onTickEnd()}clearWaitingFragment(){const t=this.waitingData;t&&(this.fragmentTracker.removeFragment(t.frag),this.waitingData=null,this.waitingVideoCC=-1,this.state=$.IDLE)}resetLoadingState(){this.clearWaitingFragment(),super.resetLoadingState()}onTickEnd(){const{media:t}=this;t!=null&&t.readyState&&(this.lastCurrentTime=t.currentTime)}doTickIdle(){const{hls:t,levels:e,media:i,trackId:s}=this,n=t.config;if(!(e!=null&&e[s])||!i&&(this.startFragRequested||!n.startFragPrefetch))return;const a=e[s],o=a.details;if(!o||o.live&&this.levelLastLoaded!==s||this.waitForCdnTuneIn(o)){this.state=$.WAITING_TRACK;return}const l=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&l&&(this.bufferFlushed=!1,this.afterBufferFlushed(l,at.AUDIO,Y.AUDIO));const h=this.getFwdBufferInfo(l,Y.AUDIO);if(h===null)return;const{bufferedTrack:d,switchingTrack:c}=this;if(!c&&this._streamEnded(h,o)){t.trigger(m.BUFFER_EOS,{type:"audio"}),this.state=$.ENDED;return}const u=this.getFwdBufferInfo(this.videoBuffer?this.videoBuffer:this.media,Y.MAIN),f=h.len,p=this.getMaxBufferLength(u==null?void 0:u.len);if(f>=p&&!c)return;const g=o.fragments[0].start;let v=h.end;if(c&&i){const y=this.getLoadPosition();d&&c.attrs!==d.attrs&&(v=y),o.PTSKnown&&y<g&&(h.end>g||h.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),i.currentTime=g+.05)}let E=this.getNextFragment(v,o),T=!1;if(E&&this.isLoopLoading(E,v)&&(T=!!E.gap,E=this.getNextFragmentLoopLoading(E,o,h,Y.MAIN,p)),!E){this.bufferFlushed=!0;return}const A=u&&E.start>u.end+o.targetduration;if(A||!(u!=null&&u.len)&&h.len){const y=this.getAppendedFrag(E.start,Y.MAIN);if(y===null||(T||(T=!!y.gap||!!A&&u.len===0),A&&!T||T&&h.nextStart&&h.nextStart<y.end))return}this.loadFragment(E,a,v)}getMaxBufferLength(t){const e=super.getMaxBufferLength();return t?Math.min(Math.max(e,t),this.config.maxMaxBufferLength):e}onMediaDetaching(){this.videoBuffer=null,super.onMediaDetaching()}onAudioTracksUpdated(t,{audioTracks:e}){this.resetTransmuxer(),this.levels=e.map(i=>new ps(i))}onAudioTrackSwitching(t,e){const i=!!e.url;this.trackId=e.id;const{fragCurrent:s}=this;s&&(s.abortRequests(),this.removeUnbufferedFrags(s.start)),this.resetLoadingState(),i?this.setInterval(cd):this.resetTransmuxer(),i?(this.switchingTrack=e,this.state=$.IDLE):(this.switchingTrack=null,this.bufferedTrack=e,this.state=$.STOPPED),this.tick()}onManifestLoading(){this.fragmentTracker.removeAllFragments(),this.startPosition=this.lastCurrentTime=0,this.bufferFlushed=!1,this.levels=this.mainDetails=this.waitingData=this.bufferedTrack=this.cachedTrackLoadedData=this.switchingTrack=null,this.startFragRequested=!1,this.trackId=this.videoTrackCC=this.waitingVideoCC=-1}onLevelLoaded(t,e){this.mainDetails=e.details,this.cachedTrackLoadedData!==null&&(this.hls.trigger(m.AUDIO_TRACK_LOADED,this.cachedTrackLoadedData),this.cachedTrackLoadedData=null)}onAudioTrackLoaded(t,e){var i;if(this.mainDetails==null){this.cachedTrackLoadedData=e;return}const{levels:s}=this,{details:n,id:a}=e;if(!s){this.warn(`Audio tracks were reset while loading level ${a}`);return}this.log(`Track ${a} loaded [${n.startSN},${n.endSN}]${n.lastPartSn?`[part-${n.lastPartSn}-${n.lastPartIndex}]`:""},duration:${n.totalduration}`);const o=s[a];let l=0;if(n.live||(i=o.details)!=null&&i.live){this.checkLiveUpdate(n);const h=this.mainDetails;if(n.deltaUpdateFailed||!h)return;!o.details&&n.hasProgramDateTime&&h.hasProgramDateTime?(Gh(n,h),l=n.fragments[0].start):l=this.alignPlaylists(n,o.details)}o.details=n,this.levelLastLoaded=a,!this.startFragRequested&&(this.mainDetails||!n.live)&&this.setStartPosition(o.details,l),this.state===$.WAITING_TRACK&&!this.waitForCdnTuneIn(n)&&(this.state=$.IDLE),this.tick()}_handleFragmentLoadProgress(t){var e;const{frag:i,part:s,payload:n}=t,{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}const h=l[o];if(!h){this.warn("Audio track is undefined on fragment load progress");return}const d=h.details;if(!d){this.warn("Audio track details undefined on fragment load progress"),this.removeUnbufferedFrags(i.start);return}const c=a.defaultAudioCodec||h.audioCodec||"mp4a.40.2";let u=this.transmuxer;u||(u=this.transmuxer=new hd(this.hls,Y.AUDIO,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));const f=this.initPTS[i.cc],p=(e=i.initSegment)==null?void 0:e.data;if(f!==void 0){const g=s?s.index:-1,v=g!==-1,E=new ia(i.level,i.sn,i.stats.chunkCount,n.byteLength,g,v);u.push(n,p,c,"",i,s,d.totalduration,!1,E,f)}else{this.log(`Unknown video PTS for cc ${i.cc}, waiting for video PTS before demuxing audio frag ${i.sn} of [${d.startSN} ,${d.endSN}],track ${o}`);const{cache:g}=this.waitingData=this.waitingData||{frag:i,part:s,cache:new dd,complete:!1};g.push(new Uint8Array(n)),this.waitingVideoCC=this.videoTrackCC,this.state=$.WAITING_INIT_PTS}}_handleFragmentLoadComplete(t){if(this.waitingData){this.waitingData.complete=!0;return}super._handleFragmentLoadComplete(t)}onBufferReset(){this.mediaBuffer=this.videoBuffer=null,this.loadedmetadata=!1}onBufferCreated(t,e){const i=e.tracks.audio;i&&(this.mediaBuffer=i.buffer||null),e.tracks.video&&(this.videoBuffer=e.tracks.video.buffer||null)}onFragBuffered(t,e){const{frag:i,part:s}=e;if(i.type!==Y.AUDIO){if(!this.loadedmetadata&&i.type===Y.MAIN){const n=this.videoBuffer||this.media;n&&lt.getBuffered(n).length&&(this.loadedmetadata=!0)}return}if(this.fragContextChanged(i)){this.warn(`Fragment ${i.sn}${s?" p: "+s.index:""} of level ${i.level} finished buffering, but was aborted. state: ${this.state}, audioSwitch: ${this.switchingTrack?this.switchingTrack.name:"false"}`);return}if(i.sn!=="initSegment"){this.fragPrevious=i;const n=this.switchingTrack;n&&(this.bufferedTrack=n,this.switchingTrack=null,this.hls.trigger(m.AUDIO_TRACK_SWITCHED,Gt({},n)))}this.fragBufferedComplete(i,s)}onError(t,e){var i;if(e.fatal){this.state=$.ERROR;return}switch(e.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(Y.AUDIO,e);break;case x.AUDIO_TRACK_LOAD_ERROR:case x.AUDIO_TRACK_LOAD_TIMEOUT:case x.LEVEL_PARSING_ERROR:!e.levelRetry&&this.state===$.WAITING_TRACK&&((i=e.context)==null?void 0:i.type)===rt.AUDIO_TRACK&&(this.state=$.IDLE);break;case x.BUFFER_FULL_ERROR:if(!e.parent||e.parent!=="audio")return;this.reduceLengthAndFlushBuffer(e)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case x.INTERNAL_EXCEPTION:this.recoverWorkerError(e);break}}onBufferFlushed(t,{type:e}){e===at.AUDIO&&(this.bufferFlushed=!0,this.state===$.ENDED&&(this.state=$.IDLE))}_handleTransmuxComplete(t){var e;const i="audio",{hls:s}=this,{remuxResult:n,chunkMeta:a}=t,o=this.getCurrentContext(a);if(!o){this.resetWhenMissingContext(a);return}const{frag:l,part:h,level:d}=o,{details:c}=d,{audio:u,text:f,id3:p,initSegment:g}=n;if(this.fragContextChanged(l)||!c){this.fragmentTracker.removeFragment(l);return}if(this.state=$.PARSING,this.switchingTrack&&u&&this.completeAudioSwitch(this.switchingTrack),g!=null&&g.tracks){const v=l.initSegment||l;this._bufferInitSegment(g.tracks,v,a),s.trigger(m.FRAG_PARSING_INIT_SEGMENT,{frag:v,id:i,tracks:g.tracks})}if(u){const{startPTS:v,endPTS:E,startDTS:T,endDTS:A}=u;h&&(h.elementaryStreams[at.AUDIO]={startPTS:v,endPTS:E,startDTS:T,endDTS:A}),l.setElementaryStreamInfo(at.AUDIO,v,E,T,A),this.bufferFragmentData(u,l,h,a)}if(p!=null&&(e=p.samples)!=null&&e.length){const v=At({id:i,frag:l,details:c},p);s.trigger(m.FRAG_PARSING_METADATA,v)}if(f){const v=At({id:i,frag:l,details:c},f);s.trigger(m.FRAG_PARSING_USERDATA,v)}}_bufferInitSegment(t,e,i){if(this.state!==$.PARSING)return;t.video&&delete t.video;const s=t.audio;if(!s)return;s.levelCodec=s.codec,s.id="audio",this.log(`Init audio buffer, container:${s.container}, codecs[parsed]=[${s.codec}]`),this.hls.trigger(m.BUFFER_CODECS,t);const n=s.initSegment;if(n!=null&&n.byteLength){const a={type:"audio",frag:e,part:null,chunkMeta:i,parent:e.type,data:n};this.hls.trigger(m.BUFFER_APPENDING,a)}this.tick()}loadFragment(t,e,i){const s=this.fragmentTracker.getState(t);if(this.fragCurrent=t,this.switchingTrack||s===Lt.NOT_LOADED||s===Lt.PARTIAL){var n;t.sn==="initSegment"?this._loadInitSegment(t,e):(n=e.details)!=null&&n.live&&!this.initPTS[t.cc]?(this.log(`Waiting for video PTS in continuity counter ${t.cc} of live stream before loading audio fragment ${t.sn} of level ${this.trackId}`),this.state=$.WAITING_INIT_PTS):(this.startFragRequested=!0,super.loadFragment(t,e,i))}else this.clearTrackerIfNeeded(t)}completeAudioSwitch(t){const{hls:e,media:i,bufferedTrack:s}=this,n=s==null?void 0:s.attrs,a=t.attrs;i&&n&&(n.CHANNELS!==a.CHANNELS||n.NAME!==a.NAME||n.LANGUAGE!==a.LANGUAGE)&&(this.log("Switching audio track : flushing all audio"),super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio")),this.bufferedTrack=t,this.switchingTrack=null,e.trigger(m.AUDIO_TRACK_SWITCHED,Gt({},t))}}class sv extends ta{constructor(t){super(t,"[audio-track-controller]"),this.tracks=[],this.groupId=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.registerListeners()}registerListeners(){const{hls:t}=this;t.on(m.MANIFEST_LOADING,this.onManifestLoading,this),t.on(m.MANIFEST_PARSED,this.onManifestParsed,this),t.on(m.LEVEL_LOADING,this.onLevelLoading,this),t.on(m.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(m.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.on(m.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(m.MANIFEST_LOADING,this.onManifestLoading,this),t.off(m.MANIFEST_PARSED,this.onManifestParsed,this),t.off(m.LEVEL_LOADING,this.onLevelLoading,this),t.off(m.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(m.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.off(m.ERROR,this.onError,this)}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,super.destroy()}onManifestLoading(){this.tracks=[],this.groupId=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0}onManifestParsed(t,e){this.tracks=e.audioTracks||[]}onAudioTrackLoaded(t,e){const{id:i,groupId:s,details:n}=e,a=this.tracksInGroup[i];if(!a||a.groupId!==s){this.warn(`Track with id:${i} and group:${s} not found in active group ${a.groupId}`);return}const o=a.details;a.details=e.details,this.log(`audio-track ${i} "${a.name}" lang:${a.lang} group:${s} loaded [${n.startSN}-${n.endSN}]`),i===this.trackId&&this.playlistLoaded(i,e,o)}onLevelLoading(t,e){this.switchLevel(e.level)}onLevelSwitching(t,e){this.switchLevel(e.level)}switchLevel(t){const e=this.hls.levels[t];if(!(e!=null&&e.audioGroupIds))return;const i=e.audioGroupIds[e.urlId];if(this.groupId!==i){this.groupId=i||null;const s=this.tracks.filter(a=>!i||a.groupId===i);this.selectDefaultTrack&&!s.some(a=>a.default)&&(this.selectDefaultTrack=!1),this.tracksInGroup=s;const n={audioTracks:s};this.log(`Updating audio tracks, ${s.length} track(s) found in group:${i}`),this.hls.trigger(m.AUDIO_TRACKS_UPDATED,n),this.selectInitialTrack()}else this.shouldReloadPlaylist(this.currentTrack)&&this.setAudioTrack(this.trackId)}onError(t,e){e.fatal||!e.context||e.context.type===rt.AUDIO_TRACK&&e.context.id===this.trackId&&e.context.groupId===this.groupId&&(this.requestScheduled=-1,this.checkRetry(e))}get audioTracks(){return this.tracksInGroup}get audioTrack(){return this.trackId}set audioTrack(t){this.selectDefaultTrack=!1,this.setAudioTrack(t)}setAudioTrack(t){const e=this.tracksInGroup;if(t<0||t>=e.length){this.warn("Invalid id passed to audio-track controller");return}this.clearTimer();const i=this.currentTrack;e[this.trackId];const s=e[t],{groupId:n,name:a}=s;if(this.log(`Switching to audio-track ${t} "${a}" lang:${s.lang} group:${n}`),this.trackId=t,this.currentTrack=s,this.selectDefaultTrack=!1,this.hls.trigger(m.AUDIO_TRACK_SWITCHING,Gt({},s)),s.details&&!s.details.live)return;const o=this.switchParams(s.url,i==null?void 0:i.details);this.loadPlaylist(o)}selectInitialTrack(){const t=this.tracksInGroup,e=this.findTrackId(this.currentTrack)|this.findTrackId(null);if(e!==-1)this.setAudioTrack(e);else{const i=new Error(`No track found for running audio group-ID: ${this.groupId} track count: ${t.length}`);this.warn(i.message),this.hls.trigger(m.ERROR,{type:W.MEDIA_ERROR,details:x.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:i})}}findTrackId(t){const e=this.tracksInGroup;for(let i=0;i<e.length;i++){const s=e[i];if((!this.selectDefaultTrack||s.default)&&(!t||t.attrs["STABLE-RENDITION-ID"]!==void 0&&t.attrs["STABLE-RENDITION-ID"]===s.attrs["STABLE-RENDITION-ID"]||t.name===s.name&&t.lang===s.lang))return s.id}return-1}loadPlaylist(t){super.loadPlaylist();const e=this.tracksInGroup[this.trackId];if(this.shouldLoadPlaylist(e)){const i=e.id,s=e.groupId;let n=e.url;if(t)try{n=t.addDirectives(n)}catch(a){this.warn(`Could not construct new URL with HLS Delivery Directives: ${a}`)}this.log(`loading audio-track playlist ${i} "${e.name}" lang:${e.lang} group:${s}`),this.clearTimer(),this.hls.trigger(m.AUDIO_TRACK_LOADING,{url:n,id:i,groupId:s,deliveryDirectives:t||null})}}}function ud(r,t){if(r.length!==t.length)return!1;for(let e=0;e<r.length;e++)if(!rv(r[e].attrs,t[e].attrs))return!1;return!0}function rv(r,t){const e=r["STABLE-RENDITION-ID"];return e?e===t["STABLE-RENDITION-ID"]:!["LANGUAGE","NAME","CHARACTERISTICS","AUTOSELECT","DEFAULT","FORCED"].some(i=>r[i]!==t[i])}const fd=500;class nv extends na{constructor(t,e,i){super(t,e,i,"[subtitle-stream-controller]",Y.SUBTITLE),this.levels=[],this.currentTrackId=-1,this.tracksBuffered=[],this.mainDetails=null,this._registerListeners()}onHandlerDestroying(){this._unregisterListeners(),this.mainDetails=null}_registerListeners(){const{hls:t}=this;t.on(m.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(m.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(m.MANIFEST_LOADING,this.onManifestLoading,this),t.on(m.LEVEL_LOADED,this.onLevelLoaded,this),t.on(m.ERROR,this.onError,this),t.on(m.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.on(m.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.on(m.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.on(m.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),t.on(m.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(m.FRAG_BUFFERED,this.onFragBuffered,this)}_unregisterListeners(){const{hls:t}=this;t.off(m.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(m.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(m.MANIFEST_LOADING,this.onManifestLoading,this),t.off(m.LEVEL_LOADED,this.onLevelLoaded,this),t.off(m.ERROR,this.onError,this),t.off(m.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.off(m.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.off(m.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.off(m.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),t.off(m.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(m.FRAG_BUFFERED,this.onFragBuffered,this)}startLoad(t){this.stopLoad(),this.state=$.IDLE,this.setInterval(fd),this.nextLoadPosition=this.startPosition=this.lastCurrentTime=t,this.tick()}onManifestLoading(){this.mainDetails=null,this.fragmentTracker.removeAllFragments()}onMediaDetaching(){this.tracksBuffered=[],super.onMediaDetaching()}onLevelLoaded(t,e){this.mainDetails=e.details}onSubtitleFragProcessed(t,e){const{frag:i,success:s}=e;if(this.fragPrevious=i,this.state=$.IDLE,!s)return;const n=this.tracksBuffered[this.currentTrackId];if(!n)return;let a;const o=i.start;for(let h=0;h<n.length;h++)if(o>=n[h].start&&o<=n[h].end){a=n[h];break}const l=i.start+i.duration;a?a.end=l:(a={start:o,end:l},n.push(a)),this.fragmentTracker.fragBuffered(i)}onBufferFlushing(t,e){const{startOffset:i,endOffset:s}=e;if(i===0&&s!==Number.POSITIVE_INFINITY){const n=s-1;if(n<=0)return;e.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,Y.SUBTITLE)}}onFragBuffered(t,e){if(!this.loadedmetadata&&e.frag.type===Y.MAIN){var i;(i=this.media)!=null&&i.buffered.length&&(this.loadedmetadata=!0)}}onError(t,e){const i=e.frag;(i==null?void 0:i.type)===Y.SUBTITLE&&(this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==$.STOPPED&&(this.state=$.IDLE))}onSubtitleTracksUpdated(t,{subtitleTracks:e}){if(ud(this.levels,e)){this.levels=e.map(i=>new ps(i));return}this.tracksBuffered=[],this.levels=e.map(i=>{const s=new ps(i);return this.tracksBuffered[s.id]=[],s}),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,Y.SUBTITLE),this.fragPrevious=null,this.mediaBuffer=null}onSubtitleTrackSwitch(t,e){if(this.currentTrackId=e.id,!this.levels.length||this.currentTrackId===-1){this.clearInterval();return}const i=this.levels[this.currentTrackId];i!=null&&i.details?this.mediaBuffer=this.mediaBufferTimeRanges:this.mediaBuffer=null,i&&this.setInterval(fd)}onSubtitleTrackLoaded(t,e){var i;const{details:s,id:n}=e,{currentTrackId:a,levels:o}=this;if(!o.length)return;const l=o[a];if(n>=o.length||n!==a||!l)return;this.mediaBuffer=this.mediaBufferTimeRanges;let h=0;if(s.live||(i=l.details)!=null&&i.live){const d=this.mainDetails;if(s.deltaUpdateFailed||!d)return;const c=d.fragments[0];l.details?(h=this.alignPlaylists(s,l.details),h===0&&c&&(h=c.start,Qn(s,h))):s.hasProgramDateTime&&d.hasProgramDateTime?(Gh(s,d),h=s.fragments[0].start):c&&(h=c.start,Qn(s,h))}l.details=s,this.levelLastLoaded=n,!this.startFragRequested&&(this.mainDetails||!s.live)&&this.setStartPosition(l.details,h),this.tick(),s.live&&!this.fragCurrent&&this.media&&this.state===$.IDLE&&(gs(null,s.fragments,this.media.currentTime,0)||(this.warn("Subtitle playlist not aligned with playback"),l.details=void 0))}_handleFragmentLoadComplete(t){const{frag:e,payload:i}=t,s=e.decryptdata,n=this.hls;if(!this.fragContextChanged(e)&&i&&i.byteLength>0&&s&&s.key&&s.iv&&s.method==="AES-128"){const a=performance.now();this.decrypter.decrypt(new Uint8Array(i),s.key.buffer,s.iv.buffer).catch(o=>{throw n.trigger(m.ERROR,{type:W.MEDIA_ERROR,details:x.FRAG_DECRYPT_ERROR,fatal:!1,error:o,reason:o.message,frag:e}),o}).then(o=>{const l=performance.now();n.trigger(m.FRAG_DECRYPTED,{frag:e,payload:o,stats:{tstart:a,tdecrypt:l}})}).catch(o=>{this.warn(`${o.name}: ${o.message}`),this.state=$.IDLE})}}doTick(){if(!this.media){this.state=$.IDLE;return}if(this.state===$.IDLE){const{currentTrackId:t,levels:e}=this,i=e[t];if(!e.length||!i||!i.details)return;const{config:s}=this,n=this.getLoadPosition(),a=lt.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],n,s.maxBufferHole),{end:o,len:l}=a,h=this.getFwdBufferInfo(this.media,Y.MAIN),d=i.details,c=this.getMaxBufferLength(h==null?void 0:h.len)+d.levelTargetDuration;if(l>c)return;const u=d.fragments,f=u.length,p=d.edge;let g=null;const v=this.fragPrevious;if(o<p){const E=s.maxFragLookUpTolerance,T=o>p-E?0:E;g=gs(v,u,Math.max(u[0].start,o),T),!g&&v&&v.start<u[0].start&&(g=u[0])}else g=u[f-1];if(!g)return;if(g=this.mapToInitFragWhenRequired(g),g.sn!=="initSegment"){const E=g.sn-d.startSN,T=u[E-1];T&&T.cc===g.cc&&this.fragmentTracker.getState(T)===Lt.NOT_LOADED&&(g=T)}this.fragmentTracker.getState(g)===Lt.NOT_LOADED&&this.loadFragment(g,i,o)}}getMaxBufferLength(t){const e=super.getMaxBufferLength();return t?Math.max(e,t):e}loadFragment(t,e,i){this.fragCurrent=t,t.sn==="initSegment"?this._loadInitSegment(t,e):(this.startFragRequested=!0,super.loadFragment(t,e,i))}get mediaBufferTimeRanges(){return new av(this.tracksBuffered[this.currentTrackId]||[])}}class av{constructor(t){this.buffered=void 0;const e=(i,s,n)=>{if(s=s>>>0,s>n-1)throw new DOMException(`Failed to execute '${i}' on 'TimeRanges': The index provided (${s}) is greater than the maximum bound (${n})`);return t[s][i]};this.buffered={get length(){return t.length},end(i){return e("end",i,t.length)},start(i){return e("start",i,t.length)}}}}class ov extends ta{constructor(t){super(t,"[subtitle-track-controller]"),this.media=null,this.tracks=[],this.groupId=null,this.tracksInGroup=[],this.trackId=-1,this.selectDefaultTrack=!0,this.queuedDefaultTrack=-1,this.trackChangeListener=()=>this.onTextTracksChanged(),this.asyncPollTrackChange=()=>this.pollTrackChange(0),this.useTextTrackPolling=!1,this.subtitlePollingInterval=-1,this._subtitleDisplay=!0,this.registerListeners()}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.trackChangeListener=this.asyncPollTrackChange=null,super.destroy()}get subtitleDisplay(){return this._subtitleDisplay}set subtitleDisplay(t){this._subtitleDisplay=t,this.trackId>-1&&this.toggleTrackModes(this.trackId)}registerListeners(){const{hls:t}=this;t.on(m.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(m.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(m.MANIFEST_LOADING,this.onManifestLoading,this),t.on(m.MANIFEST_PARSED,this.onManifestParsed,this),t.on(m.LEVEL_LOADING,this.onLevelLoading,this),t.on(m.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(m.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.on(m.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(m.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(m.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(m.MANIFEST_LOADING,this.onManifestLoading,this),t.off(m.MANIFEST_PARSED,this.onManifestParsed,this),t.off(m.LEVEL_LOADING,this.onLevelLoading,this),t.off(m.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(m.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.off(m.ERROR,this.onError,this)}onMediaAttached(t,e){this.media=e.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(t){self.clearInterval(this.subtitlePollingInterval),this.subtitlePollingInterval=self.setInterval(this.trackChangeListener,t)}onMediaDetaching(){this.media&&(self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||this.media.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId),va(this.media.textTracks).forEach(t=>{bi(t)}),this.subtitleTrack=-1,this.media=null)}onManifestLoading(){this.tracks=[],this.groupId=null,this.tracksInGroup=[],this.trackId=-1,this.selectDefaultTrack=!0}onManifestParsed(t,e){this.tracks=e.subtitleTracks}onSubtitleTrackLoaded(t,e){const{id:i,details:s}=e,{trackId:n}=this,a=this.tracksInGroup[n];if(!a){this.warn(`Invalid subtitle track id ${i}`);return}const o=a.details;a.details=e.details,this.log(`subtitle track ${i} loaded [${s.startSN}-${s.endSN}]`),i===this.trackId&&this.playlistLoaded(i,e,o)}onLevelLoading(t,e){this.switchLevel(e.level)}onLevelSwitching(t,e){this.switchLevel(e.level)}switchLevel(t){const e=this.hls.levels[t];if(!(e!=null&&e.textGroupIds))return;const i=e.textGroupIds[e.urlId],s=this.tracksInGroup?this.tracksInGroup[this.trackId]:void 0;if(this.groupId!==i){const n=this.tracks.filter(l=>!i||l.groupId===i);this.tracksInGroup=n;const a=this.findTrackId(s==null?void 0:s.name)||this.findTrackId();this.groupId=i||null;const o={subtitleTracks:n};this.log(`Updating subtitle tracks, ${n.length} track(s) found in "${i}" group-id`),this.hls.trigger(m.SUBTITLE_TRACKS_UPDATED,o),a!==-1&&this.setSubtitleTrack(a,s)}else this.shouldReloadPlaylist(s)&&this.setSubtitleTrack(this.trackId,s)}findTrackId(t){const e=this.tracksInGroup;for(let i=0;i<e.length;i++){const s=e[i];if((!this.selectDefaultTrack||s.default)&&(!t||t===s.name))return s.id}return-1}onError(t,e){e.fatal||!e.context||e.context.type===rt.SUBTITLE_TRACK&&e.context.id===this.trackId&&e.context.groupId===this.groupId&&this.checkRetry(e)}get subtitleTracks(){return this.tracksInGroup}get subtitleTrack(){return this.trackId}set subtitleTrack(t){this.selectDefaultTrack=!1;const e=this.tracksInGroup?this.tracksInGroup[this.trackId]:void 0;this.setSubtitleTrack(t,e)}loadPlaylist(t){super.loadPlaylist();const e=this.tracksInGroup[this.trackId];if(this.shouldLoadPlaylist(e)){const i=e.id,s=e.groupId;let n=e.url;if(t)try{n=t.addDirectives(n)}catch(a){this.warn(`Could not construct new URL with HLS Delivery Directives: ${a}`)}this.log(`Loading subtitle playlist for id ${i}`),this.hls.trigger(m.SUBTITLE_TRACK_LOADING,{url:n,id:i,groupId:s,deliveryDirectives:t||null})}}toggleTrackModes(t){const{media:e,trackId:i}=this;if(!e)return;const s=va(e.textTracks),n=s.filter(o=>o.groupId===this.groupId);if(t===-1)[].slice.call(s).forEach(o=>{o.mode="disabled"});else{const o=n[i];o&&(o.mode="disabled")}const a=n[t];a&&(a.mode=this.subtitleDisplay?"showing":"hidden")}setSubtitleTrack(t,e){var i;const s=this.tracksInGroup;if(!this.media){this.queuedDefaultTrack=t;return}if(this.trackId!==t&&this.toggleTrackModes(t),this.trackId===t&&(t===-1||(i=s[t])!=null&&i.details)||t<-1||t>=s.length)return;this.clearTimer();const n=s[t];if(this.log(`Switching to subtitle-track ${t}`+(n?` "${n.name}" lang:${n.lang} group:${n.groupId}`:"")),this.trackId=t,n){const{id:a,groupId:o="",name:l,type:h,url:d}=n;this.hls.trigger(m.SUBTITLE_TRACK_SWITCH,{id:a,groupId:o,name:l,type:h,url:d});const c=this.switchParams(n.url,e==null?void 0:e.details);this.loadPlaylist(c)}else this.hls.trigger(m.SUBTITLE_TRACK_SWITCH,{id:t})}onTextTracksChanged(){if(this.useTextTrackPolling||self.clearInterval(this.subtitlePollingInterval),!this.media||!this.hls.config.renderTextTracksNatively)return;let t=-1;const e=va(this.media.textTracks);for(let i=0;i<e.length;i++)if(e[i].mode==="hidden")t=i;else if(e[i].mode==="showing"){t=i;break}this.subtitleTrack!==t&&(this.subtitleTrack=t)}}function va(r){const t=[];for(let e=0;e<r.length;e++){const i=r[e];(i.kind==="subtitles"||i.kind==="captions")&&i.label&&t.push(r[e])}return t}class lv{constructor(t){this.buffers=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.buffers=t}append(t,e){const i=this.queues[e];i.push(t),i.length===1&&this.buffers[e]&&this.executeNext(e)}insertAbort(t,e){this.queues[e].unshift(t),this.executeNext(e)}appendBlocker(t){let e;const i=new Promise(n=>{e=n}),s={execute:e,onStart:()=>{},onComplete:()=>{},onError:()=>{}};return this.append(s,t),i}executeNext(t){const{buffers:e,queues:i}=this,s=e[t],n=i[t];if(n.length){const a=n[0];try{a.execute()}catch(o){L.warn("[buffer-operation-queue]: Unhandled exception executing the current operation"),a.onError(o),s!=null&&s.updating||(n.shift(),this.executeNext(t))}}}shiftAndExecuteNext(t){this.queues[t].shift(),this.executeNext(t)}current(t){return this.queues[t][0]}}const pd=lr(),gd=/([ha]vc.)(?:\.[^.,]+)+/;class hv{constructor(t){this.details=null,this._objectUrl=null,this.operationQueue=void 0,this.listeners=void 0,this.hls=void 0,this.bufferCodecEventsExpected=0,this._bufferCodecEventsTotal=0,this.media=null,this.mediaSource=null,this.lastMpegAudioChunk=null,this.appendError=0,this.tracks={},this.pendingTracks={},this.sourceBuffer=void 0,this._onMediaSourceOpen=()=>{const{media:e,mediaSource:i}=this;L.log("[buffer-controller]: Media source opened"),e&&(e.removeEventListener("emptied",this._onMediaEmptied),this.updateMediaElementDuration(),this.hls.trigger(m.MEDIA_ATTACHED,{media:e})),i&&i.removeEventListener("sourceopen",this._onMediaSourceOpen),this.checkPendingTracks()},this._onMediaSourceClose=()=>{L.log("[buffer-controller]: Media source closed")},this._onMediaSourceEnded=()=>{L.log("[buffer-controller]: Media source ended")},this._onMediaEmptied=()=>{const{media:e,_objectUrl:i}=this;e&&e.src!==i&&L.error(`Media element src was set while attaching MediaSource (${i} > ${e.src})`)},this.hls=t,this._initSourceBuffer(),this.registerListeners()}hasSourceTypes(){return this.getSourceBufferTypes().length>0||Object.keys(this.pendingTracks).length>0}destroy(){this.unregisterListeners(),this.details=null,this.lastMpegAudioChunk=null}registerListeners(){const{hls:t}=this;t.on(m.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(m.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(m.MANIFEST_LOADING,this.onManifestLoading,this),t.on(m.MANIFEST_PARSED,this.onManifestParsed,this),t.on(m.BUFFER_RESET,this.onBufferReset,this),t.on(m.BUFFER_APPENDING,this.onBufferAppending,this),t.on(m.BUFFER_CODECS,this.onBufferCodecs,this),t.on(m.BUFFER_EOS,this.onBufferEos,this),t.on(m.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(m.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(m.FRAG_PARSED,this.onFragParsed,this),t.on(m.FRAG_CHANGED,this.onFragChanged,this)}unregisterListeners(){const{hls:t}=this;t.off(m.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(m.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(m.MANIFEST_LOADING,this.onManifestLoading,this),t.off(m.MANIFEST_PARSED,this.onManifestParsed,this),t.off(m.BUFFER_RESET,this.onBufferReset,this),t.off(m.BUFFER_APPENDING,this.onBufferAppending,this),t.off(m.BUFFER_CODECS,this.onBufferCodecs,this),t.off(m.BUFFER_EOS,this.onBufferEos,this),t.off(m.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(m.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(m.FRAG_PARSED,this.onFragParsed,this),t.off(m.FRAG_CHANGED,this.onFragChanged,this)}_initSourceBuffer(){this.sourceBuffer={},this.operationQueue=new lv(this.sourceBuffer),this.listeners={audio:[],video:[],audiovideo:[]},this.lastMpegAudioChunk=null}onManifestLoading(){this.bufferCodecEventsExpected=this._bufferCodecEventsTotal=0,this.details=null}onManifestParsed(t,e){let i=2;(e.audio&&!e.video||!e.altAudio)&&(i=1),this.bufferCodecEventsExpected=this._bufferCodecEventsTotal=i,L.log(`${this.bufferCodecEventsExpected} bufferCodec event(s) expected`)}onMediaAttaching(t,e){const i=this.media=e.media;if(i&&pd){const s=this.mediaSource=new pd;s.addEventListener("sourceopen",this._onMediaSourceOpen),s.addEventListener("sourceended",this._onMediaSourceEnded),s.addEventListener("sourceclose",this._onMediaSourceClose),i.src=self.URL.createObjectURL(s),this._objectUrl=i.src,i.addEventListener("emptied",this._onMediaEmptied)}}onMediaDetaching(){const{media:t,mediaSource:e,_objectUrl:i}=this;if(e){if(L.log("[buffer-controller]: media source detaching"),e.readyState==="open")try{e.endOfStream()}catch(s){L.warn(`[buffer-controller]: onMediaDetaching: ${s.message} while calling endOfStream`)}this.onBufferReset(),e.removeEventListener("sourceopen",this._onMediaSourceOpen),e.removeEventListener("sourceended",this._onMediaSourceEnded),e.removeEventListener("sourceclose",this._onMediaSourceClose),t&&(t.removeEventListener("emptied",this._onMediaEmptied),i&&self.URL.revokeObjectURL(i),t.src===i?(t.removeAttribute("src"),t.load()):L.warn("[buffer-controller]: media.src was changed by a third party - skip cleanup")),this.mediaSource=null,this.media=null,this._objectUrl=null,this.bufferCodecEventsExpected=this._bufferCodecEventsTotal,this.pendingTracks={},this.tracks={}}this.hls.trigger(m.MEDIA_DETACHED,void 0)}onBufferReset(){this.getSourceBufferTypes().forEach(t=>{const e=this.sourceBuffer[t];try{e&&(this.removeBufferListeners(t),this.mediaSource&&this.mediaSource.removeSourceBuffer(e),this.sourceBuffer[t]=void 0)}catch(i){L.warn(`[buffer-controller]: Failed to reset the ${t} buffer`,i)}}),this._initSourceBuffer()}onBufferCodecs(t,e){const i=this.getSourceBufferTypes().length;Object.keys(e).forEach(s=>{if(i){const n=this.tracks[s];if(n&&typeof n.buffer.changeType=="function"){const{id:a,codec:o,levelCodec:l,container:h,metadata:d}=e[s],c=(n.levelCodec||n.codec).replace(gd,"$1"),u=(l||o).replace(gd,"$1");if(c!==u){const f=`${h};codecs=${l||o}`;this.appendChangeType(s,f),L.log(`[buffer-controller]: switching codec ${c} to ${u}`),this.tracks[s]={buffer:n.buffer,codec:o,container:h,levelCodec:l,metadata:d,id:a}}}}else this.pendingTracks[s]=e[s]}),!i&&(this.bufferCodecEventsExpected=Math.max(this.bufferCodecEventsExpected-1,0),this.mediaSource&&this.mediaSource.readyState==="open"&&this.checkPendingTracks())}appendChangeType(t,e){const{operationQueue:i}=this,s={execute:()=>{const n=this.sourceBuffer[t];n&&(L.log(`[buffer-controller]: changing ${t} sourceBuffer type to ${e}`),n.changeType(e)),i.shiftAndExecuteNext(t)},onStart:()=>{},onComplete:()=>{},onError:n=>{L.warn(`[buffer-controller]: Failed to change ${t} SourceBuffer type`,n)}};i.append(s,t)}onBufferAppending(t,e){const{hls:i,operationQueue:s,tracks:n}=this,{data:a,type:o,frag:l,part:h,chunkMeta:d}=e,c=d.buffering[o],u=self.performance.now();c.start=u;const f=l.stats.buffering,p=h?h.stats.buffering:null;f.start===0&&(f.start=u),p&&p.start===0&&(p.start=u);const g=n.audio;let v=!1;o==="audio"&&(g==null?void 0:g.container)==="audio/mpeg"&&(v=!this.lastMpegAudioChunk||d.id===1||this.lastMpegAudioChunk.sn!==d.sn,this.lastMpegAudioChunk=d);const E=l.start,T={execute:()=>{if(c.executeStart=self.performance.now(),v){const A=this.sourceBuffer[o];if(A){const y=E-A.timestampOffset;Math.abs(y)>=.1&&(L.log(`[buffer-controller]: Updating audio SourceBuffer timestampOffset to ${E} (delta: ${y}) sn: ${l.sn})`),A.timestampOffset=E)}}this.appendExecutor(a,o)},onStart:()=>{},onComplete:()=>{const A=self.performance.now();c.executeEnd=c.end=A,f.first===0&&(f.first=A),p&&p.first===0&&(p.first=A);const{sourceBuffer:y}=this,b={};for(const S in y)b[S]=lt.getBuffered(y[S]);this.appendError=0,this.hls.trigger(m.BUFFER_APPENDED,{type:o,frag:l,part:h,chunkMeta:d,parent:l.type,timeRanges:b})},onError:A=>{L.error(`[buffer-controller]: Error encountered while trying to append to the ${o} SourceBuffer`,A);const y={type:W.MEDIA_ERROR,parent:l.type,details:x.BUFFER_APPEND_ERROR,frag:l,part:h,chunkMeta:d,error:A,err:A,fatal:!1};A.code===DOMException.QUOTA_EXCEEDED_ERR?y.details=x.BUFFER_FULL_ERROR:(this.appendError++,y.details=x.BUFFER_APPEND_ERROR,this.appendError>i.config.appendErrorMaxRetry&&(L.error(`[buffer-controller]: Failed ${i.config.appendErrorMaxRetry} times to append segment in sourceBuffer`),y.fatal=!0)),i.trigger(m.ERROR,y)}};s.append(T,o)}onBufferFlushing(t,e){const{operationQueue:i}=this,s=n=>({execute:this.removeExecutor.bind(this,n,e.startOffset,e.endOffset),onStart:()=>{},onComplete:()=>{this.hls.trigger(m.BUFFER_FLUSHED,{type:n})},onError:a=>{L.warn(`[buffer-controller]: Failed to remove from ${n} SourceBuffer`,a)}});e.type?i.append(s(e.type),e.type):this.getSourceBufferTypes().forEach(n=>{i.append(s(n),n)})}onFragParsed(t,e){const{frag:i,part:s}=e,n=[],a=s?s.elementaryStreams:i.elementaryStreams;a[at.AUDIOVIDEO]?n.push("audiovideo"):(a[at.AUDIO]&&n.push("audio"),a[at.VIDEO]&&n.push("video"));const o=()=>{const l=self.performance.now();i.stats.buffering.end=l,s&&(s.stats.buffering.end=l);const h=s?s.stats:i.stats;this.hls.trigger(m.FRAG_BUFFERED,{frag:i,part:s,stats:h,id:i.type})};n.length===0&&L.warn(`Fragments must have at least one ElementaryStreamType set. type: ${i.type} level: ${i.level} sn: ${i.sn}`),this.blockBuffers(o,n)}onFragChanged(t,e){this.flushBackBuffer()}onBufferEos(t,e){this.getSourceBufferTypes().reduce((i,s)=>{const n=this.sourceBuffer[s];return n&&(!e.type||e.type===s)&&(n.ending=!0,n.ended||(n.ended=!0,L.log(`[buffer-controller]: ${s} sourceBuffer now EOS`))),i&&!!(!n||n.ended)},!0)&&(L.log("[buffer-controller]: Queueing mediaSource.endOfStream()"),this.blockBuffers(()=>{this.getSourceBufferTypes().forEach(s=>{const n=this.sourceBuffer[s];n&&(n.ending=!1)});const{mediaSource:i}=this;if(!i||i.readyState!=="open"){i&&L.info(`[buffer-controller]: Could not call mediaSource.endOfStream(). mediaSource.readyState: ${i.readyState}`);return}L.log("[buffer-controller]: Calling mediaSource.endOfStream()"),i.endOfStream()}))}onLevelUpdated(t,{details:e}){e.fragments.length&&(this.details=e,this.getSourceBufferTypes().length?this.blockBuffers(this.updateMediaElementDuration.bind(this)):this.updateMediaElementDuration())}flushBackBuffer(){const{hls:t,details:e,media:i,sourceBuffer:s}=this;if(!i||e===null)return;const n=this.getSourceBufferTypes();if(!n.length)return;const a=e.live&&t.config.liveBackBufferLength!==null?t.config.liveBackBufferLength:t.config.backBufferLength;if(!j(a)||a<0)return;const o=i.currentTime,l=e.levelTargetDuration,h=Math.max(a,l),d=Math.floor(o/l)*l-h;n.forEach(c=>{const u=s[c];if(u){const f=lt.getBuffered(u);if(f.length>0&&d>f.start(0)){if(t.trigger(m.BACK_BUFFER_REACHED,{bufferEnd:d}),e.live)t.trigger(m.LIVE_BACK_BUFFER_REACHED,{bufferEnd:d});else if(u.ended&&f.end(f.length-1)-o<l*2){L.info(`[buffer-controller]: Cannot flush ${c} back buffer while SourceBuffer is in ended state`);return}t.trigger(m.BUFFER_FLUSHING,{startOffset:0,endOffset:d,type:c})}}})}updateMediaElementDuration(){if(!this.details||!this.media||!this.mediaSource||this.mediaSource.readyState!=="open")return;const{details:t,hls:e,media:i,mediaSource:s}=this,n=t.fragments[0].start+t.totalduration,a=i.duration,o=j(s.duration)?s.duration:0;t.live&&e.config.liveDurationInfinity?(L.log("[buffer-controller]: Media Source duration is set to Infinity"),s.duration=1/0,this.updateSeekableRange(t)):(n>o&&n>a||!j(a))&&(L.log(`[buffer-controller]: Updating Media Source duration to ${n.toFixed(3)}`),s.duration=n)}updateSeekableRange(t){const e=this.mediaSource,i=t.fragments;if(i.length&&t.live&&e!=null&&e.setLiveSeekableRange){const s=Math.max(0,i[0].start),n=Math.max(s,s+t.totalduration);e.setLiveSeekableRange(s,n)}}checkPendingTracks(){const{bufferCodecEventsExpected:t,operationQueue:e,pendingTracks:i}=this,s=Object.keys(i).length;if(s&&!t||s===2){this.createSourceBuffers(i),this.pendingTracks={};const n=this.getSourceBufferTypes();if(n.length)this.hls.trigger(m.BUFFER_CREATED,{tracks:this.tracks}),n.forEach(a=>{e.executeNext(a)});else{const a=new Error("could not create source buffer for media codec(s)");this.hls.trigger(m.ERROR,{type:W.MEDIA_ERROR,details:x.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:a,reason:a.message})}}}createSourceBuffers(t){const{sourceBuffer:e,mediaSource:i}=this;if(!i)throw Error("createSourceBuffers called when mediaSource was null");for(const s in t)if(!e[s]){const n=t[s];if(!n)throw Error(`source buffer exists for track ${s}, however track does not`);const a=n.levelCodec||n.codec,o=`${n.container};codecs=${a}`;L.log(`[buffer-controller]: creating sourceBuffer(${o})`);try{const l=e[s]=i.addSourceBuffer(o),h=s;this.addBufferListener(h,"updatestart",this._onSBUpdateStart),this.addBufferListener(h,"updateend",this._onSBUpdateEnd),this.addBufferListener(h,"error",this._onSBUpdateError),this.tracks[s]={buffer:l,codec:a,container:n.container,levelCodec:n.levelCodec,metadata:n.metadata,id:n.id}}catch(l){L.error(`[buffer-controller]: error while trying to add sourceBuffer: ${l.message}`),this.hls.trigger(m.ERROR,{type:W.MEDIA_ERROR,details:x.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:l,mimeType:o})}}}_onSBUpdateStart(t){const{operationQueue:e}=this;e.current(t).onStart()}_onSBUpdateEnd(t){const{operationQueue:e}=this;e.current(t).onComplete(),e.shiftAndExecuteNext(t)}_onSBUpdateError(t,e){const i=new Error(`${t} SourceBuffer error`);L.error(`[buffer-controller]: ${i}`,e),this.hls.trigger(m.ERROR,{type:W.MEDIA_ERROR,details:x.BUFFER_APPENDING_ERROR,error:i,fatal:!1});const s=this.operationQueue.current(t);s&&s.onError(e)}removeExecutor(t,e,i){const{media:s,mediaSource:n,operationQueue:a,sourceBuffer:o}=this,l=o[t];if(!s||!n||!l){L.warn(`[buffer-controller]: Attempting to remove from the ${t} SourceBuffer, but it does not exist`),a.shiftAndExecuteNext(t);return}const h=j(s.duration)?s.duration:1/0,d=j(n.duration)?n.duration:1/0,c=Math.max(0,e),u=Math.min(i,h,d);u>c&&!l.ending?(l.ended=!1,L.log(`[buffer-controller]: Removing [${c},${u}] from the ${t} SourceBuffer`),l.remove(c,u)):a.shiftAndExecuteNext(t)}appendExecutor(t,e){const{operationQueue:i,sourceBuffer:s}=this,n=s[e];if(!n){L.warn(`[buffer-controller]: Attempting to append to the ${e} SourceBuffer, but it does not exist`),i.shiftAndExecuteNext(e);return}n.ended=!1,n.appendBuffer(t)}blockBuffers(t,e=this.getSourceBufferTypes()){if(!e.length){L.log("[buffer-controller]: Blocking operation requested, but no SourceBuffers exist"),Promise.resolve().then(t);return}const{operationQueue:i}=this,s=e.map(n=>i.appendBlocker(n));Promise.all(s).then(()=>{t(),e.forEach(n=>{const a=this.sourceBuffer[n];a!=null&&a.updating||i.shiftAndExecuteNext(n)})})}getSourceBufferTypes(){return Object.keys(this.sourceBuffer)}addBufferListener(t,e,i){const s=this.sourceBuffer[t];if(!s)return;const n=i.bind(this,t);this.listeners[t].push({event:e,listener:n}),s.addEventListener(e,n)}removeBufferListeners(t){const e=this.sourceBuffer[t];e&&this.listeners[t].forEach(i=>{e.removeEventListener(i.event,i.listener)})}}const md={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},vd=function(r){let t=r;return md.hasOwnProperty(r)&&(t=md[r]),String.fromCharCode(t)},oe=15,_e=100,dv={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},cv={17:2,18:4,21:6,22:8,23:10,19:13,20:15},uv={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},fv={25:2,26:4,29:6,30:8,31:10,27:13,28:15},pv=["white","green","blue","cyan","red","yellow","magenta","black","transparent"];class gv{constructor(){this.time=null,this.verboseLevel=0}log(t,e){if(this.verboseLevel>=t){const i=typeof e=="function"?e():e;L.log(`${this.time} [${t}] ${i}`)}}}const ri=function(r){const t=[];for(let e=0;e<r.length;e++)t.push(r[e].toString(16));return t};class yd{constructor(t,e,i,s,n){this.foreground=void 0,this.underline=void 0,this.italics=void 0,this.background=void 0,this.flash=void 0,this.foreground=t||"white",this.underline=e||!1,this.italics=i||!1,this.background=s||"black",this.flash=n||!1}reset(){this.foreground="white",this.underline=!1,this.italics=!1,this.background="black",this.flash=!1}setStyles(t){const e=["foreground","underline","italics","background","flash"];for(let i=0;i<e.length;i++){const s=e[i];t.hasOwnProperty(s)&&(this[s]=t[s])}}isDefault(){return this.foreground==="white"&&!this.underline&&!this.italics&&this.background==="black"&&!this.flash}equals(t){return this.foreground===t.foreground&&this.underline===t.underline&&this.italics===t.italics&&this.background===t.background&&this.flash===t.flash}copy(t){this.foreground=t.foreground,this.underline=t.underline,this.italics=t.italics,this.background=t.background,this.flash=t.flash}toString(){return"color="+this.foreground+", underline="+this.underline+", italics="+this.italics+", background="+this.background+", flash="+this.flash}}class mv{constructor(t,e,i,s,n,a){this.uchar=void 0,this.penState=void 0,this.uchar=t||" ",this.penState=new yd(e,i,s,n,a)}reset(){this.uchar=" ",this.penState.reset()}setChar(t,e){this.uchar=t,this.penState.copy(e)}setPenState(t){this.penState.copy(t)}equals(t){return this.uchar===t.uchar&&this.penState.equals(t.penState)}copy(t){this.uchar=t.uchar,this.penState.copy(t.penState)}isEmpty(){return this.uchar===" "&&this.penState.isDefault()}}class vv{constructor(t){this.chars=void 0,this.pos=void 0,this.currPenState=void 0,this.cueStartTime=void 0,this.logger=void 0,this.chars=[];for(let e=0;e<_e;e++)this.chars.push(new mv);this.logger=t,this.pos=0,this.currPenState=new yd}equals(t){let e=!0;for(let i=0;i<_e;i++)if(!this.chars[i].equals(t.chars[i])){e=!1;break}return e}copy(t){for(let e=0;e<_e;e++)this.chars[e].copy(t.chars[e])}isEmpty(){let t=!0;for(let e=0;e<_e;e++)if(!this.chars[e].isEmpty()){t=!1;break}return t}setCursor(t){this.pos!==t&&(this.pos=t),this.pos<0?(this.logger.log(3,"Negative cursor position "+this.pos),this.pos=0):this.pos>_e&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=_e)}moveCursor(t){const e=this.pos+t;if(t>1)for(let i=this.pos+1;i<e+1;i++)this.chars[i].setPenState(this.currPenState);this.setCursor(e)}backSpace(){this.moveCursor(-1),this.chars[this.pos].setChar(" ",this.currPenState)}insertChar(t){t>=144&&this.backSpace();const e=vd(t);if(this.pos>=_e){this.logger.log(0,()=>"Cannot insert "+t.toString(16)+" ("+e+") at position "+this.pos+". Skipping it!");return}this.chars[this.pos].setChar(e,this.currPenState),this.moveCursor(1)}clearFromPos(t){let e;for(e=t;e<_e;e++)this.chars[e].reset()}clear(){this.clearFromPos(0),this.pos=0,this.currPenState.reset()}clearToEndOfRow(){this.clearFromPos(this.pos)}getTextString(){const t=[];let e=!0;for(let i=0;i<_e;i++){const s=this.chars[i].uchar;s!==" "&&(e=!1),t.push(s)}return e?"":t.join("")}setPenStyles(t){this.currPenState.setStyles(t),this.chars[this.pos].setPenState(this.currPenState)}}class ya{constructor(t){this.rows=void 0,this.currRow=void 0,this.nrRollUpRows=void 0,this.lastOutputScreen=void 0,this.logger=void 0,this.rows=[];for(let e=0;e<oe;e++)this.rows.push(new vv(t));this.logger=t,this.currRow=oe-1,this.nrRollUpRows=null,this.lastOutputScreen=null,this.reset()}reset(){for(let t=0;t<oe;t++)this.rows[t].clear();this.currRow=oe-1}equals(t){let e=!0;for(let i=0;i<oe;i++)if(!this.rows[i].equals(t.rows[i])){e=!1;break}return e}copy(t){for(let e=0;e<oe;e++)this.rows[e].copy(t.rows[e])}isEmpty(){let t=!0;for(let e=0;e<oe;e++)if(!this.rows[e].isEmpty()){t=!1;break}return t}backSpace(){this.rows[this.currRow].backSpace()}clearToEndOfRow(){this.rows[this.currRow].clearToEndOfRow()}insertChar(t){this.rows[this.currRow].insertChar(t)}setPen(t){this.rows[this.currRow].setPenStyles(t)}moveCursor(t){this.rows[this.currRow].moveCursor(t)}setCursor(t){this.logger.log(2,"setCursor: "+t),this.rows[this.currRow].setCursor(t)}setPAC(t){this.logger.log(2,()=>"pacData = "+JSON.stringify(t));let e=t.row-1;if(this.nrRollUpRows&&e<this.nrRollUpRows-1&&(e=this.nrRollUpRows-1),this.nrRollUpRows&&this.currRow!==e){for(let o=0;o<oe;o++)this.rows[o].clear();const n=this.currRow+1-this.nrRollUpRows,a=this.lastOutputScreen;if(a){const o=a.rows[n].cueStartTime,l=this.logger.time;if(o&&l!==null&&o<l)for(let h=0;h<this.nrRollUpRows;h++)this.rows[e-this.nrRollUpRows+h+1].copy(a.rows[n+h])}}this.currRow=e;const i=this.rows[this.currRow];if(t.indent!==null){const n=t.indent,a=Math.max(n-1,0);i.setCursor(t.indent),t.color=i.chars[a].penState.foreground}const s={foreground:t.color,underline:t.underline,italics:t.italics,background:"black",flash:!1};this.setPen(s)}setBkgData(t){this.logger.log(2,()=>"bkgData = "+JSON.stringify(t)),this.backSpace(),this.setPen(t),this.insertChar(32)}setRollUpRows(t){this.nrRollUpRows=t}rollUp(){if(this.nrRollUpRows===null){this.logger.log(3,"roll_up but nrRollUpRows not set yet");return}this.logger.log(1,()=>this.getDisplayText());const t=this.currRow+1-this.nrRollUpRows,e=this.rows.splice(t,1)[0];e.clear(),this.rows.splice(this.currRow,0,e),this.logger.log(2,"Rolling up")}getDisplayText(t){t=t||!1;const e=[];let i="",s=-1;for(let n=0;n<oe;n++){const a=this.rows[n].getTextString();a&&(s=n+1,t?e.push("Row "+s+": '"+a+"'"):e.push(a.trim()))}return e.length>0&&(t?i="["+e.join(" | ")+"]":i=e.join(`
173
- `)),i}getTextAndFormat(){return this.rows}}class Ed{constructor(t,e,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=t,this.outputFilter=e,this.mode=null,this.verbose=0,this.displayedMemory=new ya(i),this.nonDisplayedMemory=new ya(i),this.lastOutputScreen=new ya(i),this.currRollUpRow=this.displayedMemory.rows[oe-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[oe-1],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null}getHandler(){return this.outputFilter}setHandler(t){this.outputFilter=t}setPAC(t){this.writeScreen.setPAC(t)}setBkgData(t){this.writeScreen.setBkgData(t)}setMode(t){t!==this.mode&&(this.mode=t,this.logger.log(2,()=>"MODE="+t),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=t)}insertChars(t){for(let i=0;i<t.length;i++)this.writeScreen.insertChar(t[i]);const e=this.writeScreen===this.displayedMemory?"DISP":"NON_DISP";this.logger.log(2,()=>e+": "+this.writeScreen.getDisplayText(!0)),(this.mode==="MODE_PAINT-ON"||this.mode==="MODE_ROLL-UP")&&(this.logger.log(1,()=>"DISPLAYED: "+this.displayedMemory.getDisplayText(!0)),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(t){this.logger.log(2,"RU("+t+") - Roll Up"),this.writeScreen=this.displayedMemory,this.setMode("MODE_ROLL-UP"),this.writeScreen.setRollUpRows(t)}ccFON(){this.logger.log(2,"FON - Flash On"),this.writeScreen.setPen({flash:!0})}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(!0)}ccCR(){this.logger.log(2,"CR - Carriage Return"),this.writeScreen.rollUp(),this.outputDataUpdate(!0)}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"){const t=this.displayedMemory;this.displayedMemory=this.nonDisplayedMemory,this.nonDisplayedMemory=t,this.writeScreen=this.nonDisplayedMemory,this.logger.log(1,()=>"DISP: "+this.displayedMemory.getDisplayText())}this.outputDataUpdate(!0)}ccTO(t){this.logger.log(2,"TO("+t+") - Tab Offset"),this.writeScreen.moveCursor(t)}ccMIDROW(t){const e={flash:!1};if(e.underline=t%2===1,e.italics=t>=46,e.italics)e.foreground="white";else{const i=Math.floor(t/2)-16,s=["white","green","blue","cyan","red","yellow","magenta"];e.foreground=s[i]}this.logger.log(2,"MIDROW: "+JSON.stringify(e)),this.writeScreen.setPen(e)}outputDataUpdate(t=!1){const e=this.logger.time;e!==null&&this.outputFilter&&(this.cueStartTime===null&&!this.displayedMemory.isEmpty()?this.cueStartTime=e:this.displayedMemory.equals(this.lastOutputScreen)||(this.outputFilter.newCue(this.cueStartTime,e,this.lastOutputScreen),t&&this.outputFilter.dispatchCue&&this.outputFilter.dispatchCue(),this.cueStartTime=this.displayedMemory.isEmpty()?null:e),this.lastOutputScreen.copy(this.displayedMemory))}cueSplitAtTime(t){this.outputFilter&&(this.displayedMemory.isEmpty()||(this.outputFilter.newCue&&this.outputFilter.newCue(this.cueStartTime,t,this.displayedMemory),this.cueStartTime=t))}}class Td{constructor(t,e,i){this.channels=void 0,this.currentChannel=0,this.cmdHistory=void 0,this.logger=void 0;const s=new gv;this.channels=[null,new Ed(t,e,s),new Ed(t+1,i,s)],this.cmdHistory=Ad(),this.logger=s}getHandler(t){return this.channels[t].getHandler()}setHandler(t,e){this.channels[t].setHandler(e)}addData(t,e){let i,s,n,a=!1;this.logger.time=t;for(let o=0;o<e.length;o+=2)if(s=e[o]&127,n=e[o+1]&127,!(s===0&&n===0)){if(this.logger.log(3,"["+ri([e[o],e[o+1]])+"] -> ("+ri([s,n])+")"),i=this.parseCmd(s,n),i||(i=this.parseMidrow(s,n)),i||(i=this.parsePAC(s,n)),i||(i=this.parseBackgroundAttributes(s,n)),!i&&(a=this.parseChars(s,n),a)){const l=this.currentChannel;l&&l>0?this.channels[l].insertChars(a):this.logger.log(2,"No channel found yet. TEXT-MODE?")}!i&&!a&&this.logger.log(2,"Couldn't parse cleaned data "+ri([s,n])+" orig: "+ri([e[o],e[o+1]]))}}parseCmd(t,e){const{cmdHistory:i}=this,s=(t===20||t===28||t===21||t===29)&&e>=32&&e<=47,n=(t===23||t===31)&&e>=33&&e<=35;if(!(s||n))return!1;if(bd(t,e,i))return Li(null,null,i),this.logger.log(3,"Repeated command ("+ri([t,e])+") is dropped"),!0;const a=t===20||t===21||t===23?1:2,o=this.channels[a];return t===20||t===21||t===28||t===29?e===32?o.ccRCL():e===33?o.ccBS():e===34?o.ccAOF():e===35?o.ccAON():e===36?o.ccDER():e===37?o.ccRU(2):e===38?o.ccRU(3):e===39?o.ccRU(4):e===40?o.ccFON():e===41?o.ccRDC():e===42?o.ccTR():e===43?o.ccRTD():e===44?o.ccEDM():e===45?o.ccCR():e===46?o.ccENM():e===47&&o.ccEOC():o.ccTO(e-32),Li(t,e,i),this.currentChannel=a,!0}parseMidrow(t,e){let i=0;if((t===17||t===25)&&e>=32&&e<=47){if(t===17?i=1:i=2,i!==this.currentChannel)return this.logger.log(0,"Mismatch channel in midrow parsing"),!1;const s=this.channels[i];return s?(s.ccMIDROW(e),this.logger.log(3,"MIDROW ("+ri([t,e])+")"),!0):!1}return!1}parsePAC(t,e){let i;const s=this.cmdHistory,n=(t>=17&&t<=23||t>=25&&t<=31)&&e>=64&&e<=127,a=(t===16||t===24)&&e>=64&&e<=95;if(!(n||a))return!1;if(bd(t,e,s))return Li(null,null,s),!0;const o=t<=23?1:2;e>=64&&e<=95?i=o===1?dv[t]:uv[t]:i=o===1?cv[t]:fv[t];const l=this.channels[o];return l?(l.setPAC(this.interpretPAC(i,e)),Li(t,e,s),this.currentChannel=o,!0):!1}interpretPAC(t,e){let i;const s={color:null,italics:!1,indent:null,underline:!1,row:t};return e>95?i=e-96:i=e-64,s.underline=(i&1)===1,i<=13?s.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(i/2)]:i<=15?(s.italics=!0,s.color="white"):s.indent=Math.floor((i-16)/2)*4,s}parseChars(t,e){let i,s=null,n=null;if(t>=25?(i=2,n=t-8):(i=1,n=t),n>=17&&n<=19){let a;n===17?a=e+80:n===18?a=e+112:a=e+144,this.logger.log(2,"Special char '"+vd(a)+"' in channel "+i),s=[a]}else t>=32&&t<=127&&(s=e===0?[t]:[t,e]);if(s){const a=ri(s);this.logger.log(3,"Char codes = "+a.join(",")),Li(t,e,this.cmdHistory)}return s}parseBackgroundAttributes(t,e){const i=(t===16||t===24)&&e>=32&&e<=47,s=(t===23||t===31)&&e>=45&&e<=47;if(!(i||s))return!1;let n;const a={};t===16||t===24?(n=Math.floor((e-32)/2),a.background=pv[n],e%2===1&&(a.background=a.background+"_semi")):e===45?a.background="transparent":(a.foreground="black",e===47&&(a.underline=!0));const o=t<=23?1:2;return this.channels[o].setBkgData(a),Li(t,e,this.cmdHistory),!0}reset(){for(let t=0;t<Object.keys(this.channels).length;t++){const e=this.channels[t];e&&e.reset()}this.cmdHistory=Ad()}cueSplitAtTime(t){for(let e=0;e<this.channels.length;e++){const i=this.channels[e];i&&i.cueSplitAtTime(t)}}}function Li(r,t,e){e.a=r,e.b=t}function bd(r,t,e){return e.a===r&&e.b===t}function Ad(){return{a:null,b:null}}class Tr{constructor(t,e){this.timelineController=void 0,this.cueRanges=[],this.trackName=void 0,this.startTime=null,this.endTime=null,this.screen=null,this.timelineController=t,this.trackName=e}dispatchCue(){this.startTime!==null&&(this.timelineController.addCues(this.trackName,this.startTime,this.endTime,this.screen,this.cueRanges),this.startTime=null)}newCue(t,e,i){(this.startTime===null||this.startTime>t)&&(this.startTime=t),this.endTime=e,this.screen=i,this.timelineController.createCaptionsTrack(this.trackName)}reset(){this.cueRanges=[],this.startTime=null}}var Ea=function(){if(typeof self<"u"&&self.VTTCue)return self.VTTCue;const r=["","lr","rl"],t=["start","middle","end","left","right"];function e(o,l){if(typeof l!="string"||!Array.isArray(o))return!1;const h=l.toLowerCase();return~o.indexOf(h)?h:!1}function i(o){return e(r,o)}function s(o){return e(t,o)}function n(o,...l){let h=1;for(;h<arguments.length;h++){const d=arguments[h];for(const c in d)o[c]=d[c]}return o}function a(o,l,h){const d=this,c={enumerable:!0};d.hasBeenReset=!1;let u="",f=!1,p=o,g=l,v=h,E=null,T="",A=!0,y="auto",b="start",S=50,R="middle",D=50,_="middle";Object.defineProperty(d,"id",n({},c,{get:function(){return u},set:function(I){u=""+I}})),Object.defineProperty(d,"pauseOnExit",n({},c,{get:function(){return f},set:function(I){f=!!I}})),Object.defineProperty(d,"startTime",n({},c,{get:function(){return p},set:function(I){if(typeof I!="number")throw new TypeError("Start time must be set to a number.");p=I,this.hasBeenReset=!0}})),Object.defineProperty(d,"endTime",n({},c,{get:function(){return g},set:function(I){if(typeof I!="number")throw new TypeError("End time must be set to a number.");g=I,this.hasBeenReset=!0}})),Object.defineProperty(d,"text",n({},c,{get:function(){return v},set:function(I){v=""+I,this.hasBeenReset=!0}})),Object.defineProperty(d,"region",n({},c,{get:function(){return E},set:function(I){E=I,this.hasBeenReset=!0}})),Object.defineProperty(d,"vertical",n({},c,{get:function(){return T},set:function(I){const N=i(I);if(N===!1)throw new SyntaxError("An invalid or illegal string was specified.");T=N,this.hasBeenReset=!0}})),Object.defineProperty(d,"snapToLines",n({},c,{get:function(){return A},set:function(I){A=!!I,this.hasBeenReset=!0}})),Object.defineProperty(d,"line",n({},c,{get:function(){return y},set:function(I){if(typeof I!="number"&&I!=="auto")throw new SyntaxError("An invalid number or illegal string was specified.");y=I,this.hasBeenReset=!0}})),Object.defineProperty(d,"lineAlign",n({},c,{get:function(){return b},set:function(I){const N=s(I);if(!N)throw new SyntaxError("An invalid or illegal string was specified.");b=N,this.hasBeenReset=!0}})),Object.defineProperty(d,"position",n({},c,{get:function(){return S},set:function(I){if(I<0||I>100)throw new Error("Position must be between 0 and 100.");S=I,this.hasBeenReset=!0}})),Object.defineProperty(d,"positionAlign",n({},c,{get:function(){return R},set:function(I){const N=s(I);if(!N)throw new SyntaxError("An invalid or illegal string was specified.");R=N,this.hasBeenReset=!0}})),Object.defineProperty(d,"size",n({},c,{get:function(){return D},set:function(I){if(I<0||I>100)throw new Error("Size must be between 0 and 100.");D=I,this.hasBeenReset=!0}})),Object.defineProperty(d,"align",n({},c,{get:function(){return _},set:function(I){const N=s(I);if(!N)throw new SyntaxError("An invalid or illegal string was specified.");_=N,this.hasBeenReset=!0}})),d.displayState=void 0}return a.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},a}();class yv{decode(t,e){if(!t)return"";if(typeof t!="string")throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(t))}}function wd(r){function t(i,s,n,a){return(i|0)*3600+(s|0)*60+(n|0)+parseFloat(a||0)}const e=r.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);return e?parseFloat(e[2])>59?t(e[2],e[3],0,e[4]):t(e[1],e[2],e[3],e[4]):null}class Ev{constructor(){this.values=Object.create(null)}set(t,e){!this.get(t)&&e!==""&&(this.values[t]=e)}get(t,e,i){return i?this.has(t)?this.values[t]:e[i]:this.has(t)?this.values[t]:e}has(t){return t in this.values}alt(t,e,i){for(let s=0;s<i.length;++s)if(e===i[s]){this.set(t,e);break}}integer(t,e){/^-?\d+$/.test(e)&&this.set(t,parseInt(e,10))}percent(t,e){if(/^([\d]{1,3})(\.[\d]*)?%$/.test(e)){const i=parseFloat(e);if(i>=0&&i<=100)return this.set(t,i),!0}return!1}}function Sd(r,t,e,i){const s=i?r.split(i):[r];for(const n in s){if(typeof s[n]!="string")continue;const a=s[n].split(e);if(a.length!==2)continue;const o=a[0],l=a[1];t(o,l)}}const Ta=new Ea(0,0,""),br=Ta.align==="middle"?"middle":"center";function Tv(r,t,e){const i=r;function s(){const o=wd(r);if(o===null)throw new Error("Malformed timestamp: "+i);return r=r.replace(/^[^\sa-zA-Z-]+/,""),o}function n(o,l){const h=new Ev;Sd(o,function(u,f){let p;switch(u){case"region":for(let g=e.length-1;g>=0;g--)if(e[g].id===f){h.set(u,e[g].region);break}break;case"vertical":h.alt(u,f,["rl","lr"]);break;case"line":p=f.split(","),h.integer(u,p[0]),h.percent(u,p[0])&&h.set("snapToLines",!1),h.alt(u,p[0],["auto"]),p.length===2&&h.alt("lineAlign",p[1],["start",br,"end"]);break;case"position":p=f.split(","),h.percent(u,p[0]),p.length===2&&h.alt("positionAlign",p[1],["start",br,"end","line-left","line-right","auto"]);break;case"size":h.percent(u,f);break;case"align":h.alt(u,f,["start",br,"end","left","right"]);break}},/:/,/\s/),l.region=h.get("region",null),l.vertical=h.get("vertical","");let d=h.get("line","auto");d==="auto"&&Ta.line===-1&&(d=-1),l.line=d,l.lineAlign=h.get("lineAlign","start"),l.snapToLines=h.get("snapToLines",!0),l.size=h.get("size",100),l.align=h.get("align",br);let c=h.get("position","auto");c==="auto"&&Ta.position===50&&(c=l.align==="start"||l.align==="left"?0:l.align==="end"||l.align==="right"?100:50),l.position=c}function a(){r=r.replace(/^\s+/,"")}if(a(),t.startTime=s(),a(),r.slice(0,3)!=="-->")throw new Error("Malformed time stamp (time stamps must be separated by '-->'): "+i);r=r.slice(3),a(),t.endTime=s(),a(),n(r,t)}function Ld(r){return r.replace(/<br(?: \/)?>/gi,`
174
- `)}class bv{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new yv,this.regionList=[],this.cue=null,this.oncue=void 0,this.onparsingerror=void 0,this.onflush=void 0}parse(t){const e=this;t&&(e.buffer+=e.decoder.decode(t,{stream:!0}));function i(){let n=e.buffer,a=0;for(n=Ld(n);a<n.length&&n[a]!=="\r"&&n[a]!==`
161
+ Aborting and switching to level ${I}`),t.loader&&(this.fragCurrent=this.partCurrent=null,t.abortRequests()),i.trigger(m.FRAG_LOAD_EMERGENCY_ABORTED,{frag:t,part:e,stats:o}))}onFragLoaded(t,{frag:e,part:i}){const s=i?i.stats:e.stats;if(e.type===Z.MAIN&&this.bwEstimator.sampleTTFB(s.loading.first-s.loading.start),!this.ignoreFragment(e)){if(this.clearTimer(),this.lastLoadedFragLevel=e.level,this._nextAutoLevel=-1,this.hls.config.abrMaxWithRealBitrate){const n=i?i.duration:e.duration,a=this.hls.levels[e.level],o=(a.loaded?a.loaded.bytes:0)+s.loaded,l=(a.loaded?a.loaded.duration:0)+n;a.loaded={bytes:o,duration:l},a.realBitrate=Math.round(8*o/l)}if(e.bitrateTest){const n={stats:s,frag:e,part:i,id:e.type};this.onFragBuffered(m.FRAG_BUFFERED,n),e.bitrateTest=!1}}}onFragBuffered(t,e){const{frag:i,part:s}=e,n=s!=null&&s.stats.loaded?s.stats:i.stats;if(n.aborted||this.ignoreFragment(i))return;const 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.bwEstimator.getEstimate(),i.bitrateTest?this.bitrateTestDelay=a/1e3:this.bitrateTestDelay=0}ignoreFragment(t){return t.type!==Z.MAIN||t.sn==="initSegment"}clearTimer(){self.clearInterval(this.timer)}get nextAutoLevel(){const t=this._nextAutoLevel,e=this.bwEstimator;if(t!==-1&&!e.canEstimate())return t;let i=this.getNextABRAutoLevel();if(t!==-1){const s=this.hls.levels;if(s.length>Math.max(t,i)&&s[t].loadError<=s[i].loadError)return t}return t!==-1&&(i=Math.min(t,i)),i}getNextABRAutoLevel(){const{fragCurrent:t,partCurrent:e,hls:i}=this,{maxAutoLevel:s,config:n,minAutoLevel:a,media:o}=i,l=e?e.duration:t?t.duration:0,h=o&&o.playbackRate!==0?Math.abs(o.playbackRate):1,c=this.bwEstimator?this.bwEstimator.getEstimate():n.abrEwmaDefaultEstimate,d=i.mainForwardBufferInfo,u=(d?d.len:0)/h;let f=this.findBestLevel(c,a,s,u,n.abrBandWidthFactor,n.abrBandWidthUpFactor);if(f>=0)return f;_.trace(`[abr] ${u?"rebuffering expected":"buffer is empty"}, finding optimal quality level`);let p=l?Math.min(l,n.maxStarvationDelay):n.maxStarvationDelay,g=n.abrBandWidthFactor,v=n.abrBandWidthUpFactor;if(!u){const E=this.bitrateTestDelay;E&&(p=(l?Math.min(l,n.maxLoadingDelay):n.maxLoadingDelay)-E,_.trace(`[abr] bitrate test took ${Math.round(1e3*E)}ms, set first fragment max fetchDuration to ${Math.round(1e3*p)} ms`),g=v=1)}return f=this.findBestLevel(c,a,s,u+p,g,v),Math.max(f,0)}findBestLevel(t,e,i,s,n,a){var o;const{fragCurrent:l,partCurrent:h,lastLoadedFragLevel:c}=this,{levels:d}=this.hls,u=d[c],f=!!(u!=null&&(o=u.details)!=null&&o.live),p=u==null?void 0:u.codecSet,g=h?h.duration:l?l.duration:0,v=this.bwEstimator.getEstimateTTFB()/1e3;let E=e,A=-1;for(let L=i;L>=e;L--){const y=d[L];if(!y||p&&y.codecSet!==p){y&&(E=Math.min(L,E),A=Math.max(L,A));continue}A!==-1&&_.trace(`[abr] Skipped level(s) ${E}-${A} with CODECS:"${d[A].attrs.CODECS}"; not compatible with "${u.attrs.CODECS}"`);const S=y.details,R=(h?S==null?void 0:S.partTarget:S==null?void 0:S.averagetargetduration)||g;let C;L<=c?C=n*t:C=a*t;const M=d[L].maxBitrate,D=this.getTimeToLoadFrag(v,C,M*R,S===void 0);if(_.trace(`[abr] level:${L} adjustedbw-bitrate:${Math.round(C-M)} avgDuration:${R.toFixed(1)} maxFetchDuration:${s.toFixed(1)} fetchDuration:${D.toFixed(1)}`),C>M&&(D===0||!q(D)||f&&!this.bitrateTestDelay||D<s))return L}return-1}set nextAutoLevel(t){this._nextAutoLevel=t}}class Gh{constructor(){this.chunks=[],this.dataLength=0}push(t){this.chunks.push(t),this.dataLength+=t.length}flush(){const{chunks:t,dataLength:e}=this;let i;if(t.length)t.length===1?i=t[0]:i=_m(t,e);else return new Uint8Array(0);return this.reset(),i}reset(){this.chunks.length=0,this.dataLength=0}}function _m(r,t){const e=new Uint8Array(t);let i=0;for(let s=0;s<r.length;s++){const n=r[s];e.set(n,i),i+=n.length}return e}const Vh=100;class km extends Wn{constructor(t,e,i){super(t,e,i,"[audio-stream-controller]",Z.AUDIO),this.videoBuffer=null,this.videoTrackCC=-1,this.waitingVideoCC=-1,this.bufferedTrack=null,this.switchingTrack=null,this.trackId=-1,this.waitingData=null,this.mainDetails=null,this.bufferFlushed=!1,this.cachedTrackLoadedData=null,this._registerListeners()}onHandlerDestroying(){this._unregisterListeners(),this.mainDetails=null,this.bufferedTrack=null,this.switchingTrack=null}_registerListeners(){const{hls:t}=this;t.on(m.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(m.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(m.MANIFEST_LOADING,this.onManifestLoading,this),t.on(m.LEVEL_LOADED,this.onLevelLoaded,this),t.on(m.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),t.on(m.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on(m.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.on(m.ERROR,this.onError,this),t.on(m.BUFFER_RESET,this.onBufferReset,this),t.on(m.BUFFER_CREATED,this.onBufferCreated,this),t.on(m.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on(m.INIT_PTS_FOUND,this.onInitPtsFound,this),t.on(m.FRAG_BUFFERED,this.onFragBuffered,this)}_unregisterListeners(){const{hls:t}=this;t.off(m.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(m.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(m.MANIFEST_LOADING,this.onManifestLoading,this),t.off(m.LEVEL_LOADED,this.onLevelLoaded,this),t.off(m.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),t.off(m.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off(m.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.off(m.ERROR,this.onError,this),t.off(m.BUFFER_RESET,this.onBufferReset,this),t.off(m.BUFFER_CREATED,this.onBufferCreated,this),t.off(m.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off(m.INIT_PTS_FOUND,this.onInitPtsFound,this),t.off(m.FRAG_BUFFERED,this.onFragBuffered,this)}onInitPtsFound(t,{frag:e,id:i,initPTS:s,timescale:n}){if(i==="main"){const a=e.cc;this.initPTS[e.cc]={baseTime:s,timescale:n},this.log(`InitPTS for cc: ${a} found from main: ${s}`),this.videoTrackCC=a,this.state===B.WAITING_INIT_PTS&&this.tick()}}startLoad(t){if(!this.levels){this.startPosition=t,this.state=B.STOPPED;return}const e=this.lastCurrentTime;this.stopLoad(),this.setInterval(Vh),e>0&&t===-1?(this.log(`Override startPosition with lastCurrentTime @${e.toFixed(3)}`),t=e,this.state=B.IDLE):(this.loadedmetadata=!1,this.state=B.WAITING_TRACK),this.nextLoadPosition=this.startPosition=this.lastCurrentTime=t,this.tick()}doTick(){switch(this.state){case B.IDLE:this.doTickIdle();break;case B.WAITING_TRACK:{var t;const{levels:i,trackId:s}=this,n=i==null||(t=i[s])==null?void 0:t.details;if(n){if(this.waitForCdnTuneIn(n))break;this.state=B.WAITING_INIT_PTS}break}case B.FRAG_LOADING_WAITING_RETRY:{var e;const i=performance.now(),s=this.retryDate;(!s||i>=s||(e=this.media)!=null&&e.seeking)&&(this.log("RetryDate reached, switch back to IDLE state"),this.resetStartWhenNotLoaded(this.trackId),this.state=B.IDLE);break}case B.WAITING_INIT_PTS:{const i=this.waitingData;if(i){const{frag:s,part:n,cache:a,complete:o}=i;if(this.initPTS[s.cc]!==void 0){this.waitingData=null,this.waitingVideoCC=-1,this.state=B.FRAG_LOADING;const l=a.flush(),h={frag:s,part:n,payload:l,networkDetails:null};this._handleFragmentLoadProgress(h),o&&super._handleFragmentLoadComplete(h)}else if(this.videoTrackCC!==this.waitingVideoCC)this.log(`Waiting fragment cc (${s.cc}) cancelled because video is at cc ${this.videoTrackCC}`),this.clearWaitingFragment();else{const l=this.getLoadPosition(),h=Et.bufferInfo(this.mediaBuffer,l,this.config.maxBufferHole);Bn(h.end,this.config.maxFragLookUpTolerance,s)<0&&(this.log(`Waiting fragment cc (${s.cc}) @ ${s.start} cancelled because another fragment at ${h.end} is needed`),this.clearWaitingFragment())}}else this.state=B.IDLE}}this.onTickEnd()}clearWaitingFragment(){const t=this.waitingData;t&&(this.fragmentTracker.removeFragment(t.frag),this.waitingData=null,this.waitingVideoCC=-1,this.state=B.IDLE)}resetLoadingState(){this.clearWaitingFragment(),super.resetLoadingState()}onTickEnd(){const{media:t}=this;t!=null&&t.readyState&&(this.lastCurrentTime=t.currentTime)}doTickIdle(){const{hls:t,levels:e,media:i,trackId:s}=this,n=t.config;if(!(e!=null&&e[s])||!i&&(this.startFragRequested||!n.startFragPrefetch))return;const a=e[s],o=a.details;if(!o||o.live&&this.levelLastLoaded!==s||this.waitForCdnTuneIn(o)){this.state=B.WAITING_TRACK;return}const l=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&l&&(this.bufferFlushed=!1,this.afterBufferFlushed(l,mt.AUDIO,Z.AUDIO));const h=this.getFwdBufferInfo(l,Z.AUDIO);if(h===null)return;const{bufferedTrack:c,switchingTrack:d}=this;if(!d&&this._streamEnded(h,o)){t.trigger(m.BUFFER_EOS,{type:"audio"}),this.state=B.ENDED;return}const u=this.getFwdBufferInfo(this.videoBuffer?this.videoBuffer:this.media,Z.MAIN),f=h.len,p=this.getMaxBufferLength(u==null?void 0:u.len);if(f>=p&&!d)return;const g=o.fragments[0].start;let v=h.end;if(d&&i){const y=this.getLoadPosition();c&&d.attrs!==c.attrs&&(v=y),o.PTSKnown&&y<g&&(h.end>g||h.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),i.currentTime=g+.05)}let E=this.getNextFragment(v,o),A=!1;if(E&&this.isLoopLoading(E,v)&&(A=!!E.gap,E=this.getNextFragmentLoopLoading(E,o,h,Z.MAIN,p)),!E){this.bufferFlushed=!0;return}const L=u&&E.start>u.end+o.targetduration;if(L||!(u!=null&&u.len)&&h.len){const y=this.getAppendedFrag(E.start,Z.MAIN);if(y===null||(A||(A=!!y.gap||!!L&&u.len===0),L&&!A||A&&h.nextStart&&h.nextStart<y.end))return}this.loadFragment(E,a,v)}getMaxBufferLength(t){const e=super.getMaxBufferLength();return t?Math.min(Math.max(e,t),this.config.maxMaxBufferLength):e}onMediaDetaching(){this.videoBuffer=null,super.onMediaDetaching()}onAudioTracksUpdated(t,{audioTracks:e}){this.resetTransmuxer(),this.levels=e.map(i=>new Ts(i))}onAudioTrackSwitching(t,e){const i=!!e.url;this.trackId=e.id;const{fragCurrent:s}=this;s&&(s.abortRequests(),this.removeUnbufferedFrags(s.start)),this.resetLoadingState(),i?this.setInterval(Vh):this.resetTransmuxer(),i?(this.switchingTrack=e,this.state=B.IDLE):(this.switchingTrack=null,this.bufferedTrack=e,this.state=B.STOPPED),this.tick()}onManifestLoading(){this.fragmentTracker.removeAllFragments(),this.startPosition=this.lastCurrentTime=0,this.bufferFlushed=!1,this.levels=this.mainDetails=this.waitingData=this.bufferedTrack=this.cachedTrackLoadedData=this.switchingTrack=null,this.startFragRequested=!1,this.trackId=this.videoTrackCC=this.waitingVideoCC=-1}onLevelLoaded(t,e){this.mainDetails=e.details,this.cachedTrackLoadedData!==null&&(this.hls.trigger(m.AUDIO_TRACK_LOADED,this.cachedTrackLoadedData),this.cachedTrackLoadedData=null)}onAudioTrackLoaded(t,e){var i;if(this.mainDetails==null){this.cachedTrackLoadedData=e;return}const{levels:s}=this,{details:n,id:a}=e;if(!s){this.warn(`Audio tracks were reset while loading level ${a}`);return}this.log(`Track ${a} loaded [${n.startSN},${n.endSN}]${n.lastPartSn?`[part-${n.lastPartSn}-${n.lastPartIndex}]`:""},duration:${n.totalduration}`);const o=s[a];let l=0;if(n.live||(i=o.details)!=null&&i.live){this.checkLiveUpdate(n);const h=this.mainDetails;if(n.deltaUpdateFailed||!h)return;!o.details&&n.hasProgramDateTime&&h.hasProgramDateTime?(bh(n,h),l=n.fragments[0].start):l=this.alignPlaylists(n,o.details)}o.details=n,this.levelLastLoaded=a,!this.startFragRequested&&(this.mainDetails||!n.live)&&this.setStartPosition(o.details,l),this.state===B.WAITING_TRACK&&!this.waitForCdnTuneIn(n)&&(this.state=B.IDLE),this.tick()}_handleFragmentLoadProgress(t){var e;const{frag:i,part:s,payload:n}=t,{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}const h=l[o];if(!h){this.warn("Audio track is undefined on fragment load progress");return}const c=h.details;if(!c){this.warn("Audio track details undefined on fragment load progress"),this.removeUnbufferedFrags(i.start);return}const d=a.defaultAudioCodec||h.audioCodec||"mp4a.40.2";let u=this.transmuxer;u||(u=this.transmuxer=new Hh(this.hls,Z.AUDIO,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));const f=this.initPTS[i.cc],p=(e=i.initSegment)==null?void 0:e.data;if(f!==void 0){const g=s?s.index:-1,v=g!==-1,E=new Vn(i.level,i.sn,i.stats.chunkCount,n.byteLength,g,v);u.push(n,p,d,"",i,s,c.totalduration,!1,E,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}`);const{cache:g}=this.waitingData=this.waitingData||{frag:i,part:s,cache:new Gh,complete:!1};g.push(new Uint8Array(n)),this.waitingVideoCC=this.videoTrackCC,this.state=B.WAITING_INIT_PTS}}_handleFragmentLoadComplete(t){if(this.waitingData){this.waitingData.complete=!0;return}super._handleFragmentLoadComplete(t)}onBufferReset(){this.mediaBuffer=this.videoBuffer=null,this.loadedmetadata=!1}onBufferCreated(t,e){const i=e.tracks.audio;i&&(this.mediaBuffer=i.buffer||null),e.tracks.video&&(this.videoBuffer=e.tracks.video.buffer||null)}onFragBuffered(t,e){const{frag:i,part:s}=e;if(i.type!==Z.AUDIO){if(!this.loadedmetadata&&i.type===Z.MAIN){const n=this.videoBuffer||this.media;n&&Et.getBuffered(n).length&&(this.loadedmetadata=!0)}return}if(this.fragContextChanged(i)){this.warn(`Fragment ${i.sn}${s?" p: "+s.index:""} of level ${i.level} finished buffering, but was aborted. state: ${this.state}, audioSwitch: ${this.switchingTrack?this.switchingTrack.name:"false"}`);return}if(i.sn!=="initSegment"){this.fragPrevious=i;const n=this.switchingTrack;n&&(this.bufferedTrack=n,this.switchingTrack=null,this.hls.trigger(m.AUDIO_TRACK_SWITCHED,Qt({},n)))}this.fragBufferedComplete(i,s)}onError(t,e){var i;if(e.fatal){this.state=B.ERROR;return}switch(e.details){case $.FRAG_GAP:case $.FRAG_PARSING_ERROR:case $.FRAG_DECRYPT_ERROR:case $.FRAG_LOAD_ERROR:case $.FRAG_LOAD_TIMEOUT:case $.KEY_LOAD_ERROR:case $.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(Z.AUDIO,e);break;case $.AUDIO_TRACK_LOAD_ERROR:case $.AUDIO_TRACK_LOAD_TIMEOUT:case $.LEVEL_PARSING_ERROR:!e.levelRetry&&this.state===B.WAITING_TRACK&&((i=e.context)==null?void 0:i.type)===ct.AUDIO_TRACK&&(this.state=B.IDLE);break;case $.BUFFER_FULL_ERROR:if(!e.parent||e.parent!=="audio")return;this.reduceLengthAndFlushBuffer(e)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case $.INTERNAL_EXCEPTION:this.recoverWorkerError(e);break}}onBufferFlushed(t,{type:e}){e===mt.AUDIO&&(this.bufferFlushed=!0,this.state===B.ENDED&&(this.state=B.IDLE))}_handleTransmuxComplete(t){var e;const i="audio",{hls:s}=this,{remuxResult:n,chunkMeta:a}=t,o=this.getCurrentContext(a);if(!o){this.resetWhenMissingContext(a);return}const{frag:l,part:h,level:c}=o,{details:d}=c,{audio:u,text:f,id3:p,initSegment:g}=n;if(this.fragContextChanged(l)||!d){this.fragmentTracker.removeFragment(l);return}if(this.state=B.PARSING,this.switchingTrack&&u&&this.completeAudioSwitch(this.switchingTrack),g!=null&&g.tracks){const v=l.initSegment||l;this._bufferInitSegment(g.tracks,v,a),s.trigger(m.FRAG_PARSING_INIT_SEGMENT,{frag:v,id:i,tracks:g.tracks})}if(u){const{startPTS:v,endPTS:E,startDTS:A,endDTS:L}=u;h&&(h.elementaryStreams[mt.AUDIO]={startPTS:v,endPTS:E,startDTS:A,endDTS:L}),l.setElementaryStreamInfo(mt.AUDIO,v,E,A,L),this.bufferFragmentData(u,l,h,a)}if(p!=null&&(e=p.samples)!=null&&e.length){const v=Dt({id:i,frag:l,details:d},p);s.trigger(m.FRAG_PARSING_METADATA,v)}if(f){const v=Dt({id:i,frag:l,details:d},f);s.trigger(m.FRAG_PARSING_USERDATA,v)}}_bufferInitSegment(t,e,i){if(this.state!==B.PARSING)return;t.video&&delete t.video;const s=t.audio;if(!s)return;s.levelCodec=s.codec,s.id="audio",this.log(`Init audio buffer, container:${s.container}, codecs[parsed]=[${s.codec}]`),this.hls.trigger(m.BUFFER_CODECS,t);const n=s.initSegment;if(n!=null&&n.byteLength){const a={type:"audio",frag:e,part:null,chunkMeta:i,parent:e.type,data:n};this.hls.trigger(m.BUFFER_APPENDING,a)}this.tick()}loadFragment(t,e,i){const s=this.fragmentTracker.getState(t);if(this.fragCurrent=t,this.switchingTrack||s===$t.NOT_LOADED||s===$t.PARTIAL){var n;t.sn==="initSegment"?this._loadInitSegment(t,e):(n=e.details)!=null&&n.live&&!this.initPTS[t.cc]?(this.log(`Waiting for video PTS in continuity counter ${t.cc} of live stream before loading audio fragment ${t.sn} of level ${this.trackId}`),this.state=B.WAITING_INIT_PTS):(this.startFragRequested=!0,super.loadFragment(t,e,i))}else this.clearTrackerIfNeeded(t)}completeAudioSwitch(t){const{hls:e,media:i,bufferedTrack:s}=this,n=s==null?void 0:s.attrs,a=t.attrs;i&&n&&(n.CHANNELS!==a.CHANNELS||n.NAME!==a.NAME||n.LANGUAGE!==a.LANGUAGE)&&(this.log("Switching audio track : flushing all audio"),super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio")),this.bufferedTrack=t,this.switchingTrack=null,e.trigger(m.AUDIO_TRACK_SWITCHED,Qt({},t))}}class Im extends Hn{constructor(t){super(t,"[audio-track-controller]"),this.tracks=[],this.groupId=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.registerListeners()}registerListeners(){const{hls:t}=this;t.on(m.MANIFEST_LOADING,this.onManifestLoading,this),t.on(m.MANIFEST_PARSED,this.onManifestParsed,this),t.on(m.LEVEL_LOADING,this.onLevelLoading,this),t.on(m.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(m.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.on(m.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(m.MANIFEST_LOADING,this.onManifestLoading,this),t.off(m.MANIFEST_PARSED,this.onManifestParsed,this),t.off(m.LEVEL_LOADING,this.onLevelLoading,this),t.off(m.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(m.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.off(m.ERROR,this.onError,this)}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,super.destroy()}onManifestLoading(){this.tracks=[],this.groupId=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0}onManifestParsed(t,e){this.tracks=e.audioTracks||[]}onAudioTrackLoaded(t,e){const{id:i,groupId:s,details:n}=e,a=this.tracksInGroup[i];if(!a||a.groupId!==s){this.warn(`Track with id:${i} and group:${s} not found in active group ${a.groupId}`);return}const o=a.details;a.details=e.details,this.log(`audio-track ${i} "${a.name}" lang:${a.lang} group:${s} loaded [${n.startSN}-${n.endSN}]`),i===this.trackId&&this.playlistLoaded(i,e,o)}onLevelLoading(t,e){this.switchLevel(e.level)}onLevelSwitching(t,e){this.switchLevel(e.level)}switchLevel(t){const e=this.hls.levels[t];if(!(e!=null&&e.audioGroupIds))return;const i=e.audioGroupIds[e.urlId];if(this.groupId!==i){this.groupId=i||null;const s=this.tracks.filter(a=>!i||a.groupId===i);this.selectDefaultTrack&&!s.some(a=>a.default)&&(this.selectDefaultTrack=!1),this.tracksInGroup=s;const n={audioTracks:s};this.log(`Updating audio tracks, ${s.length} track(s) found in group:${i}`),this.hls.trigger(m.AUDIO_TRACKS_UPDATED,n),this.selectInitialTrack()}else this.shouldReloadPlaylist(this.currentTrack)&&this.setAudioTrack(this.trackId)}onError(t,e){e.fatal||!e.context||e.context.type===ct.AUDIO_TRACK&&e.context.id===this.trackId&&e.context.groupId===this.groupId&&(this.requestScheduled=-1,this.checkRetry(e))}get audioTracks(){return this.tracksInGroup}get audioTrack(){return this.trackId}set audioTrack(t){this.selectDefaultTrack=!1,this.setAudioTrack(t)}setAudioTrack(t){const e=this.tracksInGroup;if(t<0||t>=e.length){this.warn("Invalid id passed to audio-track controller");return}this.clearTimer();const i=this.currentTrack;e[this.trackId];const s=e[t],{groupId:n,name:a}=s;if(this.log(`Switching to audio-track ${t} "${a}" lang:${s.lang} group:${n}`),this.trackId=t,this.currentTrack=s,this.selectDefaultTrack=!1,this.hls.trigger(m.AUDIO_TRACK_SWITCHING,Qt({},s)),s.details&&!s.details.live)return;const o=this.switchParams(s.url,i==null?void 0:i.details);this.loadPlaylist(o)}selectInitialTrack(){const t=this.tracksInGroup,e=this.findTrackId(this.currentTrack)|this.findTrackId(null);if(e!==-1)this.setAudioTrack(e);else{const i=new Error(`No track found for running audio group-ID: ${this.groupId} track count: ${t.length}`);this.warn(i.message),this.hls.trigger(m.ERROR,{type:Q.MEDIA_ERROR,details:$.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:i})}}findTrackId(t){const e=this.tracksInGroup;for(let i=0;i<e.length;i++){const s=e[i];if((!this.selectDefaultTrack||s.default)&&(!t||t.attrs["STABLE-RENDITION-ID"]!==void 0&&t.attrs["STABLE-RENDITION-ID"]===s.attrs["STABLE-RENDITION-ID"]||t.name===s.name&&t.lang===s.lang))return s.id}return-1}loadPlaylist(t){super.loadPlaylist();const e=this.tracksInGroup[this.trackId];if(this.shouldLoadPlaylist(e)){const i=e.id,s=e.groupId;let n=e.url;if(t)try{n=t.addDirectives(n)}catch(a){this.warn(`Could not construct new URL with HLS Delivery Directives: ${a}`)}this.log(`loading audio-track playlist ${i} "${e.name}" lang:${e.lang} group:${s}`),this.clearTimer(),this.hls.trigger(m.AUDIO_TRACK_LOADING,{url:n,id:i,groupId:s,deliveryDirectives:t||null})}}}function Kh(r,t){if(r.length!==t.length)return!1;for(let e=0;e<r.length;e++)if(!Cm(r[e].attrs,t[e].attrs))return!1;return!0}function Cm(r,t){const e=r["STABLE-RENDITION-ID"];return e?e===t["STABLE-RENDITION-ID"]:!["LANGUAGE","NAME","CHARACTERISTICS","AUTOSELECT","DEFAULT","FORCED"].some(i=>r[i]!==t[i])}const jh=500;class Dm extends Wn{constructor(t,e,i){super(t,e,i,"[subtitle-stream-controller]",Z.SUBTITLE),this.levels=[],this.currentTrackId=-1,this.tracksBuffered=[],this.mainDetails=null,this._registerListeners()}onHandlerDestroying(){this._unregisterListeners(),this.mainDetails=null}_registerListeners(){const{hls:t}=this;t.on(m.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(m.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(m.MANIFEST_LOADING,this.onManifestLoading,this),t.on(m.LEVEL_LOADED,this.onLevelLoaded,this),t.on(m.ERROR,this.onError,this),t.on(m.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.on(m.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.on(m.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.on(m.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),t.on(m.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(m.FRAG_BUFFERED,this.onFragBuffered,this)}_unregisterListeners(){const{hls:t}=this;t.off(m.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(m.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(m.MANIFEST_LOADING,this.onManifestLoading,this),t.off(m.LEVEL_LOADED,this.onLevelLoaded,this),t.off(m.ERROR,this.onError,this),t.off(m.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.off(m.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.off(m.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.off(m.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),t.off(m.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(m.FRAG_BUFFERED,this.onFragBuffered,this)}startLoad(t){this.stopLoad(),this.state=B.IDLE,this.setInterval(jh),this.nextLoadPosition=this.startPosition=this.lastCurrentTime=t,this.tick()}onManifestLoading(){this.mainDetails=null,this.fragmentTracker.removeAllFragments()}onMediaDetaching(){this.tracksBuffered=[],super.onMediaDetaching()}onLevelLoaded(t,e){this.mainDetails=e.details}onSubtitleFragProcessed(t,e){const{frag:i,success:s}=e;if(this.fragPrevious=i,this.state=B.IDLE,!s)return;const n=this.tracksBuffered[this.currentTrackId];if(!n)return;let a;const o=i.start;for(let h=0;h<n.length;h++)if(o>=n[h].start&&o<=n[h].end){a=n[h];break}const l=i.start+i.duration;a?a.end=l:(a={start:o,end:l},n.push(a)),this.fragmentTracker.fragBuffered(i)}onBufferFlushing(t,e){const{startOffset:i,endOffset:s}=e;if(i===0&&s!==Number.POSITIVE_INFINITY){const n=s-1;if(n<=0)return;e.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,Z.SUBTITLE)}}onFragBuffered(t,e){if(!this.loadedmetadata&&e.frag.type===Z.MAIN){var i;(i=this.media)!=null&&i.buffered.length&&(this.loadedmetadata=!0)}}onError(t,e){const i=e.frag;(i==null?void 0:i.type)===Z.SUBTITLE&&(this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==B.STOPPED&&(this.state=B.IDLE))}onSubtitleTracksUpdated(t,{subtitleTracks:e}){if(Kh(this.levels,e)){this.levels=e.map(i=>new Ts(i));return}this.tracksBuffered=[],this.levels=e.map(i=>{const s=new Ts(i);return this.tracksBuffered[s.id]=[],s}),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,Z.SUBTITLE),this.fragPrevious=null,this.mediaBuffer=null}onSubtitleTrackSwitch(t,e){if(this.currentTrackId=e.id,!this.levels.length||this.currentTrackId===-1){this.clearInterval();return}const i=this.levels[this.currentTrackId];i!=null&&i.details?this.mediaBuffer=this.mediaBufferTimeRanges:this.mediaBuffer=null,i&&this.setInterval(jh)}onSubtitleTrackLoaded(t,e){var i;const{details:s,id:n}=e,{currentTrackId:a,levels:o}=this;if(!o.length)return;const l=o[a];if(n>=o.length||n!==a||!l)return;this.mediaBuffer=this.mediaBufferTimeRanges;let h=0;if(s.live||(i=l.details)!=null&&i.live){const c=this.mainDetails;if(s.deltaUpdateFailed||!c)return;const d=c.fragments[0];l.details?(h=this.alignPlaylists(s,l.details),h===0&&d&&(h=d.start,Nn(s,h))):s.hasProgramDateTime&&c.hasProgramDateTime?(bh(s,c),h=s.fragments[0].start):d&&(h=d.start,Nn(s,h))}l.details=s,this.levelLastLoaded=n,!this.startFragRequested&&(this.mainDetails||!s.live)&&this.setStartPosition(l.details,h),this.tick(),s.live&&!this.fragCurrent&&this.media&&this.state===B.IDLE&&(As(null,s.fragments,this.media.currentTime,0)||(this.warn("Subtitle playlist not aligned with playback"),l.details=void 0))}_handleFragmentLoadComplete(t){const{frag:e,payload:i}=t,s=e.decryptdata,n=this.hls;if(!this.fragContextChanged(e)&&i&&i.byteLength>0&&s&&s.key&&s.iv&&s.method==="AES-128"){const a=performance.now();this.decrypter.decrypt(new Uint8Array(i),s.key.buffer,s.iv.buffer).catch(o=>{throw n.trigger(m.ERROR,{type:Q.MEDIA_ERROR,details:$.FRAG_DECRYPT_ERROR,fatal:!1,error:o,reason:o.message,frag:e}),o}).then(o=>{const l=performance.now();n.trigger(m.FRAG_DECRYPTED,{frag:e,payload:o,stats:{tstart:a,tdecrypt:l}})}).catch(o=>{this.warn(`${o.name}: ${o.message}`),this.state=B.IDLE})}}doTick(){if(!this.media){this.state=B.IDLE;return}if(this.state===B.IDLE){const{currentTrackId:t,levels:e}=this,i=e[t];if(!e.length||!i||!i.details)return;const{config:s}=this,n=this.getLoadPosition(),a=Et.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],n,s.maxBufferHole),{end:o,len:l}=a,h=this.getFwdBufferInfo(this.media,Z.MAIN),c=i.details,d=this.getMaxBufferLength(h==null?void 0:h.len)+c.levelTargetDuration;if(l>d)return;const u=c.fragments,f=u.length,p=c.edge;let g=null;const v=this.fragPrevious;if(o<p){const E=s.maxFragLookUpTolerance,A=o>p-E?0:E;g=As(v,u,Math.max(u[0].start,o),A),!g&&v&&v.start<u[0].start&&(g=u[0])}else g=u[f-1];if(!g)return;if(g=this.mapToInitFragWhenRequired(g),g.sn!=="initSegment"){const E=g.sn-c.startSN,A=u[E-1];A&&A.cc===g.cc&&this.fragmentTracker.getState(A)===$t.NOT_LOADED&&(g=A)}this.fragmentTracker.getState(g)===$t.NOT_LOADED&&this.loadFragment(g,i,o)}}getMaxBufferLength(t){const e=super.getMaxBufferLength();return t?Math.max(e,t):e}loadFragment(t,e,i){this.fragCurrent=t,t.sn==="initSegment"?this._loadInitSegment(t,e):(this.startFragRequested=!0,super.loadFragment(t,e,i))}get mediaBufferTimeRanges(){return new xm(this.tracksBuffered[this.currentTrackId]||[])}}class xm{constructor(t){this.buffered=void 0;const e=(i,s,n)=>{if(s=s>>>0,s>n-1)throw new DOMException(`Failed to execute '${i}' on 'TimeRanges': The index provided (${s}) is greater than the maximum bound (${n})`);return t[s][i]};this.buffered={get length(){return t.length},end(i){return e("end",i,t.length)},start(i){return e("start",i,t.length)}}}}class Pm extends Hn{constructor(t){super(t,"[subtitle-track-controller]"),this.media=null,this.tracks=[],this.groupId=null,this.tracksInGroup=[],this.trackId=-1,this.selectDefaultTrack=!0,this.queuedDefaultTrack=-1,this.trackChangeListener=()=>this.onTextTracksChanged(),this.asyncPollTrackChange=()=>this.pollTrackChange(0),this.useTextTrackPolling=!1,this.subtitlePollingInterval=-1,this._subtitleDisplay=!0,this.registerListeners()}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.trackChangeListener=this.asyncPollTrackChange=null,super.destroy()}get subtitleDisplay(){return this._subtitleDisplay}set subtitleDisplay(t){this._subtitleDisplay=t,this.trackId>-1&&this.toggleTrackModes(this.trackId)}registerListeners(){const{hls:t}=this;t.on(m.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(m.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(m.MANIFEST_LOADING,this.onManifestLoading,this),t.on(m.MANIFEST_PARSED,this.onManifestParsed,this),t.on(m.LEVEL_LOADING,this.onLevelLoading,this),t.on(m.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(m.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.on(m.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(m.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(m.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(m.MANIFEST_LOADING,this.onManifestLoading,this),t.off(m.MANIFEST_PARSED,this.onManifestParsed,this),t.off(m.LEVEL_LOADING,this.onLevelLoading,this),t.off(m.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(m.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.off(m.ERROR,this.onError,this)}onMediaAttached(t,e){this.media=e.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(t){self.clearInterval(this.subtitlePollingInterval),this.subtitlePollingInterval=self.setInterval(this.trackChangeListener,t)}onMediaDetaching(){this.media&&(self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||this.media.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId),ra(this.media.textTracks).forEach(t=>{ki(t)}),this.subtitleTrack=-1,this.media=null)}onManifestLoading(){this.tracks=[],this.groupId=null,this.tracksInGroup=[],this.trackId=-1,this.selectDefaultTrack=!0}onManifestParsed(t,e){this.tracks=e.subtitleTracks}onSubtitleTrackLoaded(t,e){const{id:i,details:s}=e,{trackId:n}=this,a=this.tracksInGroup[n];if(!a){this.warn(`Invalid subtitle track id ${i}`);return}const o=a.details;a.details=e.details,this.log(`subtitle track ${i} loaded [${s.startSN}-${s.endSN}]`),i===this.trackId&&this.playlistLoaded(i,e,o)}onLevelLoading(t,e){this.switchLevel(e.level)}onLevelSwitching(t,e){this.switchLevel(e.level)}switchLevel(t){const e=this.hls.levels[t];if(!(e!=null&&e.textGroupIds))return;const i=e.textGroupIds[e.urlId],s=this.tracksInGroup?this.tracksInGroup[this.trackId]:void 0;if(this.groupId!==i){const n=this.tracks.filter(l=>!i||l.groupId===i);this.tracksInGroup=n;const a=this.findTrackId(s==null?void 0:s.name)||this.findTrackId();this.groupId=i||null;const o={subtitleTracks:n};this.log(`Updating subtitle tracks, ${n.length} track(s) found in "${i}" group-id`),this.hls.trigger(m.SUBTITLE_TRACKS_UPDATED,o),a!==-1&&this.setSubtitleTrack(a,s)}else this.shouldReloadPlaylist(s)&&this.setSubtitleTrack(this.trackId,s)}findTrackId(t){const e=this.tracksInGroup;for(let i=0;i<e.length;i++){const s=e[i];if((!this.selectDefaultTrack||s.default)&&(!t||t===s.name))return s.id}return-1}onError(t,e){e.fatal||!e.context||e.context.type===ct.SUBTITLE_TRACK&&e.context.id===this.trackId&&e.context.groupId===this.groupId&&this.checkRetry(e)}get subtitleTracks(){return this.tracksInGroup}get subtitleTrack(){return this.trackId}set subtitleTrack(t){this.selectDefaultTrack=!1;const e=this.tracksInGroup?this.tracksInGroup[this.trackId]:void 0;this.setSubtitleTrack(t,e)}loadPlaylist(t){super.loadPlaylist();const e=this.tracksInGroup[this.trackId];if(this.shouldLoadPlaylist(e)){const i=e.id,s=e.groupId;let n=e.url;if(t)try{n=t.addDirectives(n)}catch(a){this.warn(`Could not construct new URL with HLS Delivery Directives: ${a}`)}this.log(`Loading subtitle playlist for id ${i}`),this.hls.trigger(m.SUBTITLE_TRACK_LOADING,{url:n,id:i,groupId:s,deliveryDirectives:t||null})}}toggleTrackModes(t){const{media:e,trackId:i}=this;if(!e)return;const s=ra(e.textTracks),n=s.filter(o=>o.groupId===this.groupId);if(t===-1)[].slice.call(s).forEach(o=>{o.mode="disabled"});else{const o=n[i];o&&(o.mode="disabled")}const a=n[t];a&&(a.mode=this.subtitleDisplay?"showing":"hidden")}setSubtitleTrack(t,e){var i;const s=this.tracksInGroup;if(!this.media){this.queuedDefaultTrack=t;return}if(this.trackId!==t&&this.toggleTrackModes(t),this.trackId===t&&(t===-1||(i=s[t])!=null&&i.details)||t<-1||t>=s.length)return;this.clearTimer();const n=s[t];if(this.log(`Switching to subtitle-track ${t}`+(n?` "${n.name}" lang:${n.lang} group:${n.groupId}`:"")),this.trackId=t,n){const{id:a,groupId:o="",name:l,type:h,url:c}=n;this.hls.trigger(m.SUBTITLE_TRACK_SWITCH,{id:a,groupId:o,name:l,type:h,url:c});const d=this.switchParams(n.url,e==null?void 0:e.details);this.loadPlaylist(d)}else this.hls.trigger(m.SUBTITLE_TRACK_SWITCH,{id:t})}onTextTracksChanged(){if(this.useTextTrackPolling||self.clearInterval(this.subtitlePollingInterval),!this.media||!this.hls.config.renderTextTracksNatively)return;let t=-1;const e=ra(this.media.textTracks);for(let i=0;i<e.length;i++)if(e[i].mode==="hidden")t=i;else if(e[i].mode==="showing"){t=i;break}this.subtitleTrack!==t&&(this.subtitleTrack=t)}}function ra(r){const t=[];for(let e=0;e<r.length;e++){const i=r[e];(i.kind==="subtitles"||i.kind==="captions")&&i.label&&t.push(r[e])}return t}class Om{constructor(t){this.buffers=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.buffers=t}append(t,e){const i=this.queues[e];i.push(t),i.length===1&&this.buffers[e]&&this.executeNext(e)}insertAbort(t,e){this.queues[e].unshift(t),this.executeNext(e)}appendBlocker(t){let e;const i=new Promise(n=>{e=n}),s={execute:e,onStart:()=>{},onComplete:()=>{},onError:()=>{}};return this.append(s,t),i}executeNext(t){const{buffers:e,queues:i}=this,s=e[t],n=i[t];if(n.length){const a=n[0];try{a.execute()}catch(o){_.warn("[buffer-operation-queue]: Unhandled exception executing the current operation"),a.onError(o),s!=null&&s.updating||(n.shift(),this.executeNext(t))}}}shiftAndExecuteNext(t){this.queues[t].shift(),this.executeNext(t)}current(t){return this.queues[t][0]}}const Wh=lr(),Yh=/([ha]vc.)(?:\.[^.,]+)+/;class $m{constructor(t){this.details=null,this._objectUrl=null,this.operationQueue=void 0,this.listeners=void 0,this.hls=void 0,this.bufferCodecEventsExpected=0,this._bufferCodecEventsTotal=0,this.media=null,this.mediaSource=null,this.lastMpegAudioChunk=null,this.appendError=0,this.tracks={},this.pendingTracks={},this.sourceBuffer=void 0,this._onMediaSourceOpen=()=>{const{media:e,mediaSource:i}=this;_.log("[buffer-controller]: Media source opened"),e&&(e.removeEventListener("emptied",this._onMediaEmptied),this.updateMediaElementDuration(),this.hls.trigger(m.MEDIA_ATTACHED,{media:e})),i&&i.removeEventListener("sourceopen",this._onMediaSourceOpen),this.checkPendingTracks()},this._onMediaSourceClose=()=>{_.log("[buffer-controller]: Media source closed")},this._onMediaSourceEnded=()=>{_.log("[buffer-controller]: Media source ended")},this._onMediaEmptied=()=>{const{media:e,_objectUrl:i}=this;e&&e.src!==i&&_.error(`Media element src was set while attaching MediaSource (${i} > ${e.src})`)},this.hls=t,this._initSourceBuffer(),this.registerListeners()}hasSourceTypes(){return this.getSourceBufferTypes().length>0||Object.keys(this.pendingTracks).length>0}destroy(){this.unregisterListeners(),this.details=null,this.lastMpegAudioChunk=null}registerListeners(){const{hls:t}=this;t.on(m.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(m.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(m.MANIFEST_LOADING,this.onManifestLoading,this),t.on(m.MANIFEST_PARSED,this.onManifestParsed,this),t.on(m.BUFFER_RESET,this.onBufferReset,this),t.on(m.BUFFER_APPENDING,this.onBufferAppending,this),t.on(m.BUFFER_CODECS,this.onBufferCodecs,this),t.on(m.BUFFER_EOS,this.onBufferEos,this),t.on(m.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(m.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(m.FRAG_PARSED,this.onFragParsed,this),t.on(m.FRAG_CHANGED,this.onFragChanged,this)}unregisterListeners(){const{hls:t}=this;t.off(m.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(m.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(m.MANIFEST_LOADING,this.onManifestLoading,this),t.off(m.MANIFEST_PARSED,this.onManifestParsed,this),t.off(m.BUFFER_RESET,this.onBufferReset,this),t.off(m.BUFFER_APPENDING,this.onBufferAppending,this),t.off(m.BUFFER_CODECS,this.onBufferCodecs,this),t.off(m.BUFFER_EOS,this.onBufferEos,this),t.off(m.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(m.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(m.FRAG_PARSED,this.onFragParsed,this),t.off(m.FRAG_CHANGED,this.onFragChanged,this)}_initSourceBuffer(){this.sourceBuffer={},this.operationQueue=new Om(this.sourceBuffer),this.listeners={audio:[],video:[],audiovideo:[]},this.lastMpegAudioChunk=null}onManifestLoading(){this.bufferCodecEventsExpected=this._bufferCodecEventsTotal=0,this.details=null}onManifestParsed(t,e){let i=2;(e.audio&&!e.video||!e.altAudio)&&(i=1),this.bufferCodecEventsExpected=this._bufferCodecEventsTotal=i,_.log(`${this.bufferCodecEventsExpected} bufferCodec event(s) expected`)}onMediaAttaching(t,e){const i=this.media=e.media;if(i&&Wh){const s=this.mediaSource=new Wh;s.addEventListener("sourceopen",this._onMediaSourceOpen),s.addEventListener("sourceended",this._onMediaSourceEnded),s.addEventListener("sourceclose",this._onMediaSourceClose),i.src=self.URL.createObjectURL(s),this._objectUrl=i.src,i.addEventListener("emptied",this._onMediaEmptied)}}onMediaDetaching(){const{media:t,mediaSource:e,_objectUrl:i}=this;if(e){if(_.log("[buffer-controller]: media source detaching"),e.readyState==="open")try{e.endOfStream()}catch(s){_.warn(`[buffer-controller]: onMediaDetaching: ${s.message} while calling endOfStream`)}this.onBufferReset(),e.removeEventListener("sourceopen",this._onMediaSourceOpen),e.removeEventListener("sourceended",this._onMediaSourceEnded),e.removeEventListener("sourceclose",this._onMediaSourceClose),t&&(t.removeEventListener("emptied",this._onMediaEmptied),i&&self.URL.revokeObjectURL(i),t.src===i?(t.removeAttribute("src"),t.load()):_.warn("[buffer-controller]: media.src was changed by a third party - skip cleanup")),this.mediaSource=null,this.media=null,this._objectUrl=null,this.bufferCodecEventsExpected=this._bufferCodecEventsTotal,this.pendingTracks={},this.tracks={}}this.hls.trigger(m.MEDIA_DETACHED,void 0)}onBufferReset(){this.getSourceBufferTypes().forEach(t=>{const e=this.sourceBuffer[t];try{e&&(this.removeBufferListeners(t),this.mediaSource&&this.mediaSource.removeSourceBuffer(e),this.sourceBuffer[t]=void 0)}catch(i){_.warn(`[buffer-controller]: Failed to reset the ${t} buffer`,i)}}),this._initSourceBuffer()}onBufferCodecs(t,e){const i=this.getSourceBufferTypes().length;Object.keys(e).forEach(s=>{if(i){const n=this.tracks[s];if(n&&typeof n.buffer.changeType=="function"){const{id:a,codec:o,levelCodec:l,container:h,metadata:c}=e[s],d=(n.levelCodec||n.codec).replace(Yh,"$1"),u=(l||o).replace(Yh,"$1");if(d!==u){const f=`${h};codecs=${l||o}`;this.appendChangeType(s,f),_.log(`[buffer-controller]: switching codec ${d} to ${u}`),this.tracks[s]={buffer:n.buffer,codec:o,container:h,levelCodec:l,metadata:c,id:a}}}}else this.pendingTracks[s]=e[s]}),!i&&(this.bufferCodecEventsExpected=Math.max(this.bufferCodecEventsExpected-1,0),this.mediaSource&&this.mediaSource.readyState==="open"&&this.checkPendingTracks())}appendChangeType(t,e){const{operationQueue:i}=this,s={execute:()=>{const n=this.sourceBuffer[t];n&&(_.log(`[buffer-controller]: changing ${t} sourceBuffer type to ${e}`),n.changeType(e)),i.shiftAndExecuteNext(t)},onStart:()=>{},onComplete:()=>{},onError:n=>{_.warn(`[buffer-controller]: Failed to change ${t} SourceBuffer type`,n)}};i.append(s,t)}onBufferAppending(t,e){const{hls:i,operationQueue:s,tracks:n}=this,{data:a,type:o,frag:l,part:h,chunkMeta:c}=e,d=c.buffering[o],u=self.performance.now();d.start=u;const f=l.stats.buffering,p=h?h.stats.buffering:null;f.start===0&&(f.start=u),p&&p.start===0&&(p.start=u);const g=n.audio;let v=!1;o==="audio"&&(g==null?void 0:g.container)==="audio/mpeg"&&(v=!this.lastMpegAudioChunk||c.id===1||this.lastMpegAudioChunk.sn!==c.sn,this.lastMpegAudioChunk=c);const E=l.start,A={execute:()=>{if(d.executeStart=self.performance.now(),v){const L=this.sourceBuffer[o];if(L){const y=E-L.timestampOffset;Math.abs(y)>=.1&&(_.log(`[buffer-controller]: Updating audio SourceBuffer timestampOffset to ${E} (delta: ${y}) sn: ${l.sn})`),L.timestampOffset=E)}}this.appendExecutor(a,o)},onStart:()=>{},onComplete:()=>{const L=self.performance.now();d.executeEnd=d.end=L,f.first===0&&(f.first=L),p&&p.first===0&&(p.first=L);const{sourceBuffer:y}=this,S={};for(const R in y)S[R]=Et.getBuffered(y[R]);this.appendError=0,this.hls.trigger(m.BUFFER_APPENDED,{type:o,frag:l,part:h,chunkMeta:c,parent:l.type,timeRanges:S})},onError:L=>{_.error(`[buffer-controller]: Error encountered while trying to append to the ${o} SourceBuffer`,L);const y={type:Q.MEDIA_ERROR,parent:l.type,details:$.BUFFER_APPEND_ERROR,frag:l,part:h,chunkMeta:c,error:L,err:L,fatal:!1};L.code===DOMException.QUOTA_EXCEEDED_ERR?y.details=$.BUFFER_FULL_ERROR:(this.appendError++,y.details=$.BUFFER_APPEND_ERROR,this.appendError>i.config.appendErrorMaxRetry&&(_.error(`[buffer-controller]: Failed ${i.config.appendErrorMaxRetry} times to append segment in sourceBuffer`),y.fatal=!0)),i.trigger(m.ERROR,y)}};s.append(A,o)}onBufferFlushing(t,e){const{operationQueue:i}=this,s=n=>({execute:this.removeExecutor.bind(this,n,e.startOffset,e.endOffset),onStart:()=>{},onComplete:()=>{this.hls.trigger(m.BUFFER_FLUSHED,{type:n})},onError:a=>{_.warn(`[buffer-controller]: Failed to remove from ${n} SourceBuffer`,a)}});e.type?i.append(s(e.type),e.type):this.getSourceBufferTypes().forEach(n=>{i.append(s(n),n)})}onFragParsed(t,e){const{frag:i,part:s}=e,n=[],a=s?s.elementaryStreams:i.elementaryStreams;a[mt.AUDIOVIDEO]?n.push("audiovideo"):(a[mt.AUDIO]&&n.push("audio"),a[mt.VIDEO]&&n.push("video"));const o=()=>{const l=self.performance.now();i.stats.buffering.end=l,s&&(s.stats.buffering.end=l);const h=s?s.stats:i.stats;this.hls.trigger(m.FRAG_BUFFERED,{frag:i,part:s,stats:h,id:i.type})};n.length===0&&_.warn(`Fragments must have at least one ElementaryStreamType set. type: ${i.type} level: ${i.level} sn: ${i.sn}`),this.blockBuffers(o,n)}onFragChanged(t,e){this.flushBackBuffer()}onBufferEos(t,e){this.getSourceBufferTypes().reduce((i,s)=>{const n=this.sourceBuffer[s];return n&&(!e.type||e.type===s)&&(n.ending=!0,n.ended||(n.ended=!0,_.log(`[buffer-controller]: ${s} sourceBuffer now EOS`))),i&&!!(!n||n.ended)},!0)&&(_.log("[buffer-controller]: Queueing mediaSource.endOfStream()"),this.blockBuffers(()=>{this.getSourceBufferTypes().forEach(s=>{const n=this.sourceBuffer[s];n&&(n.ending=!1)});const{mediaSource:i}=this;if(!i||i.readyState!=="open"){i&&_.info(`[buffer-controller]: Could not call mediaSource.endOfStream(). mediaSource.readyState: ${i.readyState}`);return}_.log("[buffer-controller]: Calling mediaSource.endOfStream()"),i.endOfStream()}))}onLevelUpdated(t,{details:e}){e.fragments.length&&(this.details=e,this.getSourceBufferTypes().length?this.blockBuffers(this.updateMediaElementDuration.bind(this)):this.updateMediaElementDuration())}flushBackBuffer(){const{hls:t,details:e,media:i,sourceBuffer:s}=this;if(!i||e===null)return;const n=this.getSourceBufferTypes();if(!n.length)return;const a=e.live&&t.config.liveBackBufferLength!==null?t.config.liveBackBufferLength:t.config.backBufferLength;if(!q(a)||a<0)return;const o=i.currentTime,l=e.levelTargetDuration,h=Math.max(a,l),c=Math.floor(o/l)*l-h;n.forEach(d=>{const u=s[d];if(u){const f=Et.getBuffered(u);if(f.length>0&&c>f.start(0)){if(t.trigger(m.BACK_BUFFER_REACHED,{bufferEnd:c}),e.live)t.trigger(m.LIVE_BACK_BUFFER_REACHED,{bufferEnd:c});else if(u.ended&&f.end(f.length-1)-o<l*2){_.info(`[buffer-controller]: Cannot flush ${d} back buffer while SourceBuffer is in ended state`);return}t.trigger(m.BUFFER_FLUSHING,{startOffset:0,endOffset:c,type:d})}}})}updateMediaElementDuration(){if(!this.details||!this.media||!this.mediaSource||this.mediaSource.readyState!=="open")return;const{details:t,hls:e,media:i,mediaSource:s}=this,n=t.fragments[0].start+t.totalduration,a=i.duration,o=q(s.duration)?s.duration:0;t.live&&e.config.liveDurationInfinity?(_.log("[buffer-controller]: Media Source duration is set to Infinity"),s.duration=1/0,this.updateSeekableRange(t)):(n>o&&n>a||!q(a))&&(_.log(`[buffer-controller]: Updating Media Source duration to ${n.toFixed(3)}`),s.duration=n)}updateSeekableRange(t){const e=this.mediaSource,i=t.fragments;if(i.length&&t.live&&e!=null&&e.setLiveSeekableRange){const s=Math.max(0,i[0].start),n=Math.max(s,s+t.totalduration);e.setLiveSeekableRange(s,n)}}checkPendingTracks(){const{bufferCodecEventsExpected:t,operationQueue:e,pendingTracks:i}=this,s=Object.keys(i).length;if(s&&!t||s===2){this.createSourceBuffers(i),this.pendingTracks={};const n=this.getSourceBufferTypes();if(n.length)this.hls.trigger(m.BUFFER_CREATED,{tracks:this.tracks}),n.forEach(a=>{e.executeNext(a)});else{const a=new Error("could not create source buffer for media codec(s)");this.hls.trigger(m.ERROR,{type:Q.MEDIA_ERROR,details:$.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:a,reason:a.message})}}}createSourceBuffers(t){const{sourceBuffer:e,mediaSource:i}=this;if(!i)throw Error("createSourceBuffers called when mediaSource was null");for(const s in t)if(!e[s]){const n=t[s];if(!n)throw Error(`source buffer exists for track ${s}, however track does not`);const a=n.levelCodec||n.codec,o=`${n.container};codecs=${a}`;_.log(`[buffer-controller]: creating sourceBuffer(${o})`);try{const l=e[s]=i.addSourceBuffer(o),h=s;this.addBufferListener(h,"updatestart",this._onSBUpdateStart),this.addBufferListener(h,"updateend",this._onSBUpdateEnd),this.addBufferListener(h,"error",this._onSBUpdateError),this.tracks[s]={buffer:l,codec:a,container:n.container,levelCodec:n.levelCodec,metadata:n.metadata,id:n.id}}catch(l){_.error(`[buffer-controller]: error while trying to add sourceBuffer: ${l.message}`),this.hls.trigger(m.ERROR,{type:Q.MEDIA_ERROR,details:$.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:l,mimeType:o})}}}_onSBUpdateStart(t){const{operationQueue:e}=this;e.current(t).onStart()}_onSBUpdateEnd(t){const{operationQueue:e}=this;e.current(t).onComplete(),e.shiftAndExecuteNext(t)}_onSBUpdateError(t,e){const i=new Error(`${t} SourceBuffer error`);_.error(`[buffer-controller]: ${i}`,e),this.hls.trigger(m.ERROR,{type:Q.MEDIA_ERROR,details:$.BUFFER_APPENDING_ERROR,error:i,fatal:!1});const s=this.operationQueue.current(t);s&&s.onError(e)}removeExecutor(t,e,i){const{media:s,mediaSource:n,operationQueue:a,sourceBuffer:o}=this,l=o[t];if(!s||!n||!l){_.warn(`[buffer-controller]: Attempting to remove from the ${t} SourceBuffer, but it does not exist`),a.shiftAndExecuteNext(t);return}const h=q(s.duration)?s.duration:1/0,c=q(n.duration)?n.duration:1/0,d=Math.max(0,e),u=Math.min(i,h,c);u>d&&!l.ending?(l.ended=!1,_.log(`[buffer-controller]: Removing [${d},${u}] from the ${t} SourceBuffer`),l.remove(d,u)):a.shiftAndExecuteNext(t)}appendExecutor(t,e){const{operationQueue:i,sourceBuffer:s}=this,n=s[e];if(!n){_.warn(`[buffer-controller]: Attempting to append to the ${e} SourceBuffer, but it does not exist`),i.shiftAndExecuteNext(e);return}n.ended=!1,n.appendBuffer(t)}blockBuffers(t,e=this.getSourceBufferTypes()){if(!e.length){_.log("[buffer-controller]: Blocking operation requested, but no SourceBuffers exist"),Promise.resolve().then(t);return}const{operationQueue:i}=this,s=e.map(n=>i.appendBlocker(n));Promise.all(s).then(()=>{t(),e.forEach(n=>{const a=this.sourceBuffer[n];a!=null&&a.updating||i.shiftAndExecuteNext(n)})})}getSourceBufferTypes(){return Object.keys(this.sourceBuffer)}addBufferListener(t,e,i){const s=this.sourceBuffer[t];if(!s)return;const n=i.bind(this,t);this.listeners[t].push({event:e,listener:n}),s.addEventListener(e,n)}removeBufferListeners(t){const e=this.sourceBuffer[t];e&&this.listeners[t].forEach(i=>{e.removeEventListener(i.event,i.listener)})}}const zh={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},qh=function(r){let t=r;return zh.hasOwnProperty(r)&&(t=zh[r]),String.fromCharCode(t)},ye=15,Fe=100,Mm={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},Fm={17:2,18:4,21:6,22:8,23:10,19:13,20:15},Nm={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},Um={25:2,26:4,29:6,30:8,31:10,27:13,28:15},Bm=["white","green","blue","cyan","red","yellow","magenta","black","transparent"];class Hm{constructor(){this.time=null,this.verboseLevel=0}log(t,e){if(this.verboseLevel>=t){const i=typeof e=="function"?e():e;_.log(`${this.time} [${t}] ${i}`)}}}const pi=function(r){const t=[];for(let e=0;e<r.length;e++)t.push(r[e].toString(16));return t};class Xh{constructor(t,e,i,s,n){this.foreground=void 0,this.underline=void 0,this.italics=void 0,this.background=void 0,this.flash=void 0,this.foreground=t||"white",this.underline=e||!1,this.italics=i||!1,this.background=s||"black",this.flash=n||!1}reset(){this.foreground="white",this.underline=!1,this.italics=!1,this.background="black",this.flash=!1}setStyles(t){const e=["foreground","underline","italics","background","flash"];for(let i=0;i<e.length;i++){const s=e[i];t.hasOwnProperty(s)&&(this[s]=t[s])}}isDefault(){return this.foreground==="white"&&!this.underline&&!this.italics&&this.background==="black"&&!this.flash}equals(t){return this.foreground===t.foreground&&this.underline===t.underline&&this.italics===t.italics&&this.background===t.background&&this.flash===t.flash}copy(t){this.foreground=t.foreground,this.underline=t.underline,this.italics=t.italics,this.background=t.background,this.flash=t.flash}toString(){return"color="+this.foreground+", underline="+this.underline+", italics="+this.italics+", background="+this.background+", flash="+this.flash}}class Gm{constructor(t,e,i,s,n,a){this.uchar=void 0,this.penState=void 0,this.uchar=t||" ",this.penState=new Xh(e,i,s,n,a)}reset(){this.uchar=" ",this.penState.reset()}setChar(t,e){this.uchar=t,this.penState.copy(e)}setPenState(t){this.penState.copy(t)}equals(t){return this.uchar===t.uchar&&this.penState.equals(t.penState)}copy(t){this.uchar=t.uchar,this.penState.copy(t.penState)}isEmpty(){return this.uchar===" "&&this.penState.isDefault()}}class Vm{constructor(t){this.chars=void 0,this.pos=void 0,this.currPenState=void 0,this.cueStartTime=void 0,this.logger=void 0,this.chars=[];for(let e=0;e<Fe;e++)this.chars.push(new Gm);this.logger=t,this.pos=0,this.currPenState=new Xh}equals(t){let e=!0;for(let i=0;i<Fe;i++)if(!this.chars[i].equals(t.chars[i])){e=!1;break}return e}copy(t){for(let e=0;e<Fe;e++)this.chars[e].copy(t.chars[e])}isEmpty(){let t=!0;for(let e=0;e<Fe;e++)if(!this.chars[e].isEmpty()){t=!1;break}return t}setCursor(t){this.pos!==t&&(this.pos=t),this.pos<0?(this.logger.log(3,"Negative cursor position "+this.pos),this.pos=0):this.pos>Fe&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=Fe)}moveCursor(t){const e=this.pos+t;if(t>1)for(let i=this.pos+1;i<e+1;i++)this.chars[i].setPenState(this.currPenState);this.setCursor(e)}backSpace(){this.moveCursor(-1),this.chars[this.pos].setChar(" ",this.currPenState)}insertChar(t){t>=144&&this.backSpace();const e=qh(t);if(this.pos>=Fe){this.logger.log(0,()=>"Cannot insert "+t.toString(16)+" ("+e+") at position "+this.pos+". Skipping it!");return}this.chars[this.pos].setChar(e,this.currPenState),this.moveCursor(1)}clearFromPos(t){let e;for(e=t;e<Fe;e++)this.chars[e].reset()}clear(){this.clearFromPos(0),this.pos=0,this.currPenState.reset()}clearToEndOfRow(){this.clearFromPos(this.pos)}getTextString(){const t=[];let e=!0;for(let i=0;i<Fe;i++){const s=this.chars[i].uchar;s!==" "&&(e=!1),t.push(s)}return e?"":t.join("")}setPenStyles(t){this.currPenState.setStyles(t),this.chars[this.pos].setPenState(this.currPenState)}}class na{constructor(t){this.rows=void 0,this.currRow=void 0,this.nrRollUpRows=void 0,this.lastOutputScreen=void 0,this.logger=void 0,this.rows=[];for(let e=0;e<ye;e++)this.rows.push(new Vm(t));this.logger=t,this.currRow=ye-1,this.nrRollUpRows=null,this.lastOutputScreen=null,this.reset()}reset(){for(let t=0;t<ye;t++)this.rows[t].clear();this.currRow=ye-1}equals(t){let e=!0;for(let i=0;i<ye;i++)if(!this.rows[i].equals(t.rows[i])){e=!1;break}return e}copy(t){for(let e=0;e<ye;e++)this.rows[e].copy(t.rows[e])}isEmpty(){let t=!0;for(let e=0;e<ye;e++)if(!this.rows[e].isEmpty()){t=!1;break}return t}backSpace(){this.rows[this.currRow].backSpace()}clearToEndOfRow(){this.rows[this.currRow].clearToEndOfRow()}insertChar(t){this.rows[this.currRow].insertChar(t)}setPen(t){this.rows[this.currRow].setPenStyles(t)}moveCursor(t){this.rows[this.currRow].moveCursor(t)}setCursor(t){this.logger.log(2,"setCursor: "+t),this.rows[this.currRow].setCursor(t)}setPAC(t){this.logger.log(2,()=>"pacData = "+JSON.stringify(t));let e=t.row-1;if(this.nrRollUpRows&&e<this.nrRollUpRows-1&&(e=this.nrRollUpRows-1),this.nrRollUpRows&&this.currRow!==e){for(let o=0;o<ye;o++)this.rows[o].clear();const n=this.currRow+1-this.nrRollUpRows,a=this.lastOutputScreen;if(a){const o=a.rows[n].cueStartTime,l=this.logger.time;if(o&&l!==null&&o<l)for(let h=0;h<this.nrRollUpRows;h++)this.rows[e-this.nrRollUpRows+h+1].copy(a.rows[n+h])}}this.currRow=e;const i=this.rows[this.currRow];if(t.indent!==null){const n=t.indent,a=Math.max(n-1,0);i.setCursor(t.indent),t.color=i.chars[a].penState.foreground}const s={foreground:t.color,underline:t.underline,italics:t.italics,background:"black",flash:!1};this.setPen(s)}setBkgData(t){this.logger.log(2,()=>"bkgData = "+JSON.stringify(t)),this.backSpace(),this.setPen(t),this.insertChar(32)}setRollUpRows(t){this.nrRollUpRows=t}rollUp(){if(this.nrRollUpRows===null){this.logger.log(3,"roll_up but nrRollUpRows not set yet");return}this.logger.log(1,()=>this.getDisplayText());const t=this.currRow+1-this.nrRollUpRows,e=this.rows.splice(t,1)[0];e.clear(),this.rows.splice(this.currRow,0,e),this.logger.log(2,"Rolling up")}getDisplayText(t){t=t||!1;const e=[];let i="",s=-1;for(let n=0;n<ye;n++){const a=this.rows[n].getTextString();a&&(s=n+1,t?e.push("Row "+s+": '"+a+"'"):e.push(a.trim()))}return e.length>0&&(t?i="["+e.join(" | ")+"]":i=e.join(`
162
+ `)),i}getTextAndFormat(){return this.rows}}class Qh{constructor(t,e,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=t,this.outputFilter=e,this.mode=null,this.verbose=0,this.displayedMemory=new na(i),this.nonDisplayedMemory=new na(i),this.lastOutputScreen=new na(i),this.currRollUpRow=this.displayedMemory.rows[ye-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[ye-1],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null}getHandler(){return this.outputFilter}setHandler(t){this.outputFilter=t}setPAC(t){this.writeScreen.setPAC(t)}setBkgData(t){this.writeScreen.setBkgData(t)}setMode(t){t!==this.mode&&(this.mode=t,this.logger.log(2,()=>"MODE="+t),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=t)}insertChars(t){for(let i=0;i<t.length;i++)this.writeScreen.insertChar(t[i]);const e=this.writeScreen===this.displayedMemory?"DISP":"NON_DISP";this.logger.log(2,()=>e+": "+this.writeScreen.getDisplayText(!0)),(this.mode==="MODE_PAINT-ON"||this.mode==="MODE_ROLL-UP")&&(this.logger.log(1,()=>"DISPLAYED: "+this.displayedMemory.getDisplayText(!0)),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(t){this.logger.log(2,"RU("+t+") - Roll Up"),this.writeScreen=this.displayedMemory,this.setMode("MODE_ROLL-UP"),this.writeScreen.setRollUpRows(t)}ccFON(){this.logger.log(2,"FON - Flash On"),this.writeScreen.setPen({flash:!0})}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(!0)}ccCR(){this.logger.log(2,"CR - Carriage Return"),this.writeScreen.rollUp(),this.outputDataUpdate(!0)}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"){const t=this.displayedMemory;this.displayedMemory=this.nonDisplayedMemory,this.nonDisplayedMemory=t,this.writeScreen=this.nonDisplayedMemory,this.logger.log(1,()=>"DISP: "+this.displayedMemory.getDisplayText())}this.outputDataUpdate(!0)}ccTO(t){this.logger.log(2,"TO("+t+") - Tab Offset"),this.writeScreen.moveCursor(t)}ccMIDROW(t){const e={flash:!1};if(e.underline=t%2===1,e.italics=t>=46,e.italics)e.foreground="white";else{const i=Math.floor(t/2)-16,s=["white","green","blue","cyan","red","yellow","magenta"];e.foreground=s[i]}this.logger.log(2,"MIDROW: "+JSON.stringify(e)),this.writeScreen.setPen(e)}outputDataUpdate(t=!1){const e=this.logger.time;e!==null&&this.outputFilter&&(this.cueStartTime===null&&!this.displayedMemory.isEmpty()?this.cueStartTime=e:this.displayedMemory.equals(this.lastOutputScreen)||(this.outputFilter.newCue(this.cueStartTime,e,this.lastOutputScreen),t&&this.outputFilter.dispatchCue&&this.outputFilter.dispatchCue(),this.cueStartTime=this.displayedMemory.isEmpty()?null:e),this.lastOutputScreen.copy(this.displayedMemory))}cueSplitAtTime(t){this.outputFilter&&(this.displayedMemory.isEmpty()||(this.outputFilter.newCue&&this.outputFilter.newCue(this.cueStartTime,t,this.displayedMemory),this.cueStartTime=t))}}class Zh{constructor(t,e,i){this.channels=void 0,this.currentChannel=0,this.cmdHistory=void 0,this.logger=void 0;const s=new Hm;this.channels=[null,new Qh(t,e,s),new Qh(t+1,i,s)],this.cmdHistory=tc(),this.logger=s}getHandler(t){return this.channels[t].getHandler()}setHandler(t,e){this.channels[t].setHandler(e)}addData(t,e){let i,s,n,a=!1;this.logger.time=t;for(let o=0;o<e.length;o+=2)if(s=e[o]&127,n=e[o+1]&127,!(s===0&&n===0)){if(this.logger.log(3,"["+pi([e[o],e[o+1]])+"] -> ("+pi([s,n])+")"),i=this.parseCmd(s,n),i||(i=this.parseMidrow(s,n)),i||(i=this.parsePAC(s,n)),i||(i=this.parseBackgroundAttributes(s,n)),!i&&(a=this.parseChars(s,n),a)){const l=this.currentChannel;l&&l>0?this.channels[l].insertChars(a):this.logger.log(2,"No channel found yet. TEXT-MODE?")}!i&&!a&&this.logger.log(2,"Couldn't parse cleaned data "+pi([s,n])+" orig: "+pi([e[o],e[o+1]]))}}parseCmd(t,e){const{cmdHistory:i}=this,s=(t===20||t===28||t===21||t===29)&&e>=32&&e<=47,n=(t===23||t===31)&&e>=33&&e<=35;if(!(s||n))return!1;if(Jh(t,e,i))return xi(null,null,i),this.logger.log(3,"Repeated command ("+pi([t,e])+") is dropped"),!0;const a=t===20||t===21||t===23?1:2,o=this.channels[a];return t===20||t===21||t===28||t===29?e===32?o.ccRCL():e===33?o.ccBS():e===34?o.ccAOF():e===35?o.ccAON():e===36?o.ccDER():e===37?o.ccRU(2):e===38?o.ccRU(3):e===39?o.ccRU(4):e===40?o.ccFON():e===41?o.ccRDC():e===42?o.ccTR():e===43?o.ccRTD():e===44?o.ccEDM():e===45?o.ccCR():e===46?o.ccENM():e===47&&o.ccEOC():o.ccTO(e-32),xi(t,e,i),this.currentChannel=a,!0}parseMidrow(t,e){let i=0;if((t===17||t===25)&&e>=32&&e<=47){if(t===17?i=1:i=2,i!==this.currentChannel)return this.logger.log(0,"Mismatch channel in midrow parsing"),!1;const s=this.channels[i];return s?(s.ccMIDROW(e),this.logger.log(3,"MIDROW ("+pi([t,e])+")"),!0):!1}return!1}parsePAC(t,e){let i;const s=this.cmdHistory,n=(t>=17&&t<=23||t>=25&&t<=31)&&e>=64&&e<=127,a=(t===16||t===24)&&e>=64&&e<=95;if(!(n||a))return!1;if(Jh(t,e,s))return xi(null,null,s),!0;const o=t<=23?1:2;e>=64&&e<=95?i=o===1?Mm[t]:Nm[t]:i=o===1?Fm[t]:Um[t];const l=this.channels[o];return l?(l.setPAC(this.interpretPAC(i,e)),xi(t,e,s),this.currentChannel=o,!0):!1}interpretPAC(t,e){let i;const s={color:null,italics:!1,indent:null,underline:!1,row:t};return e>95?i=e-96:i=e-64,s.underline=(i&1)===1,i<=13?s.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(i/2)]:i<=15?(s.italics=!0,s.color="white"):s.indent=Math.floor((i-16)/2)*4,s}parseChars(t,e){let i,s=null,n=null;if(t>=25?(i=2,n=t-8):(i=1,n=t),n>=17&&n<=19){let a;n===17?a=e+80:n===18?a=e+112:a=e+144,this.logger.log(2,"Special char '"+qh(a)+"' in channel "+i),s=[a]}else t>=32&&t<=127&&(s=e===0?[t]:[t,e]);if(s){const a=pi(s);this.logger.log(3,"Char codes = "+a.join(",")),xi(t,e,this.cmdHistory)}return s}parseBackgroundAttributes(t,e){const i=(t===16||t===24)&&e>=32&&e<=47,s=(t===23||t===31)&&e>=45&&e<=47;if(!(i||s))return!1;let n;const a={};t===16||t===24?(n=Math.floor((e-32)/2),a.background=Bm[n],e%2===1&&(a.background=a.background+"_semi")):e===45?a.background="transparent":(a.foreground="black",e===47&&(a.underline=!0));const o=t<=23?1:2;return this.channels[o].setBkgData(a),xi(t,e,this.cmdHistory),!0}reset(){for(let t=0;t<Object.keys(this.channels).length;t++){const e=this.channels[t];e&&e.reset()}this.cmdHistory=tc()}cueSplitAtTime(t){for(let e=0;e<this.channels.length;e++){const i=this.channels[e];i&&i.cueSplitAtTime(t)}}}function xi(r,t,e){e.a=r,e.b=t}function Jh(r,t,e){return e.a===r&&e.b===t}function tc(){return{a:null,b:null}}class br{constructor(t,e){this.timelineController=void 0,this.cueRanges=[],this.trackName=void 0,this.startTime=null,this.endTime=null,this.screen=null,this.timelineController=t,this.trackName=e}dispatchCue(){this.startTime!==null&&(this.timelineController.addCues(this.trackName,this.startTime,this.endTime,this.screen,this.cueRanges),this.startTime=null)}newCue(t,e,i){(this.startTime===null||this.startTime>t)&&(this.startTime=t),this.endTime=e,this.screen=i,this.timelineController.createCaptionsTrack(this.trackName)}reset(){this.cueRanges=[],this.startTime=null}}var aa=function(){if(typeof self<"u"&&self.VTTCue)return self.VTTCue;const r=["","lr","rl"],t=["start","middle","end","left","right"];function e(o,l){if(typeof l!="string"||!Array.isArray(o))return!1;const h=l.toLowerCase();return~o.indexOf(h)?h:!1}function i(o){return e(r,o)}function s(o){return e(t,o)}function n(o,...l){let h=1;for(;h<arguments.length;h++){const c=arguments[h];for(const d in c)o[d]=c[d]}return o}function a(o,l,h){const c=this,d={enumerable:!0};c.hasBeenReset=!1;let u="",f=!1,p=o,g=l,v=h,E=null,A="",L=!0,y="auto",S="start",R=50,C="middle",M=50,D="middle";Object.defineProperty(c,"id",n({},d,{get:function(){return u},set:function(I){u=""+I}})),Object.defineProperty(c,"pauseOnExit",n({},d,{get:function(){return f},set:function(I){f=!!I}})),Object.defineProperty(c,"startTime",n({},d,{get:function(){return p},set:function(I){if(typeof I!="number")throw new TypeError("Start time must be set to a number.");p=I,this.hasBeenReset=!0}})),Object.defineProperty(c,"endTime",n({},d,{get:function(){return g},set:function(I){if(typeof I!="number")throw new TypeError("End time must be set to a number.");g=I,this.hasBeenReset=!0}})),Object.defineProperty(c,"text",n({},d,{get:function(){return v},set:function(I){v=""+I,this.hasBeenReset=!0}})),Object.defineProperty(c,"region",n({},d,{get:function(){return E},set:function(I){E=I,this.hasBeenReset=!0}})),Object.defineProperty(c,"vertical",n({},d,{get:function(){return A},set:function(I){const G=i(I);if(G===!1)throw new SyntaxError("An invalid or illegal string was specified.");A=G,this.hasBeenReset=!0}})),Object.defineProperty(c,"snapToLines",n({},d,{get:function(){return L},set:function(I){L=!!I,this.hasBeenReset=!0}})),Object.defineProperty(c,"line",n({},d,{get:function(){return y},set:function(I){if(typeof I!="number"&&I!=="auto")throw new SyntaxError("An invalid number or illegal string was specified.");y=I,this.hasBeenReset=!0}})),Object.defineProperty(c,"lineAlign",n({},d,{get:function(){return S},set:function(I){const G=s(I);if(!G)throw new SyntaxError("An invalid or illegal string was specified.");S=G,this.hasBeenReset=!0}})),Object.defineProperty(c,"position",n({},d,{get:function(){return R},set:function(I){if(I<0||I>100)throw new Error("Position must be between 0 and 100.");R=I,this.hasBeenReset=!0}})),Object.defineProperty(c,"positionAlign",n({},d,{get:function(){return C},set:function(I){const G=s(I);if(!G)throw new SyntaxError("An invalid or illegal string was specified.");C=G,this.hasBeenReset=!0}})),Object.defineProperty(c,"size",n({},d,{get:function(){return M},set:function(I){if(I<0||I>100)throw new Error("Size must be between 0 and 100.");M=I,this.hasBeenReset=!0}})),Object.defineProperty(c,"align",n({},d,{get:function(){return D},set:function(I){const G=s(I);if(!G)throw new SyntaxError("An invalid or illegal string was specified.");D=G,this.hasBeenReset=!0}})),c.displayState=void 0}return a.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},a}();class Km{decode(t,e){if(!t)return"";if(typeof t!="string")throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(t))}}function ec(r){function t(i,s,n,a){return(i|0)*3600+(s|0)*60+(n|0)+parseFloat(a||0)}const e=r.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);return e?parseFloat(e[2])>59?t(e[2],e[3],0,e[4]):t(e[1],e[2],e[3],e[4]):null}class jm{constructor(){this.values=Object.create(null)}set(t,e){!this.get(t)&&e!==""&&(this.values[t]=e)}get(t,e,i){return i?this.has(t)?this.values[t]:e[i]:this.has(t)?this.values[t]:e}has(t){return t in this.values}alt(t,e,i){for(let s=0;s<i.length;++s)if(e===i[s]){this.set(t,e);break}}integer(t,e){/^-?\d+$/.test(e)&&this.set(t,parseInt(e,10))}percent(t,e){if(/^([\d]{1,3})(\.[\d]*)?%$/.test(e)){const i=parseFloat(e);if(i>=0&&i<=100)return this.set(t,i),!0}return!1}}function ic(r,t,e,i){const s=i?r.split(i):[r];for(const n in s){if(typeof s[n]!="string")continue;const a=s[n].split(e);if(a.length!==2)continue;const o=a[0],l=a[1];t(o,l)}}const oa=new aa(0,0,""),Tr=oa.align==="middle"?"middle":"center";function Wm(r,t,e){const i=r;function s(){const o=ec(r);if(o===null)throw new Error("Malformed timestamp: "+i);return r=r.replace(/^[^\sa-zA-Z-]+/,""),o}function n(o,l){const h=new jm;ic(o,function(u,f){let p;switch(u){case"region":for(let g=e.length-1;g>=0;g--)if(e[g].id===f){h.set(u,e[g].region);break}break;case"vertical":h.alt(u,f,["rl","lr"]);break;case"line":p=f.split(","),h.integer(u,p[0]),h.percent(u,p[0])&&h.set("snapToLines",!1),h.alt(u,p[0],["auto"]),p.length===2&&h.alt("lineAlign",p[1],["start",Tr,"end"]);break;case"position":p=f.split(","),h.percent(u,p[0]),p.length===2&&h.alt("positionAlign",p[1],["start",Tr,"end","line-left","line-right","auto"]);break;case"size":h.percent(u,f);break;case"align":h.alt(u,f,["start",Tr,"end","left","right"]);break}},/:/,/\s/),l.region=h.get("region",null),l.vertical=h.get("vertical","");let c=h.get("line","auto");c==="auto"&&oa.line===-1&&(c=-1),l.line=c,l.lineAlign=h.get("lineAlign","start"),l.snapToLines=h.get("snapToLines",!0),l.size=h.get("size",100),l.align=h.get("align",Tr);let d=h.get("position","auto");d==="auto"&&oa.position===50&&(d=l.align==="start"||l.align==="left"?0:l.align==="end"||l.align==="right"?100:50),l.position=d}function a(){r=r.replace(/^\s+/,"")}if(a(),t.startTime=s(),a(),r.slice(0,3)!=="-->")throw new Error("Malformed time stamp (time stamps must be separated by '-->'): "+i);r=r.slice(3),a(),t.endTime=s(),a(),n(r,t)}function sc(r){return r.replace(/<br(?: \/)?>/gi,`
163
+ `)}class Ym{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new Km,this.regionList=[],this.cue=null,this.oncue=void 0,this.onparsingerror=void 0,this.onflush=void 0}parse(t){const e=this;t&&(e.buffer+=e.decoder.decode(t,{stream:!0}));function i(){let n=e.buffer,a=0;for(n=sc(n);a<n.length&&n[a]!=="\r"&&n[a]!==`
175
164
  `;)++a;const o=n.slice(0,a);return n[a]==="\r"&&++a,n[a]===`
176
- `&&++a,e.buffer=n.slice(a),o}function s(n){Sd(n,function(a,o){},/:/)}try{let n="";if(e.state==="INITIAL"){if(!/\r\n|\n/.test(e.buffer))return this;n=i();const o=n.match(/^()?WEBVTT([ \t].*)?$/);if(!(o!=null&&o[0]))throw new Error("Malformed WebVTT signature.");e.state="HEADER"}let a=!1;for(;e.buffer;){if(!/\r\n|\n/.test(e.buffer))return this;switch(a?a=!1:n=i(),e.state){case"HEADER":/:/.test(n)?s(n):n||(e.state="ID");continue;case"NOTE":n||(e.state="ID");continue;case"ID":if(/^NOTE($|[ \t])/.test(n)){e.state="NOTE";break}if(!n)continue;if(e.cue=new Ea(0,0,""),e.state="CUE",n.indexOf("-->")===-1){e.cue.id=n;continue}case"CUE":if(!e.cue){e.state="BADCUE";continue}try{Tv(n,e.cue,e.regionList)}catch{e.cue=null,e.state="BADCUE";continue}e.state="CUETEXT";continue;case"CUETEXT":{const o=n.indexOf("-->")!==-1;if(!n||o&&(a=!0)){e.oncue&&e.cue&&e.oncue(e.cue),e.cue=null,e.state="ID";continue}if(e.cue===null)continue;e.cue.text&&(e.cue.text+=`
165
+ `&&++a,e.buffer=n.slice(a),o}function s(n){ic(n,function(a,o){},/:/)}try{let n="";if(e.state==="INITIAL"){if(!/\r\n|\n/.test(e.buffer))return this;n=i();const o=n.match(/^()?WEBVTT([ \t].*)?$/);if(!(o!=null&&o[0]))throw new Error("Malformed WebVTT signature.");e.state="HEADER"}let a=!1;for(;e.buffer;){if(!/\r\n|\n/.test(e.buffer))return this;switch(a?a=!1:n=i(),e.state){case"HEADER":/:/.test(n)?s(n):n||(e.state="ID");continue;case"NOTE":n||(e.state="ID");continue;case"ID":if(/^NOTE($|[ \t])/.test(n)){e.state="NOTE";break}if(!n)continue;if(e.cue=new aa(0,0,""),e.state="CUE",n.indexOf("-->")===-1){e.cue.id=n;continue}case"CUE":if(!e.cue){e.state="BADCUE";continue}try{Wm(n,e.cue,e.regionList)}catch{e.cue=null,e.state="BADCUE";continue}e.state="CUETEXT";continue;case"CUETEXT":{const o=n.indexOf("-->")!==-1;if(!n||o&&(a=!0)){e.oncue&&e.cue&&e.oncue(e.cue),e.cue=null,e.state="ID";continue}if(e.cue===null)continue;e.cue.text&&(e.cue.text+=`
177
166
  `),e.cue.text+=n}continue;case"BADCUE":n||(e.state="ID")}}}catch{e.state==="CUETEXT"&&e.cue&&e.oncue&&e.oncue(e.cue),e.cue=null,e.state=e.state==="INITIAL"?"BADWEBVTT":"BADCUE"}return this}flush(){const t=this;try{if((t.cue||t.state==="HEADER")&&(t.buffer+=`
178
167
 
179
- `,t.parse()),t.state==="INITIAL"||t.state==="BADWEBVTT")throw new Error("Malformed WebVTT signature.")}catch(e){t.onparsingerror&&t.onparsingerror(e)}return t.onflush&&t.onflush(),this}}const Av=/\r\n|\n\r|\n|\r/g,ba=function(r,t,e=0){return r.slice(e,e+t.length)===t},wv=function(r){let t=parseInt(r.slice(-3));const e=parseInt(r.slice(-6,-4)),i=parseInt(r.slice(-9,-7)),s=r.length>9?parseInt(r.substring(0,r.indexOf(":"))):0;if(!j(t)||!j(e)||!j(i)||!j(s))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${r}`);return t+=1e3*e,t+=60*1e3*i,t+=60*60*1e3*s,t},Aa=function(r){let t=5381,e=r.length;for(;e;)t=t*33^r.charCodeAt(--e);return(t>>>0).toString()};function wa(r,t,e){return Aa(r.toString())+Aa(t.toString())+Aa(e)}const Sv=function(r,t,e){let i=r[t],s=r[i.prevCC];if(!s||!s.new&&i.new){r.ccOffset=r.presentationOffset=i.start,i.new=!1;return}for(;(n=s)!=null&&n.new;){var n;r.ccOffset+=i.start-s.start,i.new=!1,i=s,s=r[i.prevCC]}r.presentationOffset=e};function Lv(r,t,e,i,s,n,a){const o=new bv,l=ge(new Uint8Array(r)).trim().replace(Av,`
168
+ `,t.parse()),t.state==="INITIAL"||t.state==="BADWEBVTT")throw new Error("Malformed WebVTT signature.")}catch(e){t.onparsingerror&&t.onparsingerror(e)}return t.onflush&&t.onflush(),this}}const zm=/\r\n|\n\r|\n|\r/g,la=function(r,t,e=0){return r.slice(e,e+t.length)===t},qm=function(r){let t=parseInt(r.slice(-3));const e=parseInt(r.slice(-6,-4)),i=parseInt(r.slice(-9,-7)),s=r.length>9?parseInt(r.substring(0,r.indexOf(":"))):0;if(!q(t)||!q(e)||!q(i)||!q(s))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${r}`);return t+=1e3*e,t+=60*1e3*i,t+=60*60*1e3*s,t},ha=function(r){let t=5381,e=r.length;for(;e;)t=t*33^r.charCodeAt(--e);return(t>>>0).toString()};function ca(r,t,e){return ha(r.toString())+ha(t.toString())+ha(e)}const Xm=function(r,t,e){let i=r[t],s=r[i.prevCC];if(!s||!s.new&&i.new){r.ccOffset=r.presentationOffset=i.start,i.new=!1;return}for(;(n=s)!=null&&n.new;){var n;r.ccOffset+=i.start-s.start,i.new=!1,i=s,s=r[i.prevCC]}r.presentationOffset=e};function Qm(r,t,e,i,s,n,a){const o=new Ym,l=Se(new Uint8Array(r)).trim().replace(zm,`
180
169
  `).split(`
181
- `),h=[],d=t?$m(t.baseTime,t.timescale):0;let c="00:00.000",u=0,f=0,p,g=!0;o.oncue=function(v){const E=e[i];let T=e.ccOffset;const A=(u-d)/9e4;if(E!=null&&E.new&&(f!==void 0?T=e.ccOffset=E.start:Sv(e,i,A)),A){if(!t){p=new Error("Missing initPTS for VTT MPEGTS");return}T=A-e.presentationOffset}const y=v.endTime-v.startTime,b=te((v.startTime+T-f)*9e4,s*9e4)/9e4;v.startTime=Math.max(b,0),v.endTime=Math.max(b+y,0);const S=v.text.trim();v.text=decodeURIComponent(encodeURIComponent(S)),v.id||(v.id=wa(v.startTime,v.endTime,S)),v.endTime>0&&h.push(v)},o.onparsingerror=function(v){p=v},o.onflush=function(){if(p){a(p);return}n(h)},l.forEach(v=>{if(g)if(ba(v,"X-TIMESTAMP-MAP=")){g=!1,v.slice(16).split(",").forEach(E=>{ba(E,"LOCAL:")?c=E.slice(6):ba(E,"MPEGTS:")&&(u=parseInt(E.slice(7)))});try{f=wv(c)/1e3}catch(E){p=E}return}else v===""&&(g=!1);o.parse(v+`
182
- `)}),o.flush()}const Sa="stpp.ttml.im1t",Rd=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,_d=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,Rv={left:"start",center:"center",right:"end",start:"start",end:"end"};function Id(r,t,e,i){const s=et(new Uint8Array(r),["mdat"]);if(s.length===0){i(new Error("Could not parse IMSC1 mdat"));return}const n=s.map(o=>ge(o)),a=Mm(t.baseTime,1,t.timescale);try{n.forEach(o=>e(_v(o,a)))}catch(o){i(o)}}function _v(r,t){const e=new DOMParser().parseFromString(r,"text/xml").getElementsByTagName("tt")[0];if(!e)throw new Error("Invalid ttml");const i={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:0},s=Object.keys(i).reduce((h,d)=>(h[d]=e.getAttribute(`ttp:${d}`)||i[d],h),{}),n=e.getAttribute("xml:space")!=="preserve",a=kd(La(e,"styling","style")),o=kd(La(e,"layout","region")),l=La(e,"body","[begin]");return[].map.call(l,h=>{const d=Cd(h,n);if(!d||!h.hasAttribute("begin"))return null;const c=_a(h.getAttribute("begin"),s),u=_a(h.getAttribute("dur"),s);let f=_a(h.getAttribute("end"),s);if(c===null)throw Dd(h);if(f===null){if(u===null)throw Dd(h);f=c+u}const p=new Ea(c-t,f-t,d);p.id=wa(p.startTime,p.endTime,p.text);const g=o[h.getAttribute("region")],v=a[h.getAttribute("style")],E=Iv(g,v,a),{textAlign:T}=E;if(T){const A=Rv[T];A&&(p.lineAlign=A),p.align=T}return At(p,E),p}).filter(h=>h!==null)}function La(r,t,e){const i=r.getElementsByTagName(t)[0];return i?[].slice.call(i.querySelectorAll(e)):[]}function kd(r){return r.reduce((t,e)=>{const i=e.getAttribute("xml:id");return i&&(t[i]=e),t},{})}function Cd(r,t){return[].slice.call(r.childNodes).reduce((e,i,s)=>{var n;return i.nodeName==="br"&&s?e+`
183
- `:(n=i.childNodes)!=null&&n.length?Cd(i,t):t?e+i.textContent.trim().replace(/\s+/g," "):e+i.textContent},"")}function Iv(r,t,e){const i="http://www.w3.org/ns/ttml#styling";let s=null;const n=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],a=r!=null&&r.hasAttribute("style")?r.getAttribute("style"):null;return a&&e.hasOwnProperty(a)&&(s=e[a]),n.reduce((o,l)=>{const h=Ra(t,i,l)||Ra(r,i,l)||Ra(s,i,l);return h&&(o[l]=h),o},{})}function Ra(r,t,e){return r&&r.hasAttributeNS(t,e)?r.getAttributeNS(t,e):null}function Dd(r){return new Error(`Could not parse ttml timestamp ${r}`)}function _a(r,t){if(!r)return null;let e=wd(r);return e===null&&(Rd.test(r)?e=kv(r,t):_d.test(r)&&(e=Cv(r,t))),e}function kv(r,t){const e=Rd.exec(r),i=(e[4]|0)+(e[5]|0)/t.subFrameRate;return(e[1]|0)*3600+(e[2]|0)*60+(e[3]|0)+i/t.frameRate}function Cv(r,t){const e=_d.exec(r),i=Number(e[1]);switch(e[2]){case"h":return i*3600;case"m":return i*60;case"ms":return i*1e3;case"f":return i/t.frameRate;case"t":return i/t.tickRate}return i}class Dv{constructor(t){if(this.hls=void 0,this.media=null,this.config=void 0,this.enabled=!0,this.Cues=void 0,this.textTracks=[],this.tracks=[],this.initPTS=[],this.unparsedVttFrags=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.cea608Parser1=void 0,this.cea608Parser2=void 0,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=xd(),this.captionsProperties=void 0,this.hls=t,this.config=t.config,this.Cues=t.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}},this.config.enableCEA708Captions){const e=new Tr(this,"textTrack1"),i=new Tr(this,"textTrack2"),s=new Tr(this,"textTrack3"),n=new Tr(this,"textTrack4");this.cea608Parser1=new Td(1,e,i),this.cea608Parser2=new Td(3,s,n)}t.on(m.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(m.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(m.MANIFEST_LOADING,this.onManifestLoading,this),t.on(m.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(m.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.on(m.FRAG_LOADING,this.onFragLoading,this),t.on(m.FRAG_LOADED,this.onFragLoaded,this),t.on(m.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),t.on(m.FRAG_DECRYPTED,this.onFragDecrypted,this),t.on(m.INIT_PTS_FOUND,this.onInitPtsFound,this),t.on(m.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),t.on(m.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){const{hls:t}=this;t.off(m.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(m.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(m.MANIFEST_LOADING,this.onManifestLoading,this),t.off(m.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(m.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.off(m.FRAG_LOADING,this.onFragLoading,this),t.off(m.FRAG_LOADED,this.onFragLoaded,this),t.off(m.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),t.off(m.FRAG_DECRYPTED,this.onFragDecrypted,this),t.off(m.INIT_PTS_FOUND,this.onInitPtsFound,this),t.off(m.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),t.off(m.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.cea608Parser1=this.cea608Parser2=null}addCues(t,e,i,s,n){let a=!1;for(let o=n.length;o--;){const l=n[o],h=Pv(l[0],l[1],e,i);if(h>=0&&(l[0]=Math.min(l[0],e),l[1]=Math.max(l[1],i),a=!0,h/(i-e)>.5))return}if(a||n.push([e,i]),this.config.renderTextTracksNatively){const o=this.captionsTracks[t];this.Cues.newCue(o,e,i,s)}else{const o=this.Cues.newCue(null,e,i,s);this.hls.trigger(m.CUES_PARSED,{type:"captions",cues:o,track:t})}}onInitPtsFound(t,{frag:e,id:i,initPTS:s,timescale:n}){const{unparsedVttFrags:a}=this;i==="main"&&(this.initPTS[e.cc]={baseTime:s,timescale:n}),a.length&&(this.unparsedVttFrags=[],a.forEach(o=>{this.onFragLoaded(m.FRAG_LOADED,o)}))}getExistingTrack(t){const{media:e}=this;if(e)for(let i=0;i<e.textTracks.length;i++){const s=e.textTracks[i];if(s[t])return s}return null}createCaptionsTrack(t){this.config.renderTextTracksNatively?this.createNativeTrack(t):this.createNonNativeTrack(t)}createNativeTrack(t){if(this.captionsTracks[t])return;const{captionsProperties:e,captionsTracks:i,media:s}=this,{label:n,languageCode:a}=e[t],o=this.getExistingTrack(t);if(o)i[t]=o,bi(i[t]),Rh(i[t],s);else{const l=this.createTextTrack("captions",n,a);l&&(l[t]=!0,i[t]=l)}}createNonNativeTrack(t){if(this.nonNativeCaptionsTracks[t])return;const e=this.captionsProperties[t];if(!e)return;const i=e.label,s={_id:t,label:i,kind:"captions",default:e.media?!!e.media.default:!1,closedCaptions:e.media};this.nonNativeCaptionsTracks[t]=s,this.hls.trigger(m.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[s]})}createTextTrack(t,e,i){const s=this.media;if(s)return s.addTextTrack(t,e,i)}onMediaAttaching(t,e){this.media=e.media,this._cleanTracks()}onMediaDetaching(){const{captionsTracks:t}=this;Object.keys(t).forEach(e=>{bi(t[e]),delete t[e]}),this.nonNativeCaptionsTracks={}}onManifestLoading(){this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=xd(),this._cleanTracks(),this.tracks=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.textTracks=[],this.unparsedVttFrags=[],this.initPTS=[],this.cea608Parser1&&this.cea608Parser2&&(this.cea608Parser1.reset(),this.cea608Parser2.reset())}_cleanTracks(){const{media:t}=this;if(!t)return;const e=t.textTracks;if(e)for(let i=0;i<e.length;i++)bi(e[i])}onSubtitleTracksUpdated(t,e){const i=e.subtitleTracks||[],s=i.some(n=>n.textCodec===Sa);if(this.config.enableWebVTT||s&&this.config.enableIMSC1){if(ud(this.tracks,i)){this.tracks=i;return}if(this.textTracks=[],this.tracks=i,this.config.renderTextTracksNatively){const n=this.media?this.media.textTracks:null;this.tracks.forEach((a,o)=>{let l;if(n&&o<n.length){let h=null;for(let d=0;d<n.length;d++)if(xv(n[d],a)){h=n[d];break}h&&(l=h)}if(l)bi(l);else{const h=this._captionsOrSubtitlesFromCharacteristics(a);l=this.createTextTrack(h,a.name,a.lang),l&&(l.mode="disabled")}l&&(l.groupId=a.groupId,this.textTracks.push(l))})}else if(this.tracks.length){const n=this.tracks.map(a=>({label:a.name,kind:a.type.toLowerCase(),default:a.default,subtitleTrack:a}));this.hls.trigger(m.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:n})}}}_captionsOrSubtitlesFromCharacteristics(t){if(t.attrs.CHARACTERISTICS){const e=/transcribes-spoken-dialog/gi.test(t.attrs.CHARACTERISTICS),i=/describes-music-and-sound/gi.test(t.attrs.CHARACTERISTICS);if(e&&i)return"captions"}return"subtitles"}onManifestLoaded(t,e){this.config.enableCEA708Captions&&e.captions&&e.captions.forEach(i=>{const s=/(?:CC|SERVICE)([1-4])/.exec(i.instreamId);if(!s)return;const n=`textTrack${s[1]}`,a=this.captionsProperties[n];a&&(a.label=i.name,i.lang&&(a.languageCode=i.lang),a.media=i)})}closedCaptionsForLevel(t){const e=this.hls.levels[t.level];return e==null?void 0:e.attrs["CLOSED-CAPTIONS"]}onFragLoading(t,e){const{cea608Parser1:i,cea608Parser2:s,lastSn:n,lastPartIndex:a}=this;if(!(!this.enabled||!(i&&s))&&e.frag.type===Y.MAIN){var o,l;const h=e.frag.sn,d=(o=e==null||(l=e.part)==null?void 0:l.index)!=null?o:-1;h===n+1||h===n&&d===a+1||(i.reset(),s.reset()),this.lastSn=h,this.lastPartIndex=d}}onFragLoaded(t,e){const{frag:i,payload:s}=e;if(i.type===Y.SUBTITLE)if(s.byteLength){const n=i.decryptdata,a="stats"in e;if(n==null||!n.encrypted||a){const o=this.tracks[i.level],l=this.vttCCs;l[i.cc]||(l[i.cc]={start:i.start,prevCC:this.prevCC,new:!0},this.prevCC=i.cc),o&&o.textCodec===Sa?this._parseIMSC1(i,s):this._parseVTTs(e)}}else this.hls.trigger(m.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,error:new Error("Empty subtitle payload")})}_parseIMSC1(t,e){const i=this.hls;Id(e,this.initPTS[t.cc],s=>{this._appendCues(s,t.level),i.trigger(m.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:t})},s=>{L.log(`Failed to parse IMSC1: ${s}`),i.trigger(m.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:t,error:s})})}_parseVTTs(t){var e;const{frag:i,payload:s}=t,{initPTS:n,unparsedVttFrags:a}=this,o=n.length-1;if(!n[i.cc]&&o===-1){a.push(t);return}const l=this.hls,h=(e=i.initSegment)!=null&&e.data?si(i.initSegment.data,new Uint8Array(s)):s;Lv(h,this.initPTS[i.cc],this.vttCCs,i.cc,i.start,d=>{this._appendCues(d,i.level),l.trigger(m.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:i})},d=>{const c=d.message==="Missing initPTS for VTT MPEGTS";c?a.push(t):this._fallbackToIMSC1(i,s),L.log(`Failed to parse VTT cue: ${d}`),!(c&&o>i.cc)&&l.trigger(m.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,error:d})})}_fallbackToIMSC1(t,e){const i=this.tracks[t.level];i.textCodec||Id(e,this.initPTS[t.cc],()=>{i.textCodec=Sa,this._parseIMSC1(t,e)},()=>{i.textCodec="wvtt"})}_appendCues(t,e){const i=this.hls;if(this.config.renderTextTracksNatively){const s=this.textTracks[e];if(!s||s.mode==="disabled")return;t.forEach(n=>_h(s,n))}else{const s=this.tracks[e];if(!s)return;const n=s.default?"default":"subtitles"+e;i.trigger(m.CUES_PARSED,{type:"subtitles",cues:t,track:n})}}onFragDecrypted(t,e){const{frag:i}=e;i.type===Y.SUBTITLE&&this.onFragLoaded(m.FRAG_LOADED,e)}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(t,e){const{cea608Parser1:i,cea608Parser2:s}=this;if(!this.enabled||!(i&&s))return;const{frag:n,samples:a}=e;if(!(n.type===Y.MAIN&&this.closedCaptionsForLevel(n)==="NONE"))for(let o=0;o<a.length;o++){const l=a[o].bytes;if(l){const h=this.extractCea608Data(l);i.addData(a[o].pts,h[0]),s.addData(a[o].pts,h[1])}}}onBufferFlushing(t,{startOffset:e,endOffset:i,endOffsetSubtitles:s,type:n}){const{media:a}=this;if(!(!a||a.currentTime<i)){if(!n||n==="video"){const{captionsTracks:o}=this;Object.keys(o).forEach(l=>Wn(o[l],e,i))}if(this.config.renderTextTracksNatively&&e===0&&s!==void 0){const{textTracks:o}=this;Object.keys(o).forEach(l=>Wn(o[l],e,s))}}}extractCea608Data(t){const e=[[],[]],i=t[0]&31;let s=2;for(let n=0;n<i;n++){const a=t[s++],o=127&t[s++],l=127&t[s++];if(!(o===0&&l===0)&&4&a){const h=3&a;(h===0||h===1)&&(e[h].push(o),e[h].push(l))}}return e}}function xv(r,t){return!!r&&r.label===t.name&&!(r.textTrack1||r.textTrack2)}function Pv(r,t,e,i){return Math.min(t,i)-Math.max(r,e)}function xd(){return{ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}}}class Ia{constructor(t){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=t,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.firstLevel=-1,this.media=null,this.restrictedLevels=[],this.timer=void 0,this.clientRect=null,this.registerListeners()}setStreamController(t){this.streamController=t}destroy(){this.unregisterListener(),this.hls.config.capLevelToPlayerSize&&this.stopCapping(),this.media=null,this.clientRect=null,this.hls=this.streamController=null}registerListeners(){const{hls:t}=this;t.on(m.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),t.on(m.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(m.MANIFEST_PARSED,this.onManifestParsed,this),t.on(m.BUFFER_CODECS,this.onBufferCodecs,this),t.on(m.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListener(){const{hls:t}=this;t.off(m.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),t.off(m.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(m.MANIFEST_PARSED,this.onManifestParsed,this),t.off(m.BUFFER_CODECS,this.onBufferCodecs,this),t.off(m.MEDIA_DETACHING,this.onMediaDetaching,this)}onFpsDropLevelCapping(t,e){const i=this.hls.levels[e.droppedLevel];this.isLevelAllowed(i)&&this.restrictedLevels.push({bitrate:i.bitrate,height:i.height,width:i.width})}onMediaAttaching(t,e){this.media=e.media instanceof HTMLVideoElement?e.media:null,this.clientRect=null}onManifestParsed(t,e){const i=this.hls;this.restrictedLevels=[],this.firstLevel=e.firstLevel,i.config.capLevelToPlayerSize&&e.video&&this.startCapping()}onBufferCodecs(t,e){this.hls.config.capLevelToPlayerSize&&e.video&&this.startCapping()}onMediaDetaching(){this.stopCapping()}detectPlayerSize(){if(this.media&&this.mediaHeight>0&&this.mediaWidth>0){const t=this.hls.levels;if(t.length){const e=this.hls;e.autoLevelCapping=this.getMaxLevel(t.length-1),e.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=e.autoLevelCapping}}}getMaxLevel(t){const e=this.hls.levels;if(!e.length)return-1;const i=e.filter((s,n)=>this.isLevelAllowed(s)&&n<=t);return this.clientRect=null,Ia.getMaxLevelByMediaSize(i,this.mediaWidth,this.mediaHeight)}startCapping(){this.timer||(this.autoLevelCapping=Number.POSITIVE_INFINITY,this.hls.firstLevel=this.getMaxLevel(this.firstLevel),self.clearInterval(this.timer),this.timer=self.setInterval(this.detectPlayerSize.bind(this),1e3),this.detectPlayerSize())}stopCapping(){this.restrictedLevels=[],this.firstLevel=-1,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer&&(self.clearInterval(this.timer),this.timer=void 0)}getDimensions(){if(this.clientRect)return this.clientRect;const t=this.media,e={width:0,height:0};if(t){const i=t.getBoundingClientRect();e.width=i.width,e.height=i.height,!e.width&&!e.height&&(e.width=i.right-i.left||t.width||0,e.height=i.bottom-i.top||t.height||0)}return this.clientRect=e,e}get mediaWidth(){return this.getDimensions().width*this.contentScaleFactor}get mediaHeight(){return this.getDimensions().height*this.contentScaleFactor}get contentScaleFactor(){let t=1;if(!this.hls.config.ignoreDevicePixelRatio)try{t=self.devicePixelRatio}catch{}return t}isLevelAllowed(t){return!this.restrictedLevels.some(e=>t.bitrate===e.bitrate&&t.width===e.width&&t.height===e.height)}static getMaxLevelByMediaSize(t,e,i){if(!(t!=null&&t.length))return-1;const s=(a,o)=>o?a.width!==o.width||a.height!==o.height:!0;let n=t.length-1;for(let a=0;a<t.length;a+=1){const o=t[a];if((o.width>=e||o.height>=i)&&s(o,t[a+1])){n=a;break}}return n}}class Ov{constructor(t){this.hls=void 0,this.isVideoPlaybackQualityAvailable=!1,this.timer=void 0,this.media=null,this.lastTime=void 0,this.lastDroppedFrames=0,this.lastDecodedFrames=0,this.streamController=void 0,this.hls=t,this.registerListeners()}setStreamController(t){this.streamController=t}registerListeners(){this.hls.on(m.MEDIA_ATTACHING,this.onMediaAttaching,this)}unregisterListeners(){this.hls.off(m.MEDIA_ATTACHING,this.onMediaAttaching,this)}destroy(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null}onMediaAttaching(t,e){const i=this.hls.config;if(i.capLevelOnFPSDrop){const s=e.media instanceof self.HTMLVideoElement?e.media:null;this.media=s,s&&typeof s.getVideoPlaybackQuality=="function"&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),i.fpsDroppedMonitoringPeriod)}}checkFPS(t,e,i){const s=performance.now();if(e){if(this.lastTime){const n=s-this.lastTime,a=i-this.lastDroppedFrames,o=e-this.lastDecodedFrames,l=1e3*a/n,h=this.hls;if(h.trigger(m.FPS_DROP,{currentDropped:a,currentDecoded:o,totalDroppedFrames:i}),l>0&&a>h.config.fpsDroppedMonitoringThreshold*o){let d=h.currentLevel;L.warn("drop FPS ratio greater than max allowed value for currentLevel: "+d),d>0&&(h.autoLevelCapping===-1||h.autoLevelCapping>=d)&&(d=d-1,h.trigger(m.FPS_DROP_LEVEL_CAPPING,{level:d,droppedLevel:h.currentLevel}),h.autoLevelCapping=d,this.streamController.nextLevelSwitch())}}this.lastTime=s,this.lastDroppedFrames=i,this.lastDecodedFrames=e}}checkFPSInterval(){const t=this.media;if(t)if(this.isVideoPlaybackQualityAvailable){const e=t.getVideoPlaybackQuality();this.checkFPS(t,e.totalVideoFrames,e.droppedVideoFrames)}else this.checkFPS(t,t.webkitDecodedFrameCount,t.webkitDroppedFrameCount)}}const Ar="[eme]";class Ri{constructor(t){this.hls=void 0,this.config=void 0,this.media=null,this.keyFormatPromise=null,this.keySystemAccessPromises={},this._requestLicenseFailureCount=0,this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},this.setMediaKeysQueue=Ri.CDMCleanupPromise?[Ri.CDMCleanupPromise]:[],this.onMediaEncrypted=this._onMediaEncrypted.bind(this),this.onWaitingForKey=this._onWaitingForKey.bind(this),this.debug=L.debug.bind(L,Ar),this.log=L.log.bind(L,Ar),this.warn=L.warn.bind(L,Ar),this.error=L.error.bind(L,Ar),this.hls=t,this.config=t.config,this.registerListeners()}destroy(){this.unregisterListeners(),this.onMediaDetached();const t=this.config;t.requestMediaKeySystemAccessFunc=null,t.licenseXhrSetup=t.licenseResponseCallback=void 0,t.drmSystems=t.drmSystemOptions={},this.hls=this.onMediaEncrypted=this.onWaitingForKey=this.keyIdToKeySessionPromise=null,this.config=null}registerListeners(){this.hls.on(m.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(m.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(m.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(m.MANIFEST_LOADED,this.onManifestLoaded,this)}unregisterListeners(){this.hls.off(m.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(m.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(m.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(m.MANIFEST_LOADED,this.onManifestLoaded,this)}getLicenseServerUrl(t){const{drmSystems:e,widevineLicenseUrl:i}=this.config,s=e[t];if(s)return s.licenseUrl;if(t===ct.WIDEVINE&&i)return i;throw new Error(`no license server URL configured for key-system "${t}"`)}getServerCertificateUrl(t){const{drmSystems:e}=this.config,i=e[t];if(i)return i.serverCertificateUrl;this.log(`No Server Certificate in config.drmSystems["${t}"]`)}attemptKeySystemAccess(t){const e=this.hls.levels,i=(a,o,l)=>!!a&&l.indexOf(a)===o,s=e.map(a=>a.audioCodec).filter(i),n=e.map(a=>a.videoCodec).filter(i);return s.length+n.length===0&&n.push("avc1.42e01e"),new Promise((a,o)=>{const l=h=>{const d=h.shift();this.getMediaKeysPromise(d,s,n).then(c=>a({keySystem:d,mediaKeys:c})).catch(c=>{h.length?l(h):c instanceof ee?o(c):o(new ee({type:W.KEY_SYSTEM_ERROR,details:x.KEY_SYSTEM_NO_ACCESS,error:c,fatal:!0},c.message))})};l(t)})}requestMediaKeySystemAccess(t,e){const{requestMediaKeySystemAccessFunc:i}=this.config;if(typeof i!="function"){let s=`Configured requestMediaKeySystemAccess is not a function ${i}`;return th===null&&self.location.protocol==="http:"&&(s=`navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`),Promise.reject(new Error(s))}return i(t,e)}getMediaKeysPromise(t,e,i){const s=zp(t,e,i,this.config.drmSystemOptions),n=this.keySystemAccessPromises[t];let a=n==null?void 0:n.keySystemAccess;if(!a){this.log(`Requesting encrypted media "${t}" key-system access with config: ${JSON.stringify(s)}`),a=this.requestMediaKeySystemAccess(t,s);const o=this.keySystemAccessPromises[t]={keySystemAccess:a};return a.catch(l=>{this.log(`Failed to obtain access to key-system "${t}": ${l}`)}),a.then(l=>{this.log(`Access for key-system "${l.keySystem}" obtained`);const h=this.fetchServerCertificate(t);return this.log(`Create media-keys for "${t}"`),o.mediaKeys=l.createMediaKeys().then(d=>(this.log(`Media-keys created for "${t}"`),h.then(c=>c?this.setMediaKeysServerCertificate(d,t,c):d))),o.mediaKeys.catch(d=>{this.error(`Failed to create media-keys for "${t}"}: ${d}`)}),o.mediaKeys})}return a.then(()=>n.mediaKeys)}createMediaKeySessionContext({decryptdata:t,keySystem:e,mediaKeys:i}){this.log(`Creating key-system session "${e}" keyId: ${me.hexDump(t.keyId||[])}`);const s=i.createSession(),n={decryptdata:t,keySystem:e,mediaKeys:i,mediaKeysSession:s,keyStatus:"status-pending"};return this.mediaKeySessions.push(n),n}renewKeySession(t){const e=t.decryptdata;if(e.pssh){const i=this.createMediaKeySessionContext(t),s=this.getKeyIdString(e),n="cenc";this.keyIdToKeySessionPromise[s]=this.generateRequestWithPreferredKeySession(i,n,e.pssh,"expired")}else this.warn("Could not renew expired session. Missing pssh initData.");this.removeSession(t)}getKeyIdString(t){if(!t)throw new Error("Could not read keyId of undefined decryptdata");if(t.keyId===null)throw new Error("keyId is null");return me.hexDump(t.keyId)}updateKeySession(t,e){var i;const s=t.mediaKeysSession;return this.log(`Updating key-session "${s.sessionId}" for keyID ${me.hexDump(((i=t.decryptdata)==null?void 0:i.keyId)||[])}
184
- } (data length: ${e&&e.byteLength})`),s.update(e)}selectKeySystemFormat(t){const e=Object.keys(t.levelkeys||{});return this.keyFormatPromise||(this.log(`Selecting key-system from fragment (sn: ${t.sn} ${t.type}: ${t.level}) key formats ${e.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(e)),this.keyFormatPromise}getKeyFormatPromise(t){return new Promise((e,i)=>{const s=Un(this.config),n=t.map(Ql).filter(a=>!!a&&s.indexOf(a)!==-1);return this.getKeySystemSelectionPromise(n).then(({keySystem:a})=>{const o=Jl(a);o?e(o):i(new Error(`Unable to find format for key-system "${a}"`))}).catch(i)})}loadKey(t){const e=t.keyInfo.decryptdata,i=this.getKeyIdString(e),s=`(keyId: ${i} format: "${e.keyFormat}" method: ${e.method} uri: ${e.uri})`;this.log(`Starting session for key ${s}`);let n=this.keyIdToKeySessionPromise[i];return n||(n=this.keyIdToKeySessionPromise[i]=this.getKeySystemForKeyPromise(e).then(({keySystem:a,mediaKeys:o})=>(this.throwIfDestroyed(),this.log(`Handle encrypted media sn: ${t.frag.sn} ${t.frag.type}: ${t.frag.level} using key ${s}`),this.attemptSetMediaKeys(a,o).then(()=>{this.throwIfDestroyed();const l=this.createMediaKeySessionContext({keySystem:a,mediaKeys:o,decryptdata:e}),h="cenc";return this.generateRequestWithPreferredKeySession(l,h,e.pssh,"playlist-key")}))),n.catch(a=>this.handleError(a))),n}throwIfDestroyed(t="Invalid state"){if(!this.hls)throw new Error("invalid state")}handleError(t){this.hls&&(this.error(t.message),t instanceof ee?this.hls.trigger(m.ERROR,t.data):this.hls.trigger(m.ERROR,{type:W.KEY_SYSTEM_ERROR,details:x.KEY_SYSTEM_NO_KEYS,error:t,fatal:!0}))}getKeySystemForKeyPromise(t){const e=this.getKeyIdString(t),i=this.keyIdToKeySessionPromise[e];if(!i){const s=Ql(t.keyFormat),n=s?[s]:Un(this.config);return this.attemptKeySystemAccess(n)}return i}getKeySystemSelectionPromise(t){if(t.length||(t=Un(this.config)),t.length===0)throw new ee({type:W.KEY_SYSTEM_ERROR,details:x.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${JSON.stringify({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(t)}_onMediaEncrypted(t){const{initDataType:e,initData:i}=t;if(this.debug(`"${t.type}" event: init data type: "${e}"`),i===null)return;let s,n;if(e==="sinf"&&this.config.drmSystems[ct.FAIRPLAY]){const d=Ct(new Uint8Array(i));try{const c=Nn(JSON.parse(d).sinf),u=lh(new Uint8Array(c));if(!u)return;s=u.subarray(8,24),n=ct.FAIRPLAY}catch{this.warn('Failed to parse sinf "encrypted" event message initData');return}}else{const d=yg(i);if(d===null)return;d.version===0&&d.systemId===Zl.WIDEVINE&&d.data&&(s=d.data.subarray(8,24)),n=Yp(d.systemId)}if(!n||!s)return;const a=me.hexDump(s),{keyIdToKeySessionPromise:o,mediaKeySessions:l}=this;let h=o[a];for(let d=0;d<l.length;d++){const c=l[d],u=c.decryptdata;if(u.pssh||!u.keyId)continue;const f=me.hexDump(u.keyId);if(a===f||u.uri.replace(/-/g,"").indexOf(a)!==-1){h=o[f],delete o[f],u.pssh=new Uint8Array(i),u.keyId=s,h=o[a]=h.then(()=>this.generateRequestWithPreferredKeySession(c,e,i,"encrypted-event-key-match"));break}}h||(h=o[a]=this.getKeySystemSelectionPromise([n]).then(({keySystem:d,mediaKeys:c})=>{var u;this.throwIfDestroyed();const f=new us("ISO-23001-7",a,(u=Jl(d))!=null?u:"");return f.pssh=new Uint8Array(i),f.keyId=s,this.attemptSetMediaKeys(d,c).then(()=>{this.throwIfDestroyed();const p=this.createMediaKeySessionContext({decryptdata:f,keySystem:d,mediaKeys:c});return this.generateRequestWithPreferredKeySession(p,e,i,"encrypted-event-no-match")})})),h.catch(d=>this.handleError(d))}_onWaitingForKey(t){this.log(`"${t.type}" event`)}attemptSetMediaKeys(t,e){const i=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${t}"`);const s=Promise.all(i).then(()=>{if(!this.media)throw new Error("Attempted to set mediaKeys without media element attached");return this.media.setMediaKeys(e)});return this.setMediaKeysQueue.push(s),s.then(()=>{this.log(`Media-keys set for "${t}"`),i.push(s),this.setMediaKeysQueue=this.setMediaKeysQueue.filter(n=>i.indexOf(n)===-1)})}generateRequestWithPreferredKeySession(t,e,i,s){var n,a;const o=(n=this.config.drmSystems)==null||(a=n[t.keySystem])==null?void 0:a.generateRequest;if(o)try{const u=o.call(this.hls,e,i,t);if(!u)throw new Error("Invalid response from configured generateRequest filter");e=u.initDataType,i=t.decryptdata.pssh=u.initData?new Uint8Array(u.initData):null}catch(u){var l;if(this.warn(u.message),(l=this.hls)!=null&&l.config.debug)throw u}if(i===null)return this.log(`Skipping key-session request for "${s}" (no initData)`),Promise.resolve(t);const h=this.getKeyIdString(t.decryptdata);this.log(`Generating key-session request for "${s}": ${h} (init data type: ${e} length: ${i?i.byteLength:null})`);const d=new pa;t.mediaKeysSession.onmessage=u=>{const f=t.mediaKeysSession;if(!f){d.emit("error",new Error("invalid state"));return}const{messageType:p,message:g}=u;this.log(`"${p}" message event for session "${f.sessionId}" message size: ${g.byteLength}`),p==="license-request"||p==="license-renewal"?this.renewLicense(t,g).catch(v=>{this.handleError(v),d.emit("error",v)}):p==="license-release"?t.keySystem===ct.FAIRPLAY&&(this.updateKeySession(t,Xl("acknowledged")),this.removeSession(t)):this.warn(`unhandled media key message type "${p}"`)},t.mediaKeysSession.onkeystatuseschange=u=>{if(!t.mediaKeysSession){d.emit("error",new Error("invalid state"));return}this.onKeyStatusChange(t);const f=t.keyStatus;d.emit("keyStatus",f),f==="expired"&&(this.warn(`${t.keySystem} expired for key ${h}`),this.renewKeySession(t))};const c=new Promise((u,f)=>{d.on("error",f),d.on("keyStatus",p=>{p.startsWith("usable")?u():p==="output-restricted"?f(new ee({type:W.KEY_SYSTEM_ERROR,details:x.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED,fatal:!1},"HDCP level output restricted")):p==="internal-error"?f(new ee({type:W.KEY_SYSTEM_ERROR,details:x.KEY_SYSTEM_STATUS_INTERNAL_ERROR,fatal:!0},`key status changed to "${p}"`)):p==="expired"?f(new Error("key expired while generating request")):this.warn(`unhandled key status change "${p}"`)})});return t.mediaKeysSession.generateRequest(e,i).then(()=>{var u;this.log(`Request generated for key-session "${(u=t.mediaKeysSession)==null?void 0:u.sessionId}" keyId: ${h}`)}).catch(u=>{throw new ee({type:W.KEY_SYSTEM_ERROR,details:x.KEY_SYSTEM_NO_SESSION,error:u,fatal:!1},`Error generating key-session request: ${u}`)}).then(()=>c).catch(u=>{throw d.removeAllListeners(),this.removeSession(t),u}).then(()=>(d.removeAllListeners(),t))}onKeyStatusChange(t){t.mediaKeysSession.keyStatuses.forEach((e,i)=>{this.log(`key status change "${e}" for keyStatuses keyId: ${me.hexDump("buffer"in i?new Uint8Array(i.buffer,i.byteOffset,i.byteLength):new Uint8Array(i))} session keyId: ${me.hexDump(new Uint8Array(t.decryptdata.keyId||[]))} uri: ${t.decryptdata.uri}`),t.keyStatus=e})}fetchServerCertificate(t){const e=this.config,i=e.loader,s=new i(e),n=this.getServerCertificateUrl(t);return n?(this.log(`Fetching serverCertificate for "${t}"`),new Promise((a,o)=>{const l={responseType:"arraybuffer",url:n},h=e.certLoadPolicy.default,d={loadPolicy:h,timeout:h.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},c={onSuccess:(u,f,p,g)=>{a(u.data)},onError:(u,f,p,g)=>{o(new ee({type:W.KEY_SYSTEM_ERROR,details:x.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:p,response:Gt({url:l.url,data:void 0},u)},`"${t}" certificate request failed (${n}). Status: ${u.code} (${u.text})`))},onTimeout:(u,f,p)=>{o(new ee({type:W.KEY_SYSTEM_ERROR,details:x.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:p,response:{url:l.url,data:void 0}},`"${t}" certificate request timed out (${n})`))},onAbort:(u,f,p)=>{o(new Error("aborted"))}};s.load(l,d,c)})):Promise.resolve()}setMediaKeysServerCertificate(t,e,i){return new Promise((s,n)=>{t.setServerCertificate(i).then(a=>{this.log(`setServerCertificate ${a?"success":"not supported by CDM"} (${i==null?void 0:i.byteLength}) on "${e}"`),s(t)}).catch(a=>{n(new ee({type:W.KEY_SYSTEM_ERROR,details:x.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:a,fatal:!0},a.message))})})}renewLicense(t,e){return this.requestLicense(t,new Uint8Array(e)).then(i=>this.updateKeySession(t,new Uint8Array(i)).catch(s=>{throw new ee({type:W.KEY_SYSTEM_ERROR,details:x.KEY_SYSTEM_SESSION_UPDATE_FAILED,error:s,fatal:!0},s.message)}))}setupLicenseXHR(t,e,i,s){const n=this.config.licenseXhrSetup;return n?Promise.resolve().then(()=>{if(!i.decryptdata)throw new Error("Key removed");return n.call(this.hls,t,e,i,s)}).catch(a=>{if(!i.decryptdata)throw a;return t.open("POST",e,!0),n.call(this.hls,t,e,i,s)}).then(a=>(t.readyState||t.open("POST",e,!0),{xhr:t,licenseChallenge:a||s})):(t.open("POST",e,!0),Promise.resolve({xhr:t,licenseChallenge:s}))}requestLicense(t,e){const i=this.config.keyLoadPolicy.default;return new Promise((s,n)=>{const a=this.getLicenseServerUrl(t.keySystem);this.log(`Sending license request to URL: ${a}`);const o=new XMLHttpRequest;o.responseType="arraybuffer",o.onreadystatechange=()=>{if(!this.hls||!t.mediaKeysSession)return n(new Error("invalid state"));if(o.readyState===4)if(o.status===200){this._requestLicenseFailureCount=0;let l=o.response;this.log(`License received ${l instanceof ArrayBuffer?l.byteLength:l}`);const h=this.config.licenseResponseCallback;if(h)try{l=h.call(this.hls,o,a,t)}catch(d){this.error(d)}s(l)}else{const l=i.errorRetry,h=l?l.maxNumRetry:0;if(this._requestLicenseFailureCount++,this._requestLicenseFailureCount>h||o.status>=400&&o.status<500)n(new ee({type:W.KEY_SYSTEM_ERROR,details:x.KEY_SYSTEM_LICENSE_REQUEST_FAILED,fatal:!0,networkDetails:o,response:{url:a,data:void 0,code:o.status,text:o.statusText}},`License Request XHR failed (${a}). Status: ${o.status} (${o.statusText})`));else{const d=h-this._requestLicenseFailureCount+1;this.warn(`Retrying license request, ${d} attempts left`),this.requestLicense(t,e).then(s,n)}}},t.licenseXhr&&t.licenseXhr.readyState!==XMLHttpRequest.DONE&&t.licenseXhr.abort(),t.licenseXhr=o,this.setupLicenseXHR(o,a,t,e).then(({xhr:l,licenseChallenge:h})=>{l.send(h)})})}onMediaAttached(t,e){if(!this.config.emeEnabled)return;const i=e.media;this.media=i,i.addEventListener("encrypted",this.onMediaEncrypted),i.addEventListener("waitingforkey",this.onWaitingForKey)}onMediaDetached(){const t=this.media,e=this.mediaKeySessions;t&&(t.removeEventListener("encrypted",this.onMediaEncrypted),t.removeEventListener("waitingforkey",this.onWaitingForKey),this.media=null),this._requestLicenseFailureCount=0,this.setMediaKeysQueue=[],this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},us.clearKeyUriToKeyIdMap();const i=e.length;Ri.CDMCleanupPromise=Promise.all(e.map(s=>this.removeSession(s)).concat(t==null?void 0:t.setMediaKeys(null).catch(s=>{this.log(`Could not clear media keys: ${s}. media.src: ${t==null?void 0:t.src}`)}))).then(()=>{i&&(this.log("finished closing key sessions and clearing media keys"),e.length=0)}).catch(s=>{this.log(`Could not close sessions and clear media keys: ${s}. media.src: ${t==null?void 0:t.src}`)})}onManifestLoading(){this.keyFormatPromise=null}onManifestLoaded(t,{sessionKeys:e}){if(!(!e||!this.config.emeEnabled)&&!this.keyFormatPromise){const i=e.reduce((s,n)=>(s.indexOf(n.keyFormat)===-1&&s.push(n.keyFormat),s),[]);this.log(`Selecting key-system from session-keys ${i.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(i)}}removeSession(t){const{mediaKeysSession:e,licenseXhr:i}=t;if(e){this.log(`Remove licenses and keys and close session ${e.sessionId}`),e.onmessage=null,e.onkeystatuseschange=null,i&&i.readyState!==XMLHttpRequest.DONE&&i.abort(),t.mediaKeysSession=t.decryptdata=t.licenseXhr=void 0;const s=this.mediaKeySessions.indexOf(t);return s>-1&&this.mediaKeySessions.splice(s,1),e.remove().catch(n=>{this.log(`Could not remove session: ${n}`)}).then(()=>e.close()).catch(n=>{this.log(`Could not close session: ${n}`)})}}}Ri.CDMCleanupPromise=void 0;class ee extends Error{constructor(t,e){super(e),this.data=void 0,t.error||(t.error=new Error(e)),this.data=t,t.err=t.error}}const Mv=1;var jt={MANIFEST:"m",AUDIO:"a",VIDEO:"v",MUXED:"av",INIT:"i",CAPTION:"c",TIMED_TEXT:"tt",KEY:"k",OTHER:"o"};const $v="h";class $e{constructor(t){this.hls=void 0,this.config=void 0,this.media=void 0,this.sid=void 0,this.cid=void 0,this.useHeaders=!1,this.initialized=!1,this.starved=!1,this.buffering=!0,this.audioBuffer=void 0,this.videoBuffer=void 0,this.onWaiting=()=>{this.initialized&&(this.starved=!0),this.buffering=!0},this.onPlaying=()=>{this.initialized||(this.initialized=!0),this.buffering=!1},this.applyPlaylistData=s=>{try{this.apply(s,{ot:jt.MANIFEST,su:!this.initialized})}catch(n){L.warn("Could not generate manifest CMCD data.",n)}},this.applyFragmentData=s=>{try{const n=s.frag,a=this.hls.levels[n.level],o=this.getObjectType(n),l={d:n.duration*1e3,ot:o};(o===jt.VIDEO||o===jt.AUDIO||o==jt.MUXED)&&(l.br=a.bitrate/1e3,l.tb=this.getTopBandwidth(o)/1e3,l.bl=this.getBufferLength(o)),this.apply(s,l)}catch(n){L.warn("Could not generate segment CMCD data.",n)}},this.hls=t;const e=this.config=t.config,{cmcd:i}=e;i!=null&&(e.pLoader=this.createPlaylistLoader(),e.fLoader=this.createFragmentLoader(),this.sid=i.sessionId||$e.uuid(),this.cid=i.contentId,this.useHeaders=i.useHeaders===!0,this.registerListeners())}registerListeners(){const t=this.hls;t.on(m.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(m.MEDIA_DETACHED,this.onMediaDetached,this),t.on(m.BUFFER_CREATED,this.onBufferCreated,this)}unregisterListeners(){const t=this.hls;t.off(m.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(m.MEDIA_DETACHED,this.onMediaDetached,this),t.off(m.BUFFER_CREATED,this.onBufferCreated,this)}destroy(){this.unregisterListeners(),this.onMediaDetached(),this.hls=this.config=this.audioBuffer=this.videoBuffer=null}onMediaAttached(t,e){this.media=e.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(t,e){var i,s;this.audioBuffer=(i=e.tracks.audio)==null?void 0:i.buffer,this.videoBuffer=(s=e.tracks.video)==null?void 0:s.buffer}createData(){var t;return{v:Mv,sf:$v,sid:this.sid,cid:this.cid,pr:(t=this.media)==null?void 0:t.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(t,e={}){At(e,this.createData());const i=e.ot===jt.INIT||e.ot===jt.VIDEO||e.ot===jt.MUXED;if(this.starved&&i&&(e.bs=!0,e.su=!0,this.starved=!1),e.su==null&&(e.su=this.buffering),this.useHeaders){const s=$e.toHeaders(e);if(!Object.keys(s).length)return;t.headers||(t.headers={}),At(t.headers,s)}else{const s=$e.toQuery(e);if(!s)return;t.url=$e.appendQueryToUri(t.url,s)}}getObjectType(t){const{type:e}=t;if(e==="subtitle")return jt.TIMED_TEXT;if(t.sn==="initSegment")return jt.INIT;if(e==="audio")return jt.AUDIO;if(e==="main")return this.hls.audioTracks.length?jt.VIDEO:jt.MUXED}getTopBandwidth(t){let e=0,i;const s=this.hls;if(t===jt.AUDIO)i=s.audioTracks;else{const n=s.maxAutoLevel,a=n>-1?n+1:s.levels.length;i=s.levels.slice(0,a)}for(const n of i)n.bitrate>e&&(e=n.bitrate);return e>0?e:NaN}getBufferLength(t){const e=this.hls.media,i=t===jt.AUDIO?this.audioBuffer:this.videoBuffer;return!i||!e?NaN:lt.bufferInfo(i,e.currentTime,this.config.maxBufferHole).len*1e3}createPlaylistLoader(){const{pLoader:t}=this.config,e=this.applyPlaylistData,i=t||this.config.loader;return class{constructor(s){this.loader=void 0,this.loader=new i(s)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(s,n,a){e(s),this.loader.load(s,n,a)}}}createFragmentLoader(){const{fLoader:t}=this.config,e=this.applyFragmentData,i=t||this.config.loader;return class{constructor(s){this.loader=void 0,this.loader=new i(s)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(s,n,a){e(s),this.loader.load(s,n,a)}}}static uuid(){const t=URL.createObjectURL(new Blob),e=t.toString();return URL.revokeObjectURL(t),e.slice(e.lastIndexOf("/")+1)}static serialize(t){const e=[],i=l=>!Number.isNaN(l)&&l!=null&&l!==""&&l!==!1,s=l=>Math.round(l),n=l=>s(l/100)*100,a={br:s,d:s,bl:n,dl:n,mtp:n,nor:l=>encodeURIComponent(l),rtp:n,tb:s},o=Object.keys(t||{}).sort();for(const l of o){let h=t[l];if(!i(h)||l==="v"&&h===1||l=="pr"&&h===1)continue;const d=a[l];d&&(h=d(h));const c=typeof h;let u;l==="ot"||l==="sf"||l==="st"?u=`${l}=${h}`:c==="boolean"?u=l:c==="number"?u=`${l}=${h}`:u=`${l}=${JSON.stringify(h)}`,e.push(u)}return e.join(",")}static toHeaders(t){const e=Object.keys(t),i={},s=["Object","Request","Session","Status"],n=[{},{},{},{}],a={br:0,d:0,ot:0,tb:0,bl:1,dl:1,mtp:1,nor:1,nrr:1,su:1,cid:2,pr:2,sf:2,sid:2,st:2,v:2,bs:3,rtp:3};for(const o of e){const l=a[o]!=null?a[o]:1;n[l][o]=t[o]}for(let o=0;o<n.length;o++){const l=$e.serialize(n[o]);l&&(i[`CMCD-${s[o]}`]=l)}return i}static toQuery(t){return`CMCD=${encodeURIComponent($e.serialize(t))}`}static appendQueryToUri(t,e){if(!e)return t;const i=t.includes("?")?"&":"?";return`${t}${i}${e}`}}const Fv=3e5;class Nv{constructor(t){this.hls=void 0,this.log=void 0,this.loader=null,this.uri=null,this.pathwayId=".",this.pathwayPriority=null,this.timeToLoad=300,this.reloadTimer=-1,this.updated=0,this.started=!1,this.enabled=!0,this.levels=null,this.audioTracks=null,this.subtitleTracks=null,this.penalizedPathways={},this.hls=t,this.log=L.log.bind(L,"[content-steering]:"),this.registerListeners()}registerListeners(){const t=this.hls;t.on(m.MANIFEST_LOADING,this.onManifestLoading,this),t.on(m.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(m.MANIFEST_PARSED,this.onManifestParsed,this),t.on(m.ERROR,this.onError,this)}unregisterListeners(){const t=this.hls;t&&(t.off(m.MANIFEST_LOADING,this.onManifestLoading,this),t.off(m.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(m.MANIFEST_PARSED,this.onManifestParsed,this),t.off(m.ERROR,this.onError,this))}startLoad(){if(this.started=!0,self.clearTimeout(this.reloadTimer),this.enabled&&this.uri)if(this.updated){const t=Math.max(this.timeToLoad*1e3-(performance.now()-this.updated),0);this.scheduleRefresh(this.uri,t)}else this.loadSteeringManifest(this.uri)}stopLoad(){this.started=!1,this.loader&&(this.loader.destroy(),this.loader=null),self.clearTimeout(this.reloadTimer)}destroy(){this.unregisterListeners(),this.stopLoad(),this.hls=null,this.levels=this.audioTracks=this.subtitleTracks=null}removeLevel(t){const e=this.levels;e&&(this.levels=e.filter(i=>i!==t))}onManifestLoading(){this.stopLoad(),this.enabled=!0,this.timeToLoad=300,this.updated=0,this.uri=null,this.pathwayId=".",this.levels=this.audioTracks=this.subtitleTracks=null}onManifestLoaded(t,e){const{contentSteering:i}=e;i!==null&&(this.pathwayId=i.pathwayId,this.uri=i.uri,this.started&&this.startLoad())}onManifestParsed(t,e){this.audioTracks=e.audioTracks,this.subtitleTracks=e.subtitleTracks}onError(t,e){const{errorAction:i}=e;if((i==null?void 0:i.action)===Ot.SendAlternateToPenaltyBox&&i.flags===Jt.MoveAllAlternatesMatchingHost){let s=this.pathwayPriority;const n=this.pathwayId;this.penalizedPathways[n]||(this.penalizedPathways[n]=performance.now()),!s&&this.levels&&(s=this.levels.reduce((a,o)=>(a.indexOf(o.pathwayId)===-1&&a.push(o.pathwayId),a),[])),s&&s.length>1&&(this.updatePathwayPriority(s),i.resolved=this.pathwayId!==n)}}filterParsedLevels(t){this.levels=t;let e=this.getLevelsForPathway(this.pathwayId);if(e.length===0){const i=t[0].pathwayId;this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${i}"`),e=this.getLevelsForPathway(i),this.pathwayId=i}return e.length!==t.length?(this.log(`Found ${e.length}/${t.length} levels in Pathway "${this.pathwayId}"`),e):t}getLevelsForPathway(t){return this.levels===null?[]:this.levels.filter(e=>t===e.pathwayId)}updatePathwayPriority(t){this.pathwayPriority=t;let e;const i=this.penalizedPathways,s=performance.now();Object.keys(i).forEach(n=>{s-i[n]>Fv&&delete i[n]});for(let n=0;n<t.length;n++){const a=t[n];if(i[a])continue;if(a===this.pathwayId)return;const o=this.hls.nextLoadLevel,l=this.hls.levels[o];if(e=this.getLevelsForPathway(a),e.length>0){this.log(`Setting Pathway to "${a}"`),this.pathwayId=a,this.hls.trigger(m.LEVELS_UPDATED,{levels:e});const h=this.hls.levels[o];l&&h&&this.levels&&(h.attrs["STABLE-VARIANT-ID"]!==l.attrs["STABLE-VARIANT-ID"]&&h.bitrate!==l.bitrate&&this.log(`Unstable Pathways change from bitrate ${l.bitrate} to ${h.bitrate}`),this.hls.nextLoadLevel=o);break}}}clonePathways(t){const e=this.levels;if(!e)return;const i={},s={};t.forEach(n=>{const{ID:a,"BASE-ID":o,"URI-REPLACEMENT":l}=n;if(e.some(d=>d.pathwayId===a))return;const h=this.getLevelsForPathway(o).map(d=>{const c=At({},d);c.details=void 0,c.url=Od(d.uri,d.attrs["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",l);const u=new dt(d.attrs);u["PATHWAY-ID"]=a;const f=u.AUDIO&&`${u.AUDIO}_clone_${a}`,p=u.SUBTITLES&&`${u.SUBTITLES}_clone_${a}`;f&&(i[u.AUDIO]=f,u.AUDIO=f),p&&(s[u.SUBTITLES]=p,u.SUBTITLES=p),c.attrs=u;const g=new ps(c);return ur(g,"audio",f),ur(g,"text",p),g});e.push(...h),Pd(this.audioTracks,i,l,a),Pd(this.subtitleTracks,s,l,a)})}loadSteeringManifest(t){const e=this.hls.config,i=e.loader;this.loader&&this.loader.destroy(),this.loader=new i(e);let s;try{s=new self.URL(t)}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest URI: ${t}`);return}if(s.protocol!=="data:"){const d=(this.hls.bandwidthEstimate||e.abrEwmaDefaultEstimate)|0;s.searchParams.set("_HLS_pathway",this.pathwayId),s.searchParams.set("_HLS_throughput",""+d)}const n={responseType:"json",url:s.href},a=e.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},h={onSuccess:(d,c,u,f)=>{this.log(`Loaded steering manifest: "${s}"`);const p=d.data;if(p.VERSION!==1){this.log(`Steering VERSION ${p.VERSION} not supported!`);return}this.updated=performance.now(),this.timeToLoad=p.TTL;const{"RELOAD-URI":g,"PATHWAY-CLONES":v,"PATHWAY-PRIORITY":E}=p;if(g)try{this.uri=new self.URL(g,s).href}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest RELOAD-URI: ${g}`);return}this.scheduleRefresh(this.uri||u.url),v&&this.clonePathways(v),E&&this.updatePathwayPriority(E)},onError:(d,c,u,f)=>{if(this.log(`Error loading steering manifest: ${d.code} ${d.text} (${c.url})`),this.stopLoad(),d.code===410){this.enabled=!1,this.log(`Steering manifest ${c.url} no longer available`);return}let p=this.timeToLoad*1e3;if(d.code===429){const g=this.loader;if(typeof(g==null?void 0:g.getResponseHeader)=="function"){const v=g.getResponseHeader("Retry-After");v&&(p=parseFloat(v)*1e3)}this.log(`Steering manifest ${c.url} rate limited`);return}this.scheduleRefresh(this.uri||c.url,p)},onTimeout:(d,c,u)=>{this.log(`Timeout loading steering manifest (${c.url})`),this.scheduleRefresh(this.uri||c.url)}};this.log(`Requesting steering manifest: ${s}`),this.loader.load(n,l,h)}scheduleRefresh(t,e=this.timeToLoad*1e3){self.clearTimeout(this.reloadTimer),this.reloadTimer=self.setTimeout(()=>{this.loadSteeringManifest(t)},e)}}function Pd(r,t,e,i){r&&Object.keys(t).forEach(s=>{const n=r.filter(a=>a.groupId===s).map(a=>{const o=At({},a);return o.details=void 0,o.attrs=new dt(o.attrs),o.url=o.attrs.URI=Od(a.url,a.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",e),o.groupId=o.attrs["GROUP-ID"]=t[s],o.attrs["PATHWAY-ID"]=i,o});r.push(...n)})}function Od(r,t,e,i){const{HOST:s,PARAMS:n,[e]:a}=i;let o;t&&(o=a==null?void 0:a[t],o&&(r=o));const l=new self.URL(r);return s&&!o&&(l.host=s),n&&Object.keys(n).sort().forEach(h=>{h&&l.searchParams.set(h,n[h])}),l.href}const Uv=/^age:\s*[\d.]+\s*$/im;class Md{constructor(t){this.xhrSetup=void 0,this.requestTimeout=void 0,this.retryTimeout=void 0,this.retryDelay=void 0,this.config=null,this.callbacks=null,this.context=void 0,this.loader=null,this.stats=void 0,this.xhrSetup=t&&t.xhrSetup||null,this.stats=new sr,this.retryDelay=0}destroy(){this.callbacks=null,this.abortInternal(),this.loader=null,this.config=null}abortInternal(){const t=this.loader;self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),t&&(t.onreadystatechange=null,t.onprogress=null,t.readyState!==4&&(this.stats.aborted=!0,t.abort()))}abort(){var t;this.abortInternal(),(t=this.callbacks)!=null&&t.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.loader)}load(t,e,i){if(this.stats.loading.start)throw new Error("Loader can only be used once.");this.stats.loading.start=self.performance.now(),this.context=t,this.config=e,this.callbacks=i,this.loadInternal()}loadInternal(){const{config:t,context:e}=this;if(!t)return;const i=this.loader=new self.XMLHttpRequest,s=this.stats;s.loading.first=0,s.loaded=0,s.aborted=!1;const n=this.xhrSetup;n?Promise.resolve().then(()=>{if(!this.stats.aborted)return n(i,e.url)}).catch(a=>(i.open("GET",e.url,!0),n(i,e.url))).then(()=>{this.stats.aborted||this.openAndSendXhr(i,e,t)}).catch(a=>{this.callbacks.onError({code:i.status,text:a.message},e,i,s)}):this.openAndSendXhr(i,e,t)}openAndSendXhr(t,e,i){t.readyState||t.open("GET",e.url,!0);const s=this.context.headers,{maxTimeToFirstByteMs:n,maxLoadTimeMs:a}=i.loadPolicy;if(s)for(const o in s)t.setRequestHeader(o,s[o]);e.rangeEnd&&t.setRequestHeader("Range","bytes="+e.rangeStart+"-"+(e.rangeEnd-1)),t.onreadystatechange=this.readystatechange.bind(this),t.onprogress=this.loadprogress.bind(this),t.responseType=e.responseType,self.clearTimeout(this.requestTimeout),i.timeout=n&&j(n)?n:a,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),i.timeout),t.send()}readystatechange(){const{context:t,loader:e,stats:i}=this;if(!t||!e)return;const s=e.readyState,n=this.config;if(!i.aborted&&s>=2&&(i.loading.first===0&&(i.loading.first=Math.max(self.performance.now(),i.loading.start),n.timeout!==n.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),n.timeout=n.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),n.loadPolicy.maxLoadTimeMs-(i.loading.first-i.loading.start)))),s===4)){self.clearTimeout(this.requestTimeout),e.onreadystatechange=null,e.onprogress=null;const a=e.status,o=e.responseType!=="text";if(a>=200&&a<300&&(o&&e.response||e.responseText!==null)){i.loading.end=Math.max(self.performance.now(),i.loading.first);const l=o?e.response:e.responseText,h=e.responseType==="arraybuffer"?l.byteLength:l.length;if(i.loaded=i.total=h,i.bwEstimate=i.total*8e3/(i.loading.end-i.loading.first),!this.callbacks)return;const d=this.callbacks.onProgress;if(d&&d(i,t,l,e),!this.callbacks)return;const c={url:e.responseURL,data:l,code:a};this.callbacks.onSuccess(c,i,t,e)}else{const l=n.loadPolicy.errorRetry,h=i.retry;cr(l,h,!1,a)?this.retry(l):(L.error(`${a} while loading ${t.url}`),this.callbacks.onError({code:a,text:e.statusText},t,e,i))}}}loadtimeout(){var t;const e=(t=this.config)==null?void 0:t.loadPolicy.timeoutRetry,i=this.stats.retry;if(cr(e,i,!0))this.retry(e);else{L.warn(`timeout while loading ${this.context.url}`);const s=this.callbacks;s&&(this.abortInternal(),s.onTimeout(this.stats,this.context,this.loader))}}retry(t){const{context:e,stats:i}=this;this.retryDelay=Zn(t,i.retry),i.retry++,L.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${e.url}, retrying ${i.retry}/${t.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(t){const e=this.stats;e.loaded=t.loaded,t.lengthComputable&&(e.total=t.total)}getCacheAge(){let t=null;if(this.loader&&Uv.test(this.loader.getAllResponseHeaders())){const e=this.loader.getResponseHeader("age");t=e?parseFloat(e):null}return t}getResponseHeader(t){return this.loader&&new RegExp(`^${t}:\\s*[\\d.]+\\s*$`,"im").test(this.loader.getAllResponseHeaders())?this.loader.getResponseHeader(t):null}}function Bv(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch{}return!1}const Hv=/(\d+)-(\d+)\/(\d+)/;class $d{constructor(t){this.fetchSetup=void 0,this.requestTimeout=void 0,this.request=void 0,this.response=void 0,this.controller=void 0,this.context=void 0,this.config=null,this.callbacks=null,this.stats=void 0,this.loader=null,this.fetchSetup=t.fetchSetup||jv,this.controller=new self.AbortController,this.stats=new sr}destroy(){this.loader=this.callbacks=null,this.abortInternal()}abortInternal(){const t=this.response;t!=null&&t.ok||(this.stats.aborted=!0,this.controller.abort())}abort(){var t;this.abortInternal(),(t=this.callbacks)!=null&&t.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.response)}load(t,e,i){const s=this.stats;if(s.loading.start)throw new Error("Loader can only be used once.");s.loading.start=self.performance.now();const n=Gv(t,this.controller.signal),a=i.onProgress,o=t.responseType==="arraybuffer",l=o?"byteLength":"length",{maxTimeToFirstByteMs:h,maxLoadTimeMs:d}=e.loadPolicy;this.context=t,this.config=e,this.callbacks=i,this.request=this.fetchSetup(t,n),self.clearTimeout(this.requestTimeout),e.timeout=h&&j(h)?h:d,this.requestTimeout=self.setTimeout(()=>{this.abortInternal(),i.onTimeout(s,t,this.response)},e.timeout),self.fetch(this.request).then(c=>{this.response=this.loader=c;const u=Math.max(self.performance.now(),s.loading.start);if(self.clearTimeout(this.requestTimeout),e.timeout=d,this.requestTimeout=self.setTimeout(()=>{this.abortInternal(),i.onTimeout(s,t,this.response)},d-(u-s.loading.start)),!c.ok){const{status:f,statusText:p}=c;throw new Wv(p||"fetch, bad network response",f,c)}return s.loading.first=u,s.total=Kv(c.headers)||s.total,a&&j(e.highWaterMark)?this.loadProgressively(c,s,t,e.highWaterMark,a):o?c.arrayBuffer():t.responseType==="json"?c.json():c.text()}).then(c=>{const{response:u}=this;self.clearTimeout(this.requestTimeout),s.loading.end=Math.max(self.performance.now(),s.loading.first);const f=c[l];f&&(s.loaded=s.total=f);const p={url:u.url,data:c,code:u.status};a&&!j(e.highWaterMark)&&a(s,t,c,u),i.onSuccess(p,s,t,u)}).catch(c=>{if(self.clearTimeout(this.requestTimeout),s.aborted)return;const u=c&&c.code||0,f=c?c.message:null;i.onError({code:u,text:f},t,c?c.details:null,s)})}getCacheAge(){let t=null;if(this.response){const e=this.response.headers.get("age");t=e?parseFloat(e):null}return t}getResponseHeader(t){return this.response?this.response.headers.get(t):null}loadProgressively(t,e,i,s=0,n){const a=new dd,o=t.body.getReader(),l=()=>o.read().then(h=>{if(h.done)return a.dataLength&&n(e,i,a.flush(),t),Promise.resolve(new ArrayBuffer(0));const d=h.value,c=d.length;return e.loaded+=c,c<s||a.dataLength?(a.push(d),a.dataLength>=s&&n(e,i,a.flush(),t)):n(e,i,d,t),l()}).catch(()=>Promise.reject());return l()}}function Gv(r,t){const e={method:"GET",mode:"cors",credentials:"same-origin",signal:t,headers:new self.Headers(At({},r.headers))};return r.rangeEnd&&e.headers.set("Range","bytes="+r.rangeStart+"-"+String(r.rangeEnd-1)),e}function Vv(r){const t=Hv.exec(r);if(t)return parseInt(t[2])-parseInt(t[1])+1}function Kv(r){const t=r.get("Content-Range");if(t){const i=Vv(t);if(j(i))return i}const e=r.get("Content-Length");if(e)return parseInt(e)}function jv(r,t){return new self.Request(r.url,t)}class Wv extends Error{constructor(t,e,i){super(t),this.code=void 0,this.details=void 0,this.code=e,this.details=i}}const Yv=/\s/,zv={newCue(r,t,e,i){const s=[];let n,a,o,l,h;const d=self.VTTCue||self.TextTrackCue;for(let u=0;u<i.rows.length;u++)if(n=i.rows[u],o=!0,l=0,h="",!n.isEmpty()){var c;for(let g=0;g<n.chars.length;g++)Yv.test(n.chars[g].uchar)&&o?l++:(h+=n.chars[g].uchar,o=!1);n.cueStartTime=t,t===e&&(e+=1e-4),l>=16?l--:l++;const f=Ld(h.trim()),p=wa(t,e,f);r!=null&&(c=r.cues)!=null&&c.getCueById(p)||(a=new d(t,e,f),a.id=p,a.line=u+1,a.align="left",a.position=10+Math.min(80,Math.floor(l*8/32)*10),s.push(a))}return r&&s.length&&(s.sort((u,f)=>u.line==="auto"||f.line==="auto"?0:u.line>8&&f.line>8?f.line-u.line:u.line-f.line),s.forEach(u=>_h(r,u))),s}},qv={maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null},Xv=Gt(Gt({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,maxBufferSize:60*1e3*1e3,maxBufferHole:.1,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,maxFragLookUpTolerance:.25,liveSyncDurationCount:3,liveMaxLatencyDurationCount:1/0,liveSyncDuration:void 0,liveMaxLatencyDuration:void 0,maxLiveSyncPlaybackRate:1,liveDurationInfinity:!1,liveBackBufferLength:null,maxMaxBufferLength:600,enableWorker:!0,workerPath:null,enableSoftwareAES:!0,startLevel:void 0,startFragPrefetch:!1,fpsDroppedMonitoringPeriod:5e3,fpsDroppedMonitoringThreshold:.2,appendErrorMaxRetry:3,loader:Md,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:tv,bufferController:hv,capLevelController:Ia,errorController:Wg,fpsController:Ov,stretchShortVideoTrack:!1,maxAudioFramesDrift:1,forceKeyFrameOnDiscontinuity:!0,abrEwmaFastLive:3,abrEwmaSlowLive:9,abrEwmaFastVoD:3,abrEwmaSlowVoD:9,abrEwmaDefaultEstimate:5e5,abrBandWidthFactor:.95,abrBandWidthUpFactor:.7,abrMaxWithRealBitrate:!1,maxStarvationDelay:4,maxLoadingDelay:4,minAutoBitrate:0,emeEnabled:!1,widevineLicenseUrl:void 0,drmSystems:{},drmSystemOptions:{},requestMediaKeySystemAccessFunc:th,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableID3MetadataCues:!0,certLoadPolicy:{default:qv},keyLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"},errorRetry:{maxNumRetry:8,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"}}},manifestLoadPolicy:{default:{maxTimeToFirstByteMs:1/0,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},playlistLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:2,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},fragLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:12e4,timeoutRetry:{maxNumRetry:4,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:6,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},steeringManifestLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},manifestLoadingTimeOut:1e4,manifestLoadingMaxRetry:1,manifestLoadingRetryDelay:1e3,manifestLoadingMaxRetryTimeout:64e3,levelLoadingTimeOut:1e4,levelLoadingMaxRetry:4,levelLoadingRetryDelay:1e3,levelLoadingMaxRetryTimeout:64e3,fragLoadingTimeOut:2e4,fragLoadingMaxRetry:6,fragLoadingRetryDelay:1e3,fragLoadingMaxRetryTimeout:64e3},Qv()),{},{subtitleStreamController:nv,subtitleTrackController:ov,timelineController:Dv,audioStreamController:iv,audioTrackController:sv,emeController:Ri,cmcdController:$e,contentSteeringController:Nv});function Qv(){return{cueHandler:zv,enableWebVTT:!0,enableIMSC1:!0,enableCEA708Captions:!0,captionsTextTrack1Label:"English",captionsTextTrack1LanguageCode:"en",captionsTextTrack2Label:"Spanish",captionsTextTrack2LanguageCode:"es",captionsTextTrack3Label:"Unknown CC",captionsTextTrack3LanguageCode:"",captionsTextTrack4Label:"Unknown CC",captionsTextTrack4LanguageCode:"",renderTextTracksNatively:!0}}function Zv(r,t){if((t.liveSyncDurationCount||t.liveMaxLatencyDurationCount)&&(t.liveSyncDuration||t.liveMaxLatencyDuration))throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");if(t.liveMaxLatencyDurationCount!==void 0&&(t.liveSyncDurationCount===void 0||t.liveMaxLatencyDurationCount<=t.liveSyncDurationCount))throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(t.liveMaxLatencyDuration!==void 0&&(t.liveSyncDuration===void 0||t.liveMaxLatencyDuration<=t.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');const e=ka(r),i=["manifest","level","frag"],s=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return i.forEach(n=>{const a=`${n==="level"?"playlist":n}LoadPolicy`,o=t[a]===void 0,l=[];s.forEach(h=>{const d=`${n}Loading${h}`,c=t[d];if(c!==void 0&&o){l.push(d);const u=e[a].default;switch(t[a]={default:u},h){case"TimeOut":u.maxLoadTimeMs=c,u.maxTimeToFirstByteMs=c;break;case"MaxRetry":u.errorRetry.maxNumRetry=c,u.timeoutRetry.maxNumRetry=c;break;case"RetryDelay":u.errorRetry.retryDelayMs=c,u.timeoutRetry.retryDelayMs=c;break;case"MaxRetryTimeout":u.errorRetry.maxRetryDelayMs=c,u.timeoutRetry.maxRetryDelayMs=c;break}}}),l.length&&L.warn(`hls.js config: "${l.join('", "')}" setting(s) are deprecated, use "${a}": ${JSON.stringify(t[a])}`)}),Gt(Gt({},e),t)}function ka(r){return r&&typeof r=="object"?Array.isArray(r)?r.map(ka):Object.keys(r).reduce((t,e)=>(t[e]=ka(r[e]),t),{}):r}function Jv(r){const t=r.loader;t!==$d&&t!==Md?(L.log("[config]: Custom loader detected, cannot enable progressive streaming"),r.progressive=!1):Bv()&&(r.loader=$d,r.progressive=!0,r.enableSoftwareAES=!0,L.log("[config]: Progressive streaming enabled, using FetchLoader"))}class Ie{static get version(){return"1.4.12"}static isSupported(){return cm()}static get Events(){return m}static get ErrorTypes(){return W}static get ErrorDetails(){return x}static get DefaultConfig(){return Ie.defaultConfig?Ie.defaultConfig:Xv}static set DefaultConfig(t){Ie.defaultConfig=t}constructor(t={}){this.config=void 0,this.userConfig=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this._emitter=new pa,this._autoLevelCapping=void 0,this._maxHdcpLevel=null,this.abrController=void 0,this.bufferController=void 0,this.capLevelController=void 0,this.latencyController=void 0,this.levelController=void 0,this.streamController=void 0,this.audioTrackController=void 0,this.subtitleTrackController=void 0,this.emeController=void 0,this.cmcdController=void 0,this._media=null,this.url=null,Fp(t.debug||!1,"Hls instance");const e=this.config=Zv(Ie.DefaultConfig,t);this.userConfig=t,this._autoLevelCapping=-1,e.progressive&&Jv(e);const{abrController:i,bufferController:s,capLevelController:n,errorController:a,fpsController:o}=e,l=new a(this),h=this.abrController=new i(this),d=this.bufferController=new s(this),c=this.capLevelController=new n(this),u=new o(this),f=new _g(this),p=new xg(this),g=e.contentSteeringController,v=g?new g(this):null,E=this.levelController=new zg(this,v),T=new qg(this),A=new Qg(this.config),y=this.streamController=new Zm(this,T,A);c.setStreamController(y),u.setStreamController(y);const b=[f,E,y];v&&b.splice(1,0,v),this.networkControllers=b;const S=[h,d,c,u,p,T];this.audioTrackController=this.createController(e.audioTrackController,b);const R=e.audioStreamController;R&&b.push(new R(this,T,A)),this.subtitleTrackController=this.createController(e.subtitleTrackController,b);const D=e.subtitleStreamController;D&&b.push(new D(this,T,A)),this.createController(e.timelineController,S),A.emeController=this.emeController=this.createController(e.emeController,S),this.cmcdController=this.createController(e.cmcdController,S),this.latencyController=this.createController(Pg,S),this.coreComponents=S,b.push(l);const _=l.onErrorOut;typeof _=="function"&&this.on(m.ERROR,_,l)}createController(t,e){if(t){const i=new t(this);return e&&e.push(i),i}return null}on(t,e,i=this){this._emitter.on(t,e,i)}once(t,e,i=this){this._emitter.once(t,e,i)}removeAllListeners(t){this._emitter.removeAllListeners(t)}off(t,e,i=this,s){this._emitter.off(t,e,i,s)}listeners(t){return this._emitter.listeners(t)}emit(t,e,i){return this._emitter.emit(t,e,i)}trigger(t,e){if(this.config.debug)return this.emit(t,t,e);try{return this.emit(t,t,e)}catch(i){L.error("An internal error happened while handling event "+t+'. Error message: "'+i.message+'". Here is a stacktrace:',i),this.trigger(m.ERROR,{type:W.OTHER_ERROR,details:x.INTERNAL_EXCEPTION,fatal:!1,event:t,error:i})}return!1}listenerCount(t){return this._emitter.listenerCount(t)}destroy(){L.log("destroy"),this.trigger(m.DESTROYING,void 0),this.detachMedia(),this.removeAllListeners(),this._autoLevelCapping=-1,this.url=null,this.networkControllers.forEach(e=>e.destroy()),this.networkControllers.length=0,this.coreComponents.forEach(e=>e.destroy()),this.coreComponents.length=0;const t=this.config;t.xhrSetup=t.fetchSetup=void 0,this.userConfig=null}attachMedia(t){L.log("attachMedia"),this._media=t,this.trigger(m.MEDIA_ATTACHING,{media:t})}detachMedia(){L.log("detachMedia"),this.trigger(m.MEDIA_DETACHING,void 0),this._media=null}loadSource(t){this.stopLoad();const e=this.media,i=this.url,s=this.url=Mn.buildAbsoluteURL(self.location.href,t,{alwaysNormalize:!0});L.log(`loadSource:${s}`),e&&i&&(i!==s||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(e)),this.trigger(m.MANIFEST_LOADING,{url:t})}startLoad(t=-1){L.log(`startLoad(${t})`),this.networkControllers.forEach(e=>{e.startLoad(t)})}stopLoad(){L.log("stopLoad"),this.networkControllers.forEach(t=>{t.stopLoad()})}swapAudioCodec(){L.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){L.log("recoverMediaError");const t=this._media;this.detachMedia(),t&&this.attachMedia(t)}removeLevel(t,e=0){this.levelController.removeLevel(t,e)}get levels(){return this.levelController.levels||[]}get currentLevel(){return this.streamController.currentLevel}set currentLevel(t){L.log(`set currentLevel:${t}`),this.loadLevel=t,this.abrController.clearTimer(),this.streamController.immediateLevelSwitch()}get nextLevel(){return this.streamController.nextLevel}set nextLevel(t){L.log(`set nextLevel:${t}`),this.levelController.manualLevel=t,this.streamController.nextLevelSwitch()}get loadLevel(){return this.levelController.level}set loadLevel(t){L.log(`set loadLevel:${t}`),this.levelController.manualLevel=t}get nextLoadLevel(){return this.levelController.nextLoadLevel}set nextLoadLevel(t){this.levelController.nextLoadLevel=t}get firstLevel(){return Math.max(this.levelController.firstLevel,this.minAutoLevel)}set firstLevel(t){L.log(`set firstLevel:${t}`),this.levelController.firstLevel=t}get startLevel(){return this.levelController.startLevel}set startLevel(t){L.log(`set startLevel:${t}`),t!==-1&&(t=Math.max(t,this.minAutoLevel)),this.levelController.startLevel=t}get capLevelToPlayerSize(){return this.config.capLevelToPlayerSize}set capLevelToPlayerSize(t){const e=!!t;e!==this.config.capLevelToPlayerSize&&(e?this.capLevelController.startCapping():(this.capLevelController.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=e)}get autoLevelCapping(){return this._autoLevelCapping}get bandwidthEstimate(){const{bwEstimator:t}=this.abrController;return t?t.getEstimate():NaN}get ttfbEstimate(){const{bwEstimator:t}=this.abrController;return t?t.getEstimateTTFB():NaN}set autoLevelCapping(t){this._autoLevelCapping!==t&&(L.log(`set autoLevelCapping:${t}`),this._autoLevelCapping=t)}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(t){qn.indexOf(t)>-1&&(this._maxHdcpLevel=t)}get autoLevelEnabled(){return this.levelController.manualLevel===-1}get manualLevel(){return this.levelController.manualLevel}get minAutoLevel(){const{levels:t,config:{minAutoBitrate:e}}=this;if(!t)return 0;const i=t.length;for(let s=0;s<i;s++)if(t[s].maxBitrate>=e)return s;return 0}get maxAutoLevel(){const{levels:t,autoLevelCapping:e,maxHdcpLevel:i}=this;let s;if(e===-1&&t&&t.length?s=t.length-1:s=e,i)for(let n=s;n--;){const a=t[n].attrs["HDCP-LEVEL"];if(a&&a<=i)return n}return s}get nextAutoLevel(){return Math.min(Math.max(this.abrController.nextAutoLevel,this.minAutoLevel),this.maxAutoLevel)}set nextAutoLevel(t){this.abrController.nextAutoLevel=Math.max(this.minAutoLevel,t)}get playingDate(){return this.streamController.currentProgramDateTime}get mainForwardBufferInfo(){return this.streamController.getMainFwdBufferInfo()}get audioTracks(){const t=this.audioTrackController;return t?t.audioTracks:[]}get audioTrack(){const t=this.audioTrackController;return t?t.audioTrack:-1}set audioTrack(t){const e=this.audioTrackController;e&&(e.audioTrack=t)}get subtitleTracks(){const t=this.subtitleTrackController;return t?t.subtitleTracks:[]}get subtitleTrack(){const t=this.subtitleTrackController;return t?t.subtitleTrack:-1}get media(){return this._media}set subtitleTrack(t){const e=this.subtitleTrackController;e&&(e.subtitleTrack=t)}get subtitleDisplay(){const t=this.subtitleTrackController;return t?t.subtitleDisplay:!1}set subtitleDisplay(t){const e=this.subtitleTrackController;e&&(e.subtitleDisplay=t)}get lowLatencyMode(){return this.config.lowLatencyMode}set lowLatencyMode(t){this.config.lowLatencyMode=t}get liveSyncPosition(){return this.latencyController.liveSyncPosition}get latency(){return this.latencyController.latency}get maxLatency(){return this.latencyController.maxLatency}get targetLatency(){return this.latencyController.targetLatency}get drift(){return this.latencyController.drift}get forceStartLoad(){return this.streamController.forceStartLoad}}Ie.defaultConfig=void 0;const t0=(r,t,e,i)=>{if(e==="length"||e==="prototype"||e==="arguments"||e==="caller")return;const s=Object.getOwnPropertyDescriptor(r,e),n=Object.getOwnPropertyDescriptor(t,e);!e0(s,n)&&i||Object.defineProperty(r,e,n)},e0=function(r,t){return r===void 0||r.configurable||r.writable===t.writable&&r.enumerable===t.enumerable&&r.configurable===t.configurable&&(r.writable||r.value===t.value)},i0=(r,t)=>{const e=Object.getPrototypeOf(t);e!==Object.getPrototypeOf(r)&&Object.setPrototypeOf(r,e)},s0=(r,t)=>`/* Wrapped ${r}*/
185
- ${t}`,r0=Object.getOwnPropertyDescriptor(Function.prototype,"toString"),n0=Object.getOwnPropertyDescriptor(Function.prototype.toString,"name"),a0=(r,t,e)=>{const i=e===""?"":`with ${e.trim()}() `,s=s0.bind(null,i,t.toString());Object.defineProperty(s,"name",n0),Object.defineProperty(r,"toString",{...r0,value:s})};function o0(r,t,{ignoreNonConfigurable:e=!1}={}){const{name:i}=r;for(const s of Reflect.ownKeys(t))t0(r,t,s,e);return i0(r,t),a0(r,t,i),r}const l0=new WeakMap;function Fd(r,{cacheKey:t=([i])=>i,cache:e=new Map}={}){const i=new Map,s=function(...n){const a=t(n);if(i.has(a))return i.get(a);const o=(async()=>{try{if(e&&await e.has(a))return await e.get(a);const l=await r.apply(this,n);try{return l}finally{e&&await e.set(a,l)}}finally{i.delete(a)}})();return i.set(a,o),o};return o0(s,r,{ignoreNonConfigurable:!0}),l0.set(s,e),s}function h0(){return/^((?!chrome|android).)*safari/i.test(navigator.userAgent)}function d0(){return["iPad Simulator","iPhone Simulator","iPod Simulator","iPad","iPhone","iPod"].includes(navigator.platform)||navigator.userAgent.includes("Mac")&&"ontouchend"in document}async function c0(r){return r.duration===1/0?new Promise(t=>{r.currentTime=Number.MAX_SAFE_INTEGER,r.ontimeupdate=()=>{r.ontimeupdate=null,t(r.duration),r.currentTime=0}}):r.duration}class u0{constructor(t){this._duration=0,this._processing=!1,this._scenes=null,this._videos={},this._videoMeta={},this._videoState={},this._resolveVideo=Fd(e=>{const{id:i,src:s,playlist:n,duration:a}=e;return this._cleanupVideo(i),new Promise(o=>{let l=null;const h=document.createElement("video");h.playsInline=!0,h.muted=!0,h.loop=!1,h.volume=this.host.volume,h.playbackRate=this.host.playbackRate;const d={loadeddata:this._handleLoadedData,waiting:this._handleWaiting,canplay:this._handleCanPlay,progress:this._handleProgress,seeked:this._handleSeeked,play:this._handlePlay,playing:this._handlePlaying,pause:this._handlePause,stalled:this._handleStalled,timeupdate:this._handleTimeUpdate,ended:this._handleEnded,error:this._handleError},c=Object.keys(d).reduce((u,f)=>{const p=f,g=d[p](i,h);return u[p]=g,h.addEventListener(f,g),u},{});if(n&&!h0()&&Ie.isSupported()){let u=!1;l=new Ie({autoStartLoad:!0,xhrSetup:f=>{const{open:p}=f,g=n.split("?")[1];f.open=function(v,E,T){E.toString().includes("?")||(E+="?"+g),p.apply(this,[v,E,T])}}}),l.loadSource(n),l.attachMedia(h),l.startLoadOnce=(f=-1)=>{l&&!u&&(l.startLoad(f),u=!0)},l.on(Ie.Events.LEVEL_LOADED,async()=>{u||l==null||l.stopLoad(),o({id:i,hls:l,node:h})})}else{h.src=s;let u=!1;if(h.startLoadOnce=()=>{u||(h.preload="auto",h.load(),u=!0)},a)h.preload="none",o({id:i,hls:l,node:h});else{h.preload="metadata";const f=async()=>{o({id:i,hls:l,node:h}),h.removeEventListener("loadedmetadata",f)};h.addEventListener("loadedmetadata",f)}}this.videos[i]={id:i,hls:l,node:h,listeners:c},this.videoState[i]={initialised:!1,waiting:!0,buffered:[]}})},{cacheKey:([{id:e,src:i,playlist:s}])=>JSON.stringify({id:e,src:i.split("?")[0],playlist:s==null?void 0:s.split("?")[0]})}),this._resolveVideoMeta=Fd(async(e,i)=>{const{id:s,captions:n,duration:a,startOffset:o,endOffset:l}=e,h=a??await c0(i),d=(o??0)*h,c=(1-(l??0))*h,u={id:s,captions:n,start:d,duration:c};return this.videoMeta[s]=u,u},{cacheKey:([{id:e,captions:i,duration:s,startOffset:n,endOffset:a}])=>JSON.stringify({id:e,captions:i,duration:s,startOffset:n,endOffset:a})}),this._handleLoadedData=(e,i)=>()=>{const s=this.videoState[e];s!=null&&s.initialised||(this.videoState={...this.videoState,[e]:{...s,initialised:!0,waiting:!1,buffered:(s==null?void 0:s.buffered)??[]}},this.setVideosCurrentTime(this.host.currentTime),this.host.dispatchEvent(new CustomEvent("video:loadeddata",{detail:{id:e,node:i}})))},this._handleWaiting=e=>()=>{const i=this.videoState[e];i!=null&&i.initialised&&!(i!=null&&i.waiting)&&(this.videoState={...this.videoState,[e]:{...i,waiting:!0}})},this._handleCanPlay=e=>()=>{const i=this.videoState[e];i!=null&&i.initialised&&i!=null&&i.waiting&&(this.videoState={...this.videoState,[e]:{...i,waiting:!1}})},this._handleProgress=(e,i)=>()=>{var s;const n=i==null?void 0:i.buffered,a=[],{start:o,video:l,videoMeta:h}=((s=this.scenes)==null?void 0:s.scenes.find(({video:d})=>e===(d==null?void 0:d.id)))??{};if(i&&n&&l&&h&&typeof o<"u"){for(let c=0;c<n.length;c++){const u=n.start(c),f=n.end(c);Math.max(u,h.start)<=Math.min(f,h.start+h.duration)&&a.push({start:Math.max(0,(Math.max(u-h.start,0)+o)/this.host.duration*100),end:Math.min((Math.min(f-h.start,h.duration)+o)/this.host.duration*100,100)})}const d=this.videoState[e];this.videoState={...this.videoState,[e]:{...d,buffered:a}}}},this._handleSeeked=(e,i)=>()=>{const s=this.videoState[e];s!=null&&s.initialised&&(this.host.draw(),this.host.dispatchEvent(new CustomEvent("video:seeked",{detail:{id:e,node:i}})))},this._handlePlay=(e,i)=>()=>{this.host.dispatchEvent(new CustomEvent("video:play",{detail:{id:e,node:i}}))},this._handlePlaying=(e,i)=>()=>{this.host.dispatchEvent(new CustomEvent("video:playing",{detail:{id:e,node:i}}))},this._handlePause=(e,i)=>()=>{this.host.dispatchEvent(new CustomEvent("video:pause",{detail:{id:e,node:i}}))},this._handleStalled=(e,i)=>()=>{this.host.dispatchEvent(new CustomEvent("video:stalled",{detail:{id:e,node:i}}))},this._handleTimeUpdate=(e,i)=>()=>{this.host.dispatchEvent(new CustomEvent("video:timeupdate",{detail:{id:e,node:i}}))},this._handleEnded=(e,i)=>()=>{this.host.dispatchEvent(new CustomEvent("video:ended",{detail:{id:e,node:i}}))},this._handleError=(e,i)=>()=>{this.host.dispatchEvent(new CustomEvent("video:error",{detail:{id:e,node:i}}))},this.host=t,this.host.addController(this)}set processing(t){t!==this._processing&&(this._processing=t,this.host.requestUpdate())}get processing(){return this._processing}set duration(t){!isNaN(t)&&t!==this._duration&&(this._duration=t,this.host.requestUpdate(),this.host.dispatchEvent(new CustomEvent("durationchange",{detail:this._duration})))}get duration(){return this._duration}set scenes(t){this._scenes=t,this.host.requestUpdate()}get scenes(){return this._scenes}set videos(t){this._videos=t,this.host.requestUpdate()}get videos(){return this._videos}set videoMeta(t){this._videoMeta=t,this.host.requestUpdate()}get videoMeta(){return this._videoMeta}set videoState(t){this._videoState=t,this.host.requestUpdate()}get videoState(){return this._videoState}_setupTask(){new Mo(this.host,async([t,e,i,s,n])=>{try{if(i||t){if(this.processing=!0,i){let a=null;if(s)try{a=await(await fetch(s,{method:"GET"})).text()}catch{this.host.dispatchEvent(new ErrorEvent("error",new Error("Track failed to fetch")))}const o=i.includes(".m3u8")?"playlist":"video";this.scenes=await tl({data:{questions:{items:[{answer:{id:"source",media:{[o]:i},captions:{current:a}}}]}},template:e,burnCaptions:n},this._resolveVideo,this._resolveVideoMeta)}else this.scenes=await tl({data:t,template:e,burnCaptions:n},this._resolveVideo,this._resolveVideoMeta);(await Promise.all(this.scenes.fonts.map(a=>new FontFace(a.name,`url(${a.url})`,{style:a.style,weight:a.weight}).load()))).forEach(a=>{document.fonts.add(a)}),this.duration=this.scenes.duration,this.host.reset(this.host.currentTime,!this.host.paused),this.host.autoplay&&this.host.play()}}catch{this.scenes=null,this.duration=0,this.host.dispatchEvent(new ErrorEvent("error",new Error("Failed to create scenes")))}finally{this.processing=!1}},()=>[this.host.data,this.host.template,this.host.src,this.host.track,this.host.burnCaptions])}_setVideoCurrentTime({time:t,scene:e}){const{start:i,video:s,videoMeta:n}=e;if(s&&s.node&&n&&typeof i<"u"){const a=t-i;s.node.currentTime=Math.max(n.start,Math.min(n.start+n.duration,a+n.start))}}setVideosCurrentTime(t){var e;(e=this.scenes)==null||e.scenes.forEach(i=>{this._setVideoCurrentTime({time:t,scene:i})})}_cleanupVideo(t){var e;const i=this.videos[t];i&&((e=i.hls)==null||e.destroy(),i.node.pause(),i.node.src="",Object.keys(i.listeners).forEach(s=>{var n;if((n=this.videos)!=null&&n[t]){const a=i.listeners[s];i.node.removeEventListener(s,a)}}),delete this.videos[t])}hostConnected(){this._setupTask()}hostDisconnected(){Object.keys(this.videos).forEach(t=>{this._cleanupVideo(t)}),this.videos={}}}function f0(r){r.requestFullscreen?r.requestFullscreen():r.mozRequestFullScreen?r.mozRequestFullScreen():r.webkitRequestFullscreen?r.webkitRequestFullscreen():r.msRequestFullscreen&&r.msRequestFullscreen()}function p0(){document.exitFullscreen?document.exitFullscreen():document.mozCancelFullScreen?document.mozCancelFullScreen():document.webkitExitFullscreen&&document.webkitExitFullscreen()}const Ca=["progress","play-large","navigation","play","volume","current-time","duration","speed","captions","fullscreen"],g0={id:"captions",event:"captions:click",label:"Closed Captions"},m0={id:"fullscreen",event:"fullscreen:click",label:"Full Screen"},Nd={title:"Playback Speed",items:[{id:"playback-rate-0.5",event:"playbackRate:click",label:"0.5x",value:.5},{id:"playback-rate-1",event:"playbackRate:click",label:"1.0x",value:1},{id:"playback-rate-1.5",event:"playbackRate:click",label:"1.5x",value:1.5},{id:"playback-rate-2",event:"playbackRate:click",label:"2.0x",value:2}]},v0={id:"playbackRate",label:"Playback playbackRate",subItems:Nd};class y0 extends sl{constructor(t){if(super(t),this.element=null,this.observer=void 0,t.type!==Qi.ELEMENT)throw new Error("Resize directive must be used in an Element expression")}disconnected(){var t;(t=this.observer)==null||t.disconnect(),this.observer=void 0}reconnected(){var t;this.element&&((t=this.observer)==null||t.observe(this.element))}update(t,[e]){return this.isConnected&&!this.observer&&(this.observer=new ResizeObserver(e),this.element=t.element,this.observer.observe(this.element)),he}}const Da=Zi(y0),ye={"red-120":"#feeded","red-130":"#fcd5d0","red-400":"#e84a4a","red-500":"#c51c3a","red-700":"#a21c39","red-800":"#850231","red-900":"#580A2D","teal-100":"#a5e9ed","teal-600":"#006776","purple-100":"#d7cfff","purple-700":"#5f2fe9","green-200":"#a4d7aa","green-500":"#38b319","green-800":"#2b3c2f","grey-100":"#f0f0f0","light-50":"rgba(255, 255, 255, .05)","light-100":"rgba(255, 255, 255, .1)","light-200":"rgba(255, 255, 255, .2)","light-400":"rgba(255, 255, 255, .4)","light-500":"rgba(255, 255, 255, .5)","light-640":"rgba(255, 255, 255, .64)","light-800":"rgba(255, 255, 255, .8)","light-1000":"#fff","dark-50":"rgba(0, 0, 0, .05)","dark-80":"rgba(0, 0, 0, .08)","dark-100":"rgba(0, 0, 0, .1)","dark-200":"rgba(0, 0, 0, .2)","dark-250":"rgba(0, 0, 0, .25)","dark-400":"rgba(0, 0, 0, .4)","dark-500":"rgba(0, 0, 0, .5)","dark-640":"rgba(0, 0, 0, .64)","dark-800":"rgba(0, 0, 0, .8)","dark-900":"rgba(0, 0, 0, .9)","dark-1000":"#000"},E0={colors:ye,space:{xxs:".25rem",xs:".5rem",small:".75rem",medium:"1rem",large:"1.5rem",xl:"2.5rem"},sizes:{xxs:"1rem",xs:"1.5rem",small:"2rem",medium:"2.5rem",large:"3rem"},fontWeights:{regular:400,semibold:600},lineHeights:{small:1.1,medium:1.25,large:1.4},letterSpacings:{xxs:"-.04rem",xs:"-.03rem",small:"-.02rem",medium:"-.01rem",large:0},fontSizes:{micro:".625rem",small:".75rem",medium:".875rem",large:"1rem",xl:"1.25rem",xxl:"1.5rem",xxxl:"2rem",huge:"2.75rem"},fontFamilies:{sans:'Roobert, "Times New Roman", -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial,"Noto Sans", sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji"',mono:'"Maison Neue Mono", Menlo, Monaco, Consolas, Liberation Mono, "Courier New", monospace'},borderWidths:{thin:".0625rem"},radii:{small:".25rem",medium:".5rem",large:".75rem",xl:"1rem"},shadows:{small:`.25rem .25rem .25rem ${ye["dark-100"]}`,medium:`0 .125rem .625rem ${ye["dark-100"]}`,large:`0 .25rem 1rem ${ye["dark-50"]}`,xl:`.25rem .25rem 1rem ${ye["dark-250"]}`,xxl:`0 .25rem 2rem ${ye["dark-100"]}`,xxxl:`.25rem .25rem 3rem ${ye["dark-250"]}`,toolbar:`0 -.625rem .625rem ${ye["dark-50"]}`,text:`0 0 .25rem ${ye["dark-250"]}`},timings:{fast:".1s",normal:".2s",slow:".3s"},easings:{linear:"linear"},focusOutline:{width:".2rem",color:ye["dark-400"]},iconSizes:{small:"0.75rem",medium:"1rem",large:"1.5rem"}},Ud=Zu.flatten(E0,{delimiter:"-"}),T0=Object.keys(Ud).map(r=>Oi(`:host { --${r}: ${Ud[r]}; }`)),b0=r=>{class t extends r{firstUpdated(){const i=new FontFace("Roobert","url(https://media-player-fonts.s3.ap-southeast-2.amazonaws.com/Roobert-Regular.woff2)",{style:"normal",weight:"400"}),s=new FontFace("Roobert","url(https://media-player-fonts.s3.ap-southeast-2.amazonaws.com/Roobert-SemiBold.woff2)",{style:"normal",weight:"600"});document.fonts.add(i),document.fonts.add(s)}}return t.styles=[(r==null?void 0:r.styles)??[],T0,Ft`
170
+ `),h=[],c=t?lm(t.baseTime,t.timescale):0;let d="00:00.000",u=0,f=0,p,g=!0;o.oncue=function(v){const E=e[i];let A=e.ccOffset;const L=(u-c)/9e4;if(E!=null&&E.new&&(f!==void 0?A=e.ccOffset=E.start:Xm(e,i,L)),L){if(!t){p=new Error("Missing initPTS for VTT MPEGTS");return}A=L-e.presentationOffset}const y=v.endTime-v.startTime,S=ue((v.startTime+A-f)*9e4,s*9e4)/9e4;v.startTime=Math.max(S,0),v.endTime=Math.max(S+y,0);const R=v.text.trim();v.text=decodeURIComponent(encodeURIComponent(R)),v.id||(v.id=ca(v.startTime,v.endTime,R)),v.endTime>0&&h.push(v)},o.onparsingerror=function(v){p=v},o.onflush=function(){if(p){a(p);return}n(h)},l.forEach(v=>{if(g)if(la(v,"X-TIMESTAMP-MAP=")){g=!1,v.slice(16).split(",").forEach(E=>{la(E,"LOCAL:")?d=E.slice(6):la(E,"MPEGTS:")&&(u=parseInt(E.slice(7)))});try{f=qm(d)/1e3}catch(E){p=E}return}else v===""&&(g=!1);o.parse(v+`
171
+ `)}),o.flush()}const da="stpp.ttml.im1t",rc=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,nc=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,Zm={left:"start",center:"center",right:"end",start:"start",end:"end"};function ac(r,t,e,i){const s=ot(new Uint8Array(r),["mdat"]);if(s.length===0){i(new Error("Could not parse IMSC1 mdat"));return}const n=s.map(o=>Se(o)),a=om(t.baseTime,1,t.timescale);try{n.forEach(o=>e(Jm(o,a)))}catch(o){i(o)}}function Jm(r,t){const e=new DOMParser().parseFromString(r,"text/xml").getElementsByTagName("tt")[0];if(!e)throw new Error("Invalid ttml");const i={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:0},s=Object.keys(i).reduce((h,c)=>(h[c]=e.getAttribute(`ttp:${c}`)||i[c],h),{}),n=e.getAttribute("xml:space")!=="preserve",a=oc(ua(e,"styling","style")),o=oc(ua(e,"layout","region")),l=ua(e,"body","[begin]");return[].map.call(l,h=>{const c=lc(h,n);if(!c||!h.hasAttribute("begin"))return null;const d=pa(h.getAttribute("begin"),s),u=pa(h.getAttribute("dur"),s);let f=pa(h.getAttribute("end"),s);if(d===null)throw hc(h);if(f===null){if(u===null)throw hc(h);f=d+u}const p=new aa(d-t,f-t,c);p.id=ca(p.startTime,p.endTime,p.text);const g=o[h.getAttribute("region")],v=a[h.getAttribute("style")],E=tv(g,v,a),{textAlign:A}=E;if(A){const L=Zm[A];L&&(p.lineAlign=L),p.align=A}return Dt(p,E),p}).filter(h=>h!==null)}function ua(r,t,e){const i=r.getElementsByTagName(t)[0];return i?[].slice.call(i.querySelectorAll(e)):[]}function oc(r){return r.reduce((t,e)=>{const i=e.getAttribute("xml:id");return i&&(t[i]=e),t},{})}function lc(r,t){return[].slice.call(r.childNodes).reduce((e,i,s)=>{var n;return i.nodeName==="br"&&s?e+`
172
+ `:(n=i.childNodes)!=null&&n.length?lc(i,t):t?e+i.textContent.trim().replace(/\s+/g," "):e+i.textContent},"")}function tv(r,t,e){const i="http://www.w3.org/ns/ttml#styling";let s=null;const n=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],a=r!=null&&r.hasAttribute("style")?r.getAttribute("style"):null;return a&&e.hasOwnProperty(a)&&(s=e[a]),n.reduce((o,l)=>{const h=fa(t,i,l)||fa(r,i,l)||fa(s,i,l);return h&&(o[l]=h),o},{})}function fa(r,t,e){return r&&r.hasAttributeNS(t,e)?r.getAttributeNS(t,e):null}function hc(r){return new Error(`Could not parse ttml timestamp ${r}`)}function pa(r,t){if(!r)return null;let e=ec(r);return e===null&&(rc.test(r)?e=ev(r,t):nc.test(r)&&(e=iv(r,t))),e}function ev(r,t){const e=rc.exec(r),i=(e[4]|0)+(e[5]|0)/t.subFrameRate;return(e[1]|0)*3600+(e[2]|0)*60+(e[3]|0)+i/t.frameRate}function iv(r,t){const e=nc.exec(r),i=Number(e[1]);switch(e[2]){case"h":return i*3600;case"m":return i*60;case"ms":return i*1e3;case"f":return i/t.frameRate;case"t":return i/t.tickRate}return i}class sv{constructor(t){if(this.hls=void 0,this.media=null,this.config=void 0,this.enabled=!0,this.Cues=void 0,this.textTracks=[],this.tracks=[],this.initPTS=[],this.unparsedVttFrags=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.cea608Parser1=void 0,this.cea608Parser2=void 0,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=cc(),this.captionsProperties=void 0,this.hls=t,this.config=t.config,this.Cues=t.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}},this.config.enableCEA708Captions){const e=new br(this,"textTrack1"),i=new br(this,"textTrack2"),s=new br(this,"textTrack3"),n=new br(this,"textTrack4");this.cea608Parser1=new Zh(1,e,i),this.cea608Parser2=new Zh(3,s,n)}t.on(m.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(m.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(m.MANIFEST_LOADING,this.onManifestLoading,this),t.on(m.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(m.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.on(m.FRAG_LOADING,this.onFragLoading,this),t.on(m.FRAG_LOADED,this.onFragLoaded,this),t.on(m.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),t.on(m.FRAG_DECRYPTED,this.onFragDecrypted,this),t.on(m.INIT_PTS_FOUND,this.onInitPtsFound,this),t.on(m.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),t.on(m.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){const{hls:t}=this;t.off(m.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(m.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(m.MANIFEST_LOADING,this.onManifestLoading,this),t.off(m.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(m.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.off(m.FRAG_LOADING,this.onFragLoading,this),t.off(m.FRAG_LOADED,this.onFragLoaded,this),t.off(m.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),t.off(m.FRAG_DECRYPTED,this.onFragDecrypted,this),t.off(m.INIT_PTS_FOUND,this.onInitPtsFound,this),t.off(m.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),t.off(m.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.cea608Parser1=this.cea608Parser2=null}addCues(t,e,i,s,n){let a=!1;for(let o=n.length;o--;){const l=n[o],h=nv(l[0],l[1],e,i);if(h>=0&&(l[0]=Math.min(l[0],e),l[1]=Math.max(l[1],i),a=!0,h/(i-e)>.5))return}if(a||n.push([e,i]),this.config.renderTextTracksNatively){const o=this.captionsTracks[t];this.Cues.newCue(o,e,i,s)}else{const o=this.Cues.newCue(null,e,i,s);this.hls.trigger(m.CUES_PARSED,{type:"captions",cues:o,track:t})}}onInitPtsFound(t,{frag:e,id:i,initPTS:s,timescale:n}){const{unparsedVttFrags:a}=this;i==="main"&&(this.initPTS[e.cc]={baseTime:s,timescale:n}),a.length&&(this.unparsedVttFrags=[],a.forEach(o=>{this.onFragLoaded(m.FRAG_LOADED,o)}))}getExistingTrack(t){const{media:e}=this;if(e)for(let i=0;i<e.textTracks.length;i++){const s=e.textTracks[i];if(s[t])return s}return null}createCaptionsTrack(t){this.config.renderTextTracksNatively?this.createNativeTrack(t):this.createNonNativeTrack(t)}createNativeTrack(t){if(this.captionsTracks[t])return;const{captionsProperties:e,captionsTracks:i,media:s}=this,{label:n,languageCode:a}=e[t],o=this.getExistingTrack(t);if(o)i[t]=o,ki(i[t]),rh(i[t],s);else{const l=this.createTextTrack("captions",n,a);l&&(l[t]=!0,i[t]=l)}}createNonNativeTrack(t){if(this.nonNativeCaptionsTracks[t])return;const e=this.captionsProperties[t];if(!e)return;const i=e.label,s={_id:t,label:i,kind:"captions",default:e.media?!!e.media.default:!1,closedCaptions:e.media};this.nonNativeCaptionsTracks[t]=s,this.hls.trigger(m.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[s]})}createTextTrack(t,e,i){const s=this.media;if(s)return s.addTextTrack(t,e,i)}onMediaAttaching(t,e){this.media=e.media,this._cleanTracks()}onMediaDetaching(){const{captionsTracks:t}=this;Object.keys(t).forEach(e=>{ki(t[e]),delete t[e]}),this.nonNativeCaptionsTracks={}}onManifestLoading(){this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=cc(),this._cleanTracks(),this.tracks=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.textTracks=[],this.unparsedVttFrags=[],this.initPTS=[],this.cea608Parser1&&this.cea608Parser2&&(this.cea608Parser1.reset(),this.cea608Parser2.reset())}_cleanTracks(){const{media:t}=this;if(!t)return;const e=t.textTracks;if(e)for(let i=0;i<e.length;i++)ki(e[i])}onSubtitleTracksUpdated(t,e){const i=e.subtitleTracks||[],s=i.some(n=>n.textCodec===da);if(this.config.enableWebVTT||s&&this.config.enableIMSC1){if(Kh(this.tracks,i)){this.tracks=i;return}if(this.textTracks=[],this.tracks=i,this.config.renderTextTracksNatively){const n=this.media?this.media.textTracks:null;this.tracks.forEach((a,o)=>{let l;if(n&&o<n.length){let h=null;for(let c=0;c<n.length;c++)if(rv(n[c],a)){h=n[c];break}h&&(l=h)}if(l)ki(l);else{const h=this._captionsOrSubtitlesFromCharacteristics(a);l=this.createTextTrack(h,a.name,a.lang),l&&(l.mode="disabled")}l&&(l.groupId=a.groupId,this.textTracks.push(l))})}else if(this.tracks.length){const n=this.tracks.map(a=>({label:a.name,kind:a.type.toLowerCase(),default:a.default,subtitleTrack:a}));this.hls.trigger(m.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:n})}}}_captionsOrSubtitlesFromCharacteristics(t){if(t.attrs.CHARACTERISTICS){const e=/transcribes-spoken-dialog/gi.test(t.attrs.CHARACTERISTICS),i=/describes-music-and-sound/gi.test(t.attrs.CHARACTERISTICS);if(e&&i)return"captions"}return"subtitles"}onManifestLoaded(t,e){this.config.enableCEA708Captions&&e.captions&&e.captions.forEach(i=>{const s=/(?:CC|SERVICE)([1-4])/.exec(i.instreamId);if(!s)return;const n=`textTrack${s[1]}`,a=this.captionsProperties[n];a&&(a.label=i.name,i.lang&&(a.languageCode=i.lang),a.media=i)})}closedCaptionsForLevel(t){const e=this.hls.levels[t.level];return e==null?void 0:e.attrs["CLOSED-CAPTIONS"]}onFragLoading(t,e){const{cea608Parser1:i,cea608Parser2:s,lastSn:n,lastPartIndex:a}=this;if(!(!this.enabled||!(i&&s))&&e.frag.type===Z.MAIN){var o,l;const h=e.frag.sn,c=(o=e==null||(l=e.part)==null?void 0:l.index)!=null?o:-1;h===n+1||h===n&&c===a+1||(i.reset(),s.reset()),this.lastSn=h,this.lastPartIndex=c}}onFragLoaded(t,e){const{frag:i,payload:s}=e;if(i.type===Z.SUBTITLE)if(s.byteLength){const n=i.decryptdata,a="stats"in e;if(n==null||!n.encrypted||a){const o=this.tracks[i.level],l=this.vttCCs;l[i.cc]||(l[i.cc]={start:i.start,prevCC:this.prevCC,new:!0},this.prevCC=i.cc),o&&o.textCodec===da?this._parseIMSC1(i,s):this._parseVTTs(e)}}else this.hls.trigger(m.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,error:new Error("Empty subtitle payload")})}_parseIMSC1(t,e){const i=this.hls;ac(e,this.initPTS[t.cc],s=>{this._appendCues(s,t.level),i.trigger(m.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:t})},s=>{_.log(`Failed to parse IMSC1: ${s}`),i.trigger(m.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:t,error:s})})}_parseVTTs(t){var e;const{frag:i,payload:s}=t,{initPTS:n,unparsedVttFrags:a}=this,o=n.length-1;if(!n[i.cc]&&o===-1){a.push(t);return}const l=this.hls,h=(e=i.initSegment)!=null&&e.data?fi(i.initSegment.data,new Uint8Array(s)):s;Qm(h,this.initPTS[i.cc],this.vttCCs,i.cc,i.start,c=>{this._appendCues(c,i.level),l.trigger(m.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:i})},c=>{const d=c.message==="Missing initPTS for VTT MPEGTS";d?a.push(t):this._fallbackToIMSC1(i,s),_.log(`Failed to parse VTT cue: ${c}`),!(d&&o>i.cc)&&l.trigger(m.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,error:c})})}_fallbackToIMSC1(t,e){const i=this.tracks[t.level];i.textCodec||ac(e,this.initPTS[t.cc],()=>{i.textCodec=da,this._parseIMSC1(t,e)},()=>{i.textCodec="wvtt"})}_appendCues(t,e){const i=this.hls;if(this.config.renderTextTracksNatively){const s=this.textTracks[e];if(!s||s.mode==="disabled")return;t.forEach(n=>nh(s,n))}else{const s=this.tracks[e];if(!s)return;const n=s.default?"default":"subtitles"+e;i.trigger(m.CUES_PARSED,{type:"subtitles",cues:t,track:n})}}onFragDecrypted(t,e){const{frag:i}=e;i.type===Z.SUBTITLE&&this.onFragLoaded(m.FRAG_LOADED,e)}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(t,e){const{cea608Parser1:i,cea608Parser2:s}=this;if(!this.enabled||!(i&&s))return;const{frag:n,samples:a}=e;if(!(n.type===Z.MAIN&&this.closedCaptionsForLevel(n)==="NONE"))for(let o=0;o<a.length;o++){const l=a[o].bytes;if(l){const h=this.extractCea608Data(l);i.addData(a[o].pts,h[0]),s.addData(a[o].pts,h[1])}}}onBufferFlushing(t,{startOffset:e,endOffset:i,endOffsetSubtitles:s,type:n}){const{media:a}=this;if(!(!a||a.currentTime<i)){if(!n||n==="video"){const{captionsTracks:o}=this;Object.keys(o).forEach(l=>Pn(o[l],e,i))}if(this.config.renderTextTracksNatively&&e===0&&s!==void 0){const{textTracks:o}=this;Object.keys(o).forEach(l=>Pn(o[l],e,s))}}}extractCea608Data(t){const e=[[],[]],i=t[0]&31;let s=2;for(let n=0;n<i;n++){const a=t[s++],o=127&t[s++],l=127&t[s++];if(!(o===0&&l===0)&&4&a){const h=3&a;(h===0||h===1)&&(e[h].push(o),e[h].push(l))}}return e}}function rv(r,t){return!!r&&r.label===t.name&&!(r.textTrack1||r.textTrack2)}function nv(r,t,e,i){return Math.min(t,i)-Math.max(r,e)}function cc(){return{ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}}}class ga{constructor(t){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=t,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.firstLevel=-1,this.media=null,this.restrictedLevels=[],this.timer=void 0,this.clientRect=null,this.registerListeners()}setStreamController(t){this.streamController=t}destroy(){this.unregisterListener(),this.hls.config.capLevelToPlayerSize&&this.stopCapping(),this.media=null,this.clientRect=null,this.hls=this.streamController=null}registerListeners(){const{hls:t}=this;t.on(m.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),t.on(m.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(m.MANIFEST_PARSED,this.onManifestParsed,this),t.on(m.BUFFER_CODECS,this.onBufferCodecs,this),t.on(m.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListener(){const{hls:t}=this;t.off(m.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),t.off(m.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(m.MANIFEST_PARSED,this.onManifestParsed,this),t.off(m.BUFFER_CODECS,this.onBufferCodecs,this),t.off(m.MEDIA_DETACHING,this.onMediaDetaching,this)}onFpsDropLevelCapping(t,e){const i=this.hls.levels[e.droppedLevel];this.isLevelAllowed(i)&&this.restrictedLevels.push({bitrate:i.bitrate,height:i.height,width:i.width})}onMediaAttaching(t,e){this.media=e.media instanceof HTMLVideoElement?e.media:null,this.clientRect=null}onManifestParsed(t,e){const i=this.hls;this.restrictedLevels=[],this.firstLevel=e.firstLevel,i.config.capLevelToPlayerSize&&e.video&&this.startCapping()}onBufferCodecs(t,e){this.hls.config.capLevelToPlayerSize&&e.video&&this.startCapping()}onMediaDetaching(){this.stopCapping()}detectPlayerSize(){if(this.media&&this.mediaHeight>0&&this.mediaWidth>0){const t=this.hls.levels;if(t.length){const e=this.hls;e.autoLevelCapping=this.getMaxLevel(t.length-1),e.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=e.autoLevelCapping}}}getMaxLevel(t){const e=this.hls.levels;if(!e.length)return-1;const i=e.filter((s,n)=>this.isLevelAllowed(s)&&n<=t);return this.clientRect=null,ga.getMaxLevelByMediaSize(i,this.mediaWidth,this.mediaHeight)}startCapping(){this.timer||(this.autoLevelCapping=Number.POSITIVE_INFINITY,this.hls.firstLevel=this.getMaxLevel(this.firstLevel),self.clearInterval(this.timer),this.timer=self.setInterval(this.detectPlayerSize.bind(this),1e3),this.detectPlayerSize())}stopCapping(){this.restrictedLevels=[],this.firstLevel=-1,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer&&(self.clearInterval(this.timer),this.timer=void 0)}getDimensions(){if(this.clientRect)return this.clientRect;const t=this.media,e={width:0,height:0};if(t){const i=t.getBoundingClientRect();e.width=i.width,e.height=i.height,!e.width&&!e.height&&(e.width=i.right-i.left||t.width||0,e.height=i.bottom-i.top||t.height||0)}return this.clientRect=e,e}get mediaWidth(){return this.getDimensions().width*this.contentScaleFactor}get mediaHeight(){return this.getDimensions().height*this.contentScaleFactor}get contentScaleFactor(){let t=1;if(!this.hls.config.ignoreDevicePixelRatio)try{t=self.devicePixelRatio}catch{}return t}isLevelAllowed(t){return!this.restrictedLevels.some(e=>t.bitrate===e.bitrate&&t.width===e.width&&t.height===e.height)}static getMaxLevelByMediaSize(t,e,i){if(!(t!=null&&t.length))return-1;const s=(a,o)=>o?a.width!==o.width||a.height!==o.height:!0;let n=t.length-1;for(let a=0;a<t.length;a+=1){const o=t[a];if((o.width>=e||o.height>=i)&&s(o,t[a+1])){n=a;break}}return n}}class av{constructor(t){this.hls=void 0,this.isVideoPlaybackQualityAvailable=!1,this.timer=void 0,this.media=null,this.lastTime=void 0,this.lastDroppedFrames=0,this.lastDecodedFrames=0,this.streamController=void 0,this.hls=t,this.registerListeners()}setStreamController(t){this.streamController=t}registerListeners(){this.hls.on(m.MEDIA_ATTACHING,this.onMediaAttaching,this)}unregisterListeners(){this.hls.off(m.MEDIA_ATTACHING,this.onMediaAttaching,this)}destroy(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null}onMediaAttaching(t,e){const i=this.hls.config;if(i.capLevelOnFPSDrop){const s=e.media instanceof self.HTMLVideoElement?e.media:null;this.media=s,s&&typeof s.getVideoPlaybackQuality=="function"&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),i.fpsDroppedMonitoringPeriod)}}checkFPS(t,e,i){const s=performance.now();if(e){if(this.lastTime){const n=s-this.lastTime,a=i-this.lastDroppedFrames,o=e-this.lastDecodedFrames,l=1e3*a/n,h=this.hls;if(h.trigger(m.FPS_DROP,{currentDropped:a,currentDecoded:o,totalDroppedFrames:i}),l>0&&a>h.config.fpsDroppedMonitoringThreshold*o){let c=h.currentLevel;_.warn("drop FPS ratio greater than max allowed value for currentLevel: "+c),c>0&&(h.autoLevelCapping===-1||h.autoLevelCapping>=c)&&(c=c-1,h.trigger(m.FPS_DROP_LEVEL_CAPPING,{level:c,droppedLevel:h.currentLevel}),h.autoLevelCapping=c,this.streamController.nextLevelSwitch())}}this.lastTime=s,this.lastDroppedFrames=i,this.lastDecodedFrames=e}}checkFPSInterval(){const t=this.media;if(t)if(this.isVideoPlaybackQualityAvailable){const e=t.getVideoPlaybackQuality();this.checkFPS(t,e.totalVideoFrames,e.droppedVideoFrames)}else this.checkFPS(t,t.webkitDecodedFrameCount,t.webkitDroppedFrameCount)}}const Ar="[eme]";class Pi{constructor(t){this.hls=void 0,this.config=void 0,this.media=null,this.keyFormatPromise=null,this.keySystemAccessPromises={},this._requestLicenseFailureCount=0,this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},this.setMediaKeysQueue=Pi.CDMCleanupPromise?[Pi.CDMCleanupPromise]:[],this.onMediaEncrypted=this._onMediaEncrypted.bind(this),this.onWaitingForKey=this._onWaitingForKey.bind(this),this.debug=_.debug.bind(_,Ar),this.log=_.log.bind(_,Ar),this.warn=_.warn.bind(_,Ar),this.error=_.error.bind(_,Ar),this.hls=t,this.config=t.config,this.registerListeners()}destroy(){this.unregisterListeners(),this.onMediaDetached();const t=this.config;t.requestMediaKeySystemAccessFunc=null,t.licenseXhrSetup=t.licenseResponseCallback=void 0,t.drmSystems=t.drmSystemOptions={},this.hls=this.onMediaEncrypted=this.onWaitingForKey=this.keyIdToKeySessionPromise=null,this.config=null}registerListeners(){this.hls.on(m.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(m.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(m.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(m.MANIFEST_LOADED,this.onManifestLoaded,this)}unregisterListeners(){this.hls.off(m.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(m.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(m.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(m.MANIFEST_LOADED,this.onManifestLoaded,this)}getLicenseServerUrl(t){const{drmSystems:e,widevineLicenseUrl:i}=this.config,s=e[t];if(s)return s.licenseUrl;if(t===Lt.WIDEVINE&&i)return i;throw new Error(`no license server URL configured for key-system "${t}"`)}getServerCertificateUrl(t){const{drmSystems:e}=this.config,i=e[t];if(i)return i.serverCertificateUrl;this.log(`No Server Certificate in config.drmSystems["${t}"]`)}attemptKeySystemAccess(t){const e=this.hls.levels,i=(a,o,l)=>!!a&&l.indexOf(a)===o,s=e.map(a=>a.audioCodec).filter(i),n=e.map(a=>a.videoCodec).filter(i);return s.length+n.length===0&&n.push("avc1.42e01e"),new Promise((a,o)=>{const l=h=>{const c=h.shift();this.getMediaKeysPromise(c,s,n).then(d=>a({keySystem:c,mediaKeys:d})).catch(d=>{h.length?l(h):d instanceof fe?o(d):o(new fe({type:Q.KEY_SYSTEM_ERROR,details:$.KEY_SYSTEM_NO_ACCESS,error:d,fatal:!0},d.message))})};l(t)})}requestMediaKeySystemAccess(t,e){const{requestMediaKeySystemAccessFunc:i}=this.config;if(typeof i!="function"){let s=`Configured requestMediaKeySystemAccess is not a function ${i}`;return xl===null&&self.location.protocol==="http:"&&(s=`navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`),Promise.reject(new Error(s))}return i(t,e)}getMediaKeysPromise(t,e,i){const s=bp(t,e,i,this.config.drmSystemOptions),n=this.keySystemAccessPromises[t];let a=n==null?void 0:n.keySystemAccess;if(!a){this.log(`Requesting encrypted media "${t}" key-system access with config: ${JSON.stringify(s)}`),a=this.requestMediaKeySystemAccess(t,s);const o=this.keySystemAccessPromises[t]={keySystemAccess:a};return a.catch(l=>{this.log(`Failed to obtain access to key-system "${t}": ${l}`)}),a.then(l=>{this.log(`Access for key-system "${l.keySystem}" obtained`);const h=this.fetchServerCertificate(t);return this.log(`Create media-keys for "${t}"`),o.mediaKeys=l.createMediaKeys().then(c=>(this.log(`Media-keys created for "${t}"`),h.then(d=>d?this.setMediaKeysServerCertificate(c,t,d):c))),o.mediaKeys.catch(c=>{this.error(`Failed to create media-keys for "${t}"}: ${c}`)}),o.mediaKeys})}return a.then(()=>n.mediaKeys)}createMediaKeySessionContext({decryptdata:t,keySystem:e,mediaKeys:i}){this.log(`Creating key-system session "${e}" keyId: ${Le.hexDump(t.keyId||[])}`);const s=i.createSession(),n={decryptdata:t,keySystem:e,mediaKeys:i,mediaKeysSession:s,keyStatus:"status-pending"};return this.mediaKeySessions.push(n),n}renewKeySession(t){const e=t.decryptdata;if(e.pssh){const i=this.createMediaKeySessionContext(t),s=this.getKeyIdString(e),n="cenc";this.keyIdToKeySessionPromise[s]=this.generateRequestWithPreferredKeySession(i,n,e.pssh,"expired")}else this.warn("Could not renew expired session. Missing pssh initData.");this.removeSession(t)}getKeyIdString(t){if(!t)throw new Error("Could not read keyId of undefined decryptdata");if(t.keyId===null)throw new Error("keyId is null");return Le.hexDump(t.keyId)}updateKeySession(t,e){var i;const s=t.mediaKeysSession;return this.log(`Updating key-session "${s.sessionId}" for keyID ${Le.hexDump(((i=t.decryptdata)==null?void 0:i.keyId)||[])}
173
+ } (data length: ${e&&e.byteLength})`),s.update(e)}selectKeySystemFormat(t){const e=Object.keys(t.levelkeys||{});return this.keyFormatPromise||(this.log(`Selecting key-system from fragment (sn: ${t.sn} ${t.type}: ${t.level}) key formats ${e.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(e)),this.keyFormatPromise}getKeyFormatPromise(t){return new Promise((e,i)=>{const s=Rn(this.config),n=t.map(Il).filter(a=>!!a&&s.indexOf(a)!==-1);return this.getKeySystemSelectionPromise(n).then(({keySystem:a})=>{const o=Dl(a);o?e(o):i(new Error(`Unable to find format for key-system "${a}"`))}).catch(i)})}loadKey(t){const e=t.keyInfo.decryptdata,i=this.getKeyIdString(e),s=`(keyId: ${i} format: "${e.keyFormat}" method: ${e.method} uri: ${e.uri})`;this.log(`Starting session for key ${s}`);let n=this.keyIdToKeySessionPromise[i];return n||(n=this.keyIdToKeySessionPromise[i]=this.getKeySystemForKeyPromise(e).then(({keySystem:a,mediaKeys:o})=>(this.throwIfDestroyed(),this.log(`Handle encrypted media sn: ${t.frag.sn} ${t.frag.type}: ${t.frag.level} using key ${s}`),this.attemptSetMediaKeys(a,o).then(()=>{this.throwIfDestroyed();const l=this.createMediaKeySessionContext({keySystem:a,mediaKeys:o,decryptdata:e}),h="cenc";return this.generateRequestWithPreferredKeySession(l,h,e.pssh,"playlist-key")}))),n.catch(a=>this.handleError(a))),n}throwIfDestroyed(t="Invalid state"){if(!this.hls)throw new Error("invalid state")}handleError(t){this.hls&&(this.error(t.message),t instanceof fe?this.hls.trigger(m.ERROR,t.data):this.hls.trigger(m.ERROR,{type:Q.KEY_SYSTEM_ERROR,details:$.KEY_SYSTEM_NO_KEYS,error:t,fatal:!0}))}getKeySystemForKeyPromise(t){const e=this.getKeyIdString(t),i=this.keyIdToKeySessionPromise[e];if(!i){const s=Il(t.keyFormat),n=s?[s]:Rn(this.config);return this.attemptKeySystemAccess(n)}return i}getKeySystemSelectionPromise(t){if(t.length||(t=Rn(this.config)),t.length===0)throw new fe({type:Q.KEY_SYSTEM_ERROR,details:$.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${JSON.stringify({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(t)}_onMediaEncrypted(t){const{initDataType:e,initData:i}=t;if(this.debug(`"${t.type}" event: init data type: "${e}"`),i===null)return;let s,n;if(e==="sinf"&&this.config.drmSystems[Lt.FAIRPLAY]){const c=Ut(new Uint8Array(i));try{const d=Ln(JSON.parse(c).sinf),u=Bl(new Uint8Array(d));if(!u)return;s=u.subarray(8,24),n=Lt.FAIRPLAY}catch{this.warn('Failed to parse sinf "encrypted" event message initData');return}}else{const c=Kp(i);if(c===null)return;c.version===0&&c.systemId===Cl.WIDEVINE&&c.data&&(s=c.data.subarray(8,24)),n=Ep(c.systemId)}if(!n||!s)return;const a=Le.hexDump(s),{keyIdToKeySessionPromise:o,mediaKeySessions:l}=this;let h=o[a];for(let c=0;c<l.length;c++){const d=l[c],u=d.decryptdata;if(u.pssh||!u.keyId)continue;const f=Le.hexDump(u.keyId);if(a===f||u.uri.replace(/-/g,"").indexOf(a)!==-1){h=o[f],delete o[f],u.pssh=new Uint8Array(i),u.keyId=s,h=o[a]=h.then(()=>this.generateRequestWithPreferredKeySession(d,e,i,"encrypted-event-key-match"));break}}h||(h=o[a]=this.getKeySystemSelectionPromise([n]).then(({keySystem:c,mediaKeys:d})=>{var u;this.throwIfDestroyed();const f=new Es("ISO-23001-7",a,(u=Dl(c))!=null?u:"");return f.pssh=new Uint8Array(i),f.keyId=s,this.attemptSetMediaKeys(c,d).then(()=>{this.throwIfDestroyed();const p=this.createMediaKeySessionContext({decryptdata:f,keySystem:c,mediaKeys:d});return this.generateRequestWithPreferredKeySession(p,e,i,"encrypted-event-no-match")})})),h.catch(c=>this.handleError(c))}_onWaitingForKey(t){this.log(`"${t.type}" event`)}attemptSetMediaKeys(t,e){const i=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${t}"`);const s=Promise.all(i).then(()=>{if(!this.media)throw new Error("Attempted to set mediaKeys without media element attached");return this.media.setMediaKeys(e)});return this.setMediaKeysQueue.push(s),s.then(()=>{this.log(`Media-keys set for "${t}"`),i.push(s),this.setMediaKeysQueue=this.setMediaKeysQueue.filter(n=>i.indexOf(n)===-1)})}generateRequestWithPreferredKeySession(t,e,i,s){var n,a;const o=(n=this.config.drmSystems)==null||(a=n[t.keySystem])==null?void 0:a.generateRequest;if(o)try{const u=o.call(this.hls,e,i,t);if(!u)throw new Error("Invalid response from configured generateRequest filter");e=u.initDataType,i=t.decryptdata.pssh=u.initData?new Uint8Array(u.initData):null}catch(u){var l;if(this.warn(u.message),(l=this.hls)!=null&&l.config.debug)throw u}if(i===null)return this.log(`Skipping key-session request for "${s}" (no initData)`),Promise.resolve(t);const h=this.getKeyIdString(t.decryptdata);this.log(`Generating key-session request for "${s}": ${h} (init data type: ${e} length: ${i?i.byteLength:null})`);const c=new ea;t.mediaKeysSession.onmessage=u=>{const f=t.mediaKeysSession;if(!f){c.emit("error",new Error("invalid state"));return}const{messageType:p,message:g}=u;this.log(`"${p}" message event for session "${f.sessionId}" message size: ${g.byteLength}`),p==="license-request"||p==="license-renewal"?this.renewLicense(t,g).catch(v=>{this.handleError(v),c.emit("error",v)}):p==="license-release"?t.keySystem===Lt.FAIRPLAY&&(this.updateKeySession(t,kl("acknowledged")),this.removeSession(t)):this.warn(`unhandled media key message type "${p}"`)},t.mediaKeysSession.onkeystatuseschange=u=>{if(!t.mediaKeysSession){c.emit("error",new Error("invalid state"));return}this.onKeyStatusChange(t);const f=t.keyStatus;c.emit("keyStatus",f),f==="expired"&&(this.warn(`${t.keySystem} expired for key ${h}`),this.renewKeySession(t))};const d=new Promise((u,f)=>{c.on("error",f),c.on("keyStatus",p=>{p.startsWith("usable")?u():p==="output-restricted"?f(new fe({type:Q.KEY_SYSTEM_ERROR,details:$.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED,fatal:!1},"HDCP level output restricted")):p==="internal-error"?f(new fe({type:Q.KEY_SYSTEM_ERROR,details:$.KEY_SYSTEM_STATUS_INTERNAL_ERROR,fatal:!0},`key status changed to "${p}"`)):p==="expired"?f(new Error("key expired while generating request")):this.warn(`unhandled key status change "${p}"`)})});return t.mediaKeysSession.generateRequest(e,i).then(()=>{var u;this.log(`Request generated for key-session "${(u=t.mediaKeysSession)==null?void 0:u.sessionId}" keyId: ${h}`)}).catch(u=>{throw new fe({type:Q.KEY_SYSTEM_ERROR,details:$.KEY_SYSTEM_NO_SESSION,error:u,fatal:!1},`Error generating key-session request: ${u}`)}).then(()=>d).catch(u=>{throw c.removeAllListeners(),this.removeSession(t),u}).then(()=>(c.removeAllListeners(),t))}onKeyStatusChange(t){t.mediaKeysSession.keyStatuses.forEach((e,i)=>{this.log(`key status change "${e}" for keyStatuses keyId: ${Le.hexDump("buffer"in i?new Uint8Array(i.buffer,i.byteOffset,i.byteLength):new Uint8Array(i))} session keyId: ${Le.hexDump(new Uint8Array(t.decryptdata.keyId||[]))} uri: ${t.decryptdata.uri}`),t.keyStatus=e})}fetchServerCertificate(t){const e=this.config,i=e.loader,s=new i(e),n=this.getServerCertificateUrl(t);return n?(this.log(`Fetching serverCertificate for "${t}"`),new Promise((a,o)=>{const l={responseType:"arraybuffer",url:n},h=e.certLoadPolicy.default,c={loadPolicy:h,timeout:h.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},d={onSuccess:(u,f,p,g)=>{a(u.data)},onError:(u,f,p,g)=>{o(new fe({type:Q.KEY_SYSTEM_ERROR,details:$.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:p,response:Qt({url:l.url,data:void 0},u)},`"${t}" certificate request failed (${n}). Status: ${u.code} (${u.text})`))},onTimeout:(u,f,p)=>{o(new fe({type:Q.KEY_SYSTEM_ERROR,details:$.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:p,response:{url:l.url,data:void 0}},`"${t}" certificate request timed out (${n})`))},onAbort:(u,f,p)=>{o(new Error("aborted"))}};s.load(l,c,d)})):Promise.resolve()}setMediaKeysServerCertificate(t,e,i){return new Promise((s,n)=>{t.setServerCertificate(i).then(a=>{this.log(`setServerCertificate ${a?"success":"not supported by CDM"} (${i==null?void 0:i.byteLength}) on "${e}"`),s(t)}).catch(a=>{n(new fe({type:Q.KEY_SYSTEM_ERROR,details:$.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:a,fatal:!0},a.message))})})}renewLicense(t,e){return this.requestLicense(t,new Uint8Array(e)).then(i=>this.updateKeySession(t,new Uint8Array(i)).catch(s=>{throw new fe({type:Q.KEY_SYSTEM_ERROR,details:$.KEY_SYSTEM_SESSION_UPDATE_FAILED,error:s,fatal:!0},s.message)}))}setupLicenseXHR(t,e,i,s){const n=this.config.licenseXhrSetup;return n?Promise.resolve().then(()=>{if(!i.decryptdata)throw new Error("Key removed");return n.call(this.hls,t,e,i,s)}).catch(a=>{if(!i.decryptdata)throw a;return t.open("POST",e,!0),n.call(this.hls,t,e,i,s)}).then(a=>(t.readyState||t.open("POST",e,!0),{xhr:t,licenseChallenge:a||s})):(t.open("POST",e,!0),Promise.resolve({xhr:t,licenseChallenge:s}))}requestLicense(t,e){const i=this.config.keyLoadPolicy.default;return new Promise((s,n)=>{const a=this.getLicenseServerUrl(t.keySystem);this.log(`Sending license request to URL: ${a}`);const o=new XMLHttpRequest;o.responseType="arraybuffer",o.onreadystatechange=()=>{if(!this.hls||!t.mediaKeysSession)return n(new Error("invalid state"));if(o.readyState===4)if(o.status===200){this._requestLicenseFailureCount=0;let l=o.response;this.log(`License received ${l instanceof ArrayBuffer?l.byteLength:l}`);const h=this.config.licenseResponseCallback;if(h)try{l=h.call(this.hls,o,a,t)}catch(c){this.error(c)}s(l)}else{const l=i.errorRetry,h=l?l.maxNumRetry:0;if(this._requestLicenseFailureCount++,this._requestLicenseFailureCount>h||o.status>=400&&o.status<500)n(new fe({type:Q.KEY_SYSTEM_ERROR,details:$.KEY_SYSTEM_LICENSE_REQUEST_FAILED,fatal:!0,networkDetails:o,response:{url:a,data:void 0,code:o.status,text:o.statusText}},`License Request XHR failed (${a}). Status: ${o.status} (${o.statusText})`));else{const c=h-this._requestLicenseFailureCount+1;this.warn(`Retrying license request, ${c} attempts left`),this.requestLicense(t,e).then(s,n)}}},t.licenseXhr&&t.licenseXhr.readyState!==XMLHttpRequest.DONE&&t.licenseXhr.abort(),t.licenseXhr=o,this.setupLicenseXHR(o,a,t,e).then(({xhr:l,licenseChallenge:h})=>{l.send(h)})})}onMediaAttached(t,e){if(!this.config.emeEnabled)return;const i=e.media;this.media=i,i.addEventListener("encrypted",this.onMediaEncrypted),i.addEventListener("waitingforkey",this.onWaitingForKey)}onMediaDetached(){const t=this.media,e=this.mediaKeySessions;t&&(t.removeEventListener("encrypted",this.onMediaEncrypted),t.removeEventListener("waitingforkey",this.onWaitingForKey),this.media=null),this._requestLicenseFailureCount=0,this.setMediaKeysQueue=[],this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},Es.clearKeyUriToKeyIdMap();const i=e.length;Pi.CDMCleanupPromise=Promise.all(e.map(s=>this.removeSession(s)).concat(t==null?void 0:t.setMediaKeys(null).catch(s=>{this.log(`Could not clear media keys: ${s}. media.src: ${t==null?void 0:t.src}`)}))).then(()=>{i&&(this.log("finished closing key sessions and clearing media keys"),e.length=0)}).catch(s=>{this.log(`Could not close sessions and clear media keys: ${s}. media.src: ${t==null?void 0:t.src}`)})}onManifestLoading(){this.keyFormatPromise=null}onManifestLoaded(t,{sessionKeys:e}){if(!(!e||!this.config.emeEnabled)&&!this.keyFormatPromise){const i=e.reduce((s,n)=>(s.indexOf(n.keyFormat)===-1&&s.push(n.keyFormat),s),[]);this.log(`Selecting key-system from session-keys ${i.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(i)}}removeSession(t){const{mediaKeysSession:e,licenseXhr:i}=t;if(e){this.log(`Remove licenses and keys and close session ${e.sessionId}`),e.onmessage=null,e.onkeystatuseschange=null,i&&i.readyState!==XMLHttpRequest.DONE&&i.abort(),t.mediaKeysSession=t.decryptdata=t.licenseXhr=void 0;const s=this.mediaKeySessions.indexOf(t);return s>-1&&this.mediaKeySessions.splice(s,1),e.remove().catch(n=>{this.log(`Could not remove session: ${n}`)}).then(()=>e.close()).catch(n=>{this.log(`Could not close session: ${n}`)})}}}Pi.CDMCleanupPromise=void 0;class fe extends Error{constructor(t,e){super(e),this.data=void 0,t.error||(t.error=new Error(e)),this.data=t,t.err=t.error}}const ov=1;var te={MANIFEST:"m",AUDIO:"a",VIDEO:"v",MUXED:"av",INIT:"i",CAPTION:"c",TIMED_TEXT:"tt",KEY:"k",OTHER:"o"};const lv="h";class Ye{constructor(t){this.hls=void 0,this.config=void 0,this.media=void 0,this.sid=void 0,this.cid=void 0,this.useHeaders=!1,this.initialized=!1,this.starved=!1,this.buffering=!0,this.audioBuffer=void 0,this.videoBuffer=void 0,this.onWaiting=()=>{this.initialized&&(this.starved=!0),this.buffering=!0},this.onPlaying=()=>{this.initialized||(this.initialized=!0),this.buffering=!1},this.applyPlaylistData=s=>{try{this.apply(s,{ot:te.MANIFEST,su:!this.initialized})}catch(n){_.warn("Could not generate manifest CMCD data.",n)}},this.applyFragmentData=s=>{try{const n=s.frag,a=this.hls.levels[n.level],o=this.getObjectType(n),l={d:n.duration*1e3,ot:o};(o===te.VIDEO||o===te.AUDIO||o==te.MUXED)&&(l.br=a.bitrate/1e3,l.tb=this.getTopBandwidth(o)/1e3,l.bl=this.getBufferLength(o)),this.apply(s,l)}catch(n){_.warn("Could not generate segment CMCD data.",n)}},this.hls=t;const e=this.config=t.config,{cmcd:i}=e;i!=null&&(e.pLoader=this.createPlaylistLoader(),e.fLoader=this.createFragmentLoader(),this.sid=i.sessionId||Ye.uuid(),this.cid=i.contentId,this.useHeaders=i.useHeaders===!0,this.registerListeners())}registerListeners(){const t=this.hls;t.on(m.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(m.MEDIA_DETACHED,this.onMediaDetached,this),t.on(m.BUFFER_CREATED,this.onBufferCreated,this)}unregisterListeners(){const t=this.hls;t.off(m.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(m.MEDIA_DETACHED,this.onMediaDetached,this),t.off(m.BUFFER_CREATED,this.onBufferCreated,this)}destroy(){this.unregisterListeners(),this.onMediaDetached(),this.hls=this.config=this.audioBuffer=this.videoBuffer=null}onMediaAttached(t,e){this.media=e.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(t,e){var i,s;this.audioBuffer=(i=e.tracks.audio)==null?void 0:i.buffer,this.videoBuffer=(s=e.tracks.video)==null?void 0:s.buffer}createData(){var t;return{v:ov,sf:lv,sid:this.sid,cid:this.cid,pr:(t=this.media)==null?void 0:t.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(t,e={}){Dt(e,this.createData());const i=e.ot===te.INIT||e.ot===te.VIDEO||e.ot===te.MUXED;if(this.starved&&i&&(e.bs=!0,e.su=!0,this.starved=!1),e.su==null&&(e.su=this.buffering),this.useHeaders){const s=Ye.toHeaders(e);if(!Object.keys(s).length)return;t.headers||(t.headers={}),Dt(t.headers,s)}else{const s=Ye.toQuery(e);if(!s)return;t.url=Ye.appendQueryToUri(t.url,s)}}getObjectType(t){const{type:e}=t;if(e==="subtitle")return te.TIMED_TEXT;if(t.sn==="initSegment")return te.INIT;if(e==="audio")return te.AUDIO;if(e==="main")return this.hls.audioTracks.length?te.VIDEO:te.MUXED}getTopBandwidth(t){let e=0,i;const s=this.hls;if(t===te.AUDIO)i=s.audioTracks;else{const n=s.maxAutoLevel,a=n>-1?n+1:s.levels.length;i=s.levels.slice(0,a)}for(const n of i)n.bitrate>e&&(e=n.bitrate);return e>0?e:NaN}getBufferLength(t){const e=this.hls.media,i=t===te.AUDIO?this.audioBuffer:this.videoBuffer;return!i||!e?NaN:Et.bufferInfo(i,e.currentTime,this.config.maxBufferHole).len*1e3}createPlaylistLoader(){const{pLoader:t}=this.config,e=this.applyPlaylistData,i=t||this.config.loader;return class{constructor(s){this.loader=void 0,this.loader=new i(s)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(s,n,a){e(s),this.loader.load(s,n,a)}}}createFragmentLoader(){const{fLoader:t}=this.config,e=this.applyFragmentData,i=t||this.config.loader;return class{constructor(s){this.loader=void 0,this.loader=new i(s)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(s,n,a){e(s),this.loader.load(s,n,a)}}}static uuid(){const t=URL.createObjectURL(new Blob),e=t.toString();return URL.revokeObjectURL(t),e.slice(e.lastIndexOf("/")+1)}static serialize(t){const e=[],i=l=>!Number.isNaN(l)&&l!=null&&l!==""&&l!==!1,s=l=>Math.round(l),n=l=>s(l/100)*100,a={br:s,d:s,bl:n,dl:n,mtp:n,nor:l=>encodeURIComponent(l),rtp:n,tb:s},o=Object.keys(t||{}).sort();for(const l of o){let h=t[l];if(!i(h)||l==="v"&&h===1||l=="pr"&&h===1)continue;const c=a[l];c&&(h=c(h));const d=typeof h;let u;l==="ot"||l==="sf"||l==="st"?u=`${l}=${h}`:d==="boolean"?u=l:d==="number"?u=`${l}=${h}`:u=`${l}=${JSON.stringify(h)}`,e.push(u)}return e.join(",")}static toHeaders(t){const e=Object.keys(t),i={},s=["Object","Request","Session","Status"],n=[{},{},{},{}],a={br:0,d:0,ot:0,tb:0,bl:1,dl:1,mtp:1,nor:1,nrr:1,su:1,cid:2,pr:2,sf:2,sid:2,st:2,v:2,bs:3,rtp:3};for(const o of e){const l=a[o]!=null?a[o]:1;n[l][o]=t[o]}for(let o=0;o<n.length;o++){const l=Ye.serialize(n[o]);l&&(i[`CMCD-${s[o]}`]=l)}return i}static toQuery(t){return`CMCD=${encodeURIComponent(Ye.serialize(t))}`}static appendQueryToUri(t,e){if(!e)return t;const i=t.includes("?")?"&":"?";return`${t}${i}${e}`}}const hv=3e5;class cv{constructor(t){this.hls=void 0,this.log=void 0,this.loader=null,this.uri=null,this.pathwayId=".",this.pathwayPriority=null,this.timeToLoad=300,this.reloadTimer=-1,this.updated=0,this.started=!1,this.enabled=!0,this.levels=null,this.audioTracks=null,this.subtitleTracks=null,this.penalizedPathways={},this.hls=t,this.log=_.log.bind(_,"[content-steering]:"),this.registerListeners()}registerListeners(){const t=this.hls;t.on(m.MANIFEST_LOADING,this.onManifestLoading,this),t.on(m.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(m.MANIFEST_PARSED,this.onManifestParsed,this),t.on(m.ERROR,this.onError,this)}unregisterListeners(){const t=this.hls;t&&(t.off(m.MANIFEST_LOADING,this.onManifestLoading,this),t.off(m.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(m.MANIFEST_PARSED,this.onManifestParsed,this),t.off(m.ERROR,this.onError,this))}startLoad(){if(this.started=!0,self.clearTimeout(this.reloadTimer),this.enabled&&this.uri)if(this.updated){const t=Math.max(this.timeToLoad*1e3-(performance.now()-this.updated),0);this.scheduleRefresh(this.uri,t)}else this.loadSteeringManifest(this.uri)}stopLoad(){this.started=!1,this.loader&&(this.loader.destroy(),this.loader=null),self.clearTimeout(this.reloadTimer)}destroy(){this.unregisterListeners(),this.stopLoad(),this.hls=null,this.levels=this.audioTracks=this.subtitleTracks=null}removeLevel(t){const e=this.levels;e&&(this.levels=e.filter(i=>i!==t))}onManifestLoading(){this.stopLoad(),this.enabled=!0,this.timeToLoad=300,this.updated=0,this.uri=null,this.pathwayId=".",this.levels=this.audioTracks=this.subtitleTracks=null}onManifestLoaded(t,e){const{contentSteering:i}=e;i!==null&&(this.pathwayId=i.pathwayId,this.uri=i.uri,this.started&&this.startLoad())}onManifestParsed(t,e){this.audioTracks=e.audioTracks,this.subtitleTracks=e.subtitleTracks}onError(t,e){const{errorAction:i}=e;if((i==null?void 0:i.action)===Gt.SendAlternateToPenaltyBox&&i.flags===de.MoveAllAlternatesMatchingHost){let s=this.pathwayPriority;const n=this.pathwayId;this.penalizedPathways[n]||(this.penalizedPathways[n]=performance.now()),!s&&this.levels&&(s=this.levels.reduce((a,o)=>(a.indexOf(o.pathwayId)===-1&&a.push(o.pathwayId),a),[])),s&&s.length>1&&(this.updatePathwayPriority(s),i.resolved=this.pathwayId!==n)}}filterParsedLevels(t){this.levels=t;let e=this.getLevelsForPathway(this.pathwayId);if(e.length===0){const i=t[0].pathwayId;this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${i}"`),e=this.getLevelsForPathway(i),this.pathwayId=i}return e.length!==t.length?(this.log(`Found ${e.length}/${t.length} levels in Pathway "${this.pathwayId}"`),e):t}getLevelsForPathway(t){return this.levels===null?[]:this.levels.filter(e=>t===e.pathwayId)}updatePathwayPriority(t){this.pathwayPriority=t;let e;const i=this.penalizedPathways,s=performance.now();Object.keys(i).forEach(n=>{s-i[n]>hv&&delete i[n]});for(let n=0;n<t.length;n++){const a=t[n];if(i[a])continue;if(a===this.pathwayId)return;const o=this.hls.nextLoadLevel,l=this.hls.levels[o];if(e=this.getLevelsForPathway(a),e.length>0){this.log(`Setting Pathway to "${a}"`),this.pathwayId=a,this.hls.trigger(m.LEVELS_UPDATED,{levels:e});const h=this.hls.levels[o];l&&h&&this.levels&&(h.attrs["STABLE-VARIANT-ID"]!==l.attrs["STABLE-VARIANT-ID"]&&h.bitrate!==l.bitrate&&this.log(`Unstable Pathways change from bitrate ${l.bitrate} to ${h.bitrate}`),this.hls.nextLoadLevel=o);break}}}clonePathways(t){const e=this.levels;if(!e)return;const i={},s={};t.forEach(n=>{const{ID:a,"BASE-ID":o,"URI-REPLACEMENT":l}=n;if(e.some(c=>c.pathwayId===a))return;const h=this.getLevelsForPathway(o).map(c=>{const d=Dt({},c);d.details=void 0,d.url=uc(c.uri,c.attrs["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",l);const u=new St(c.attrs);u["PATHWAY-ID"]=a;const f=u.AUDIO&&`${u.AUDIO}_clone_${a}`,p=u.SUBTITLES&&`${u.SUBTITLES}_clone_${a}`;f&&(i[u.AUDIO]=f,u.AUDIO=f),p&&(s[u.SUBTITLES]=p,u.SUBTITLES=p),d.attrs=u;const g=new Ts(d);return ur(g,"audio",f),ur(g,"text",p),g});e.push(...h),dc(this.audioTracks,i,l,a),dc(this.subtitleTracks,s,l,a)})}loadSteeringManifest(t){const e=this.hls.config,i=e.loader;this.loader&&this.loader.destroy(),this.loader=new i(e);let s;try{s=new self.URL(t)}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest URI: ${t}`);return}if(s.protocol!=="data:"){const c=(this.hls.bandwidthEstimate||e.abrEwmaDefaultEstimate)|0;s.searchParams.set("_HLS_pathway",this.pathwayId),s.searchParams.set("_HLS_throughput",""+c)}const n={responseType:"json",url:s.href},a=e.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},h={onSuccess:(c,d,u,f)=>{this.log(`Loaded steering manifest: "${s}"`);const p=c.data;if(p.VERSION!==1){this.log(`Steering VERSION ${p.VERSION} not supported!`);return}this.updated=performance.now(),this.timeToLoad=p.TTL;const{"RELOAD-URI":g,"PATHWAY-CLONES":v,"PATHWAY-PRIORITY":E}=p;if(g)try{this.uri=new self.URL(g,s).href}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest RELOAD-URI: ${g}`);return}this.scheduleRefresh(this.uri||u.url),v&&this.clonePathways(v),E&&this.updatePathwayPriority(E)},onError:(c,d,u,f)=>{if(this.log(`Error loading steering manifest: ${c.code} ${c.text} (${d.url})`),this.stopLoad(),c.code===410){this.enabled=!1,this.log(`Steering manifest ${d.url} no longer available`);return}let p=this.timeToLoad*1e3;if(c.code===429){const g=this.loader;if(typeof(g==null?void 0:g.getResponseHeader)=="function"){const v=g.getResponseHeader("Retry-After");v&&(p=parseFloat(v)*1e3)}this.log(`Steering manifest ${d.url} rate limited`);return}this.scheduleRefresh(this.uri||d.url,p)},onTimeout:(c,d,u)=>{this.log(`Timeout loading steering manifest (${d.url})`),this.scheduleRefresh(this.uri||d.url)}};this.log(`Requesting steering manifest: ${s}`),this.loader.load(n,l,h)}scheduleRefresh(t,e=this.timeToLoad*1e3){self.clearTimeout(this.reloadTimer),this.reloadTimer=self.setTimeout(()=>{this.loadSteeringManifest(t)},e)}}function dc(r,t,e,i){r&&Object.keys(t).forEach(s=>{const n=r.filter(a=>a.groupId===s).map(a=>{const o=Dt({},a);return o.details=void 0,o.attrs=new St(o.attrs),o.url=o.attrs.URI=uc(a.url,a.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",e),o.groupId=o.attrs["GROUP-ID"]=t[s],o.attrs["PATHWAY-ID"]=i,o});r.push(...n)})}function uc(r,t,e,i){const{HOST:s,PARAMS:n,[e]:a}=i;let o;t&&(o=a==null?void 0:a[t],o&&(r=o));const l=new self.URL(r);return s&&!o&&(l.host=s),n&&Object.keys(n).sort().forEach(h=>{h&&l.searchParams.set(h,n[h])}),l.href}const dv=/^age:\s*[\d.]+\s*$/im;class fc{constructor(t){this.xhrSetup=void 0,this.requestTimeout=void 0,this.retryTimeout=void 0,this.retryDelay=void 0,this.config=null,this.callbacks=null,this.context=void 0,this.loader=null,this.stats=void 0,this.xhrSetup=t&&t.xhrSetup||null,this.stats=new sr,this.retryDelay=0}destroy(){this.callbacks=null,this.abortInternal(),this.loader=null,this.config=null}abortInternal(){const t=this.loader;self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),t&&(t.onreadystatechange=null,t.onprogress=null,t.readyState!==4&&(this.stats.aborted=!0,t.abort()))}abort(){var t;this.abortInternal(),(t=this.callbacks)!=null&&t.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.loader)}load(t,e,i){if(this.stats.loading.start)throw new Error("Loader can only be used once.");this.stats.loading.start=self.performance.now(),this.context=t,this.config=e,this.callbacks=i,this.loadInternal()}loadInternal(){const{config:t,context:e}=this;if(!t)return;const i=this.loader=new self.XMLHttpRequest,s=this.stats;s.loading.first=0,s.loaded=0,s.aborted=!1;const n=this.xhrSetup;n?Promise.resolve().then(()=>{if(!this.stats.aborted)return n(i,e.url)}).catch(a=>(i.open("GET",e.url,!0),n(i,e.url))).then(()=>{this.stats.aborted||this.openAndSendXhr(i,e,t)}).catch(a=>{this.callbacks.onError({code:i.status,text:a.message},e,i,s)}):this.openAndSendXhr(i,e,t)}openAndSendXhr(t,e,i){t.readyState||t.open("GET",e.url,!0);const s=this.context.headers,{maxTimeToFirstByteMs:n,maxLoadTimeMs:a}=i.loadPolicy;if(s)for(const o in s)t.setRequestHeader(o,s[o]);e.rangeEnd&&t.setRequestHeader("Range","bytes="+e.rangeStart+"-"+(e.rangeEnd-1)),t.onreadystatechange=this.readystatechange.bind(this),t.onprogress=this.loadprogress.bind(this),t.responseType=e.responseType,self.clearTimeout(this.requestTimeout),i.timeout=n&&q(n)?n:a,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),i.timeout),t.send()}readystatechange(){const{context:t,loader:e,stats:i}=this;if(!t||!e)return;const s=e.readyState,n=this.config;if(!i.aborted&&s>=2&&(i.loading.first===0&&(i.loading.first=Math.max(self.performance.now(),i.loading.start),n.timeout!==n.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),n.timeout=n.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),n.loadPolicy.maxLoadTimeMs-(i.loading.first-i.loading.start)))),s===4)){self.clearTimeout(this.requestTimeout),e.onreadystatechange=null,e.onprogress=null;const a=e.status,o=e.responseType!=="text";if(a>=200&&a<300&&(o&&e.response||e.responseText!==null)){i.loading.end=Math.max(self.performance.now(),i.loading.first);const l=o?e.response:e.responseText,h=e.responseType==="arraybuffer"?l.byteLength:l.length;if(i.loaded=i.total=h,i.bwEstimate=i.total*8e3/(i.loading.end-i.loading.first),!this.callbacks)return;const c=this.callbacks.onProgress;if(c&&c(i,t,l,e),!this.callbacks)return;const d={url:e.responseURL,data:l,code:a};this.callbacks.onSuccess(d,i,t,e)}else{const l=n.loadPolicy.errorRetry,h=i.retry;dr(l,h,!1,a)?this.retry(l):(_.error(`${a} while loading ${t.url}`),this.callbacks.onError({code:a,text:e.statusText},t,e,i))}}}loadtimeout(){var t;const e=(t=this.config)==null?void 0:t.loadPolicy.timeoutRetry,i=this.stats.retry;if(dr(e,i,!0))this.retry(e);else{_.warn(`timeout while loading ${this.context.url}`);const s=this.callbacks;s&&(this.abortInternal(),s.onTimeout(this.stats,this.context,this.loader))}}retry(t){const{context:e,stats:i}=this;this.retryDelay=Un(t,i.retry),i.retry++,_.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${e.url}, retrying ${i.retry}/${t.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(t){const e=this.stats;e.loaded=t.loaded,t.lengthComputable&&(e.total=t.total)}getCacheAge(){let t=null;if(this.loader&&dv.test(this.loader.getAllResponseHeaders())){const e=this.loader.getResponseHeader("age");t=e?parseFloat(e):null}return t}getResponseHeader(t){return this.loader&&new RegExp(`^${t}:\\s*[\\d.]+\\s*$`,"im").test(this.loader.getAllResponseHeaders())?this.loader.getResponseHeader(t):null}}function uv(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch{}return!1}const fv=/(\d+)-(\d+)\/(\d+)/;class pc{constructor(t){this.fetchSetup=void 0,this.requestTimeout=void 0,this.request=void 0,this.response=void 0,this.controller=void 0,this.context=void 0,this.config=null,this.callbacks=null,this.stats=void 0,this.loader=null,this.fetchSetup=t.fetchSetup||vv,this.controller=new self.AbortController,this.stats=new sr}destroy(){this.loader=this.callbacks=null,this.abortInternal()}abortInternal(){const t=this.response;t!=null&&t.ok||(this.stats.aborted=!0,this.controller.abort())}abort(){var t;this.abortInternal(),(t=this.callbacks)!=null&&t.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.response)}load(t,e,i){const s=this.stats;if(s.loading.start)throw new Error("Loader can only be used once.");s.loading.start=self.performance.now();const n=pv(t,this.controller.signal),a=i.onProgress,o=t.responseType==="arraybuffer",l=o?"byteLength":"length",{maxTimeToFirstByteMs:h,maxLoadTimeMs:c}=e.loadPolicy;this.context=t,this.config=e,this.callbacks=i,this.request=this.fetchSetup(t,n),self.clearTimeout(this.requestTimeout),e.timeout=h&&q(h)?h:c,this.requestTimeout=self.setTimeout(()=>{this.abortInternal(),i.onTimeout(s,t,this.response)},e.timeout),self.fetch(this.request).then(d=>{this.response=this.loader=d;const u=Math.max(self.performance.now(),s.loading.start);if(self.clearTimeout(this.requestTimeout),e.timeout=c,this.requestTimeout=self.setTimeout(()=>{this.abortInternal(),i.onTimeout(s,t,this.response)},c-(u-s.loading.start)),!d.ok){const{status:f,statusText:p}=d;throw new yv(p||"fetch, bad network response",f,d)}return s.loading.first=u,s.total=mv(d.headers)||s.total,a&&q(e.highWaterMark)?this.loadProgressively(d,s,t,e.highWaterMark,a):o?d.arrayBuffer():t.responseType==="json"?d.json():d.text()}).then(d=>{const{response:u}=this;self.clearTimeout(this.requestTimeout),s.loading.end=Math.max(self.performance.now(),s.loading.first);const f=d[l];f&&(s.loaded=s.total=f);const p={url:u.url,data:d,code:u.status};a&&!q(e.highWaterMark)&&a(s,t,d,u),i.onSuccess(p,s,t,u)}).catch(d=>{if(self.clearTimeout(this.requestTimeout),s.aborted)return;const u=d&&d.code||0,f=d?d.message:null;i.onError({code:u,text:f},t,d?d.details:null,s)})}getCacheAge(){let t=null;if(this.response){const e=this.response.headers.get("age");t=e?parseFloat(e):null}return t}getResponseHeader(t){return this.response?this.response.headers.get(t):null}loadProgressively(t,e,i,s=0,n){const a=new Gh,o=t.body.getReader(),l=()=>o.read().then(h=>{if(h.done)return a.dataLength&&n(e,i,a.flush(),t),Promise.resolve(new ArrayBuffer(0));const c=h.value,d=c.length;return e.loaded+=d,d<s||a.dataLength?(a.push(c),a.dataLength>=s&&n(e,i,a.flush(),t)):n(e,i,c,t),l()}).catch(()=>Promise.reject());return l()}}function pv(r,t){const e={method:"GET",mode:"cors",credentials:"same-origin",signal:t,headers:new self.Headers(Dt({},r.headers))};return r.rangeEnd&&e.headers.set("Range","bytes="+r.rangeStart+"-"+String(r.rangeEnd-1)),e}function gv(r){const t=fv.exec(r);if(t)return parseInt(t[2])-parseInt(t[1])+1}function mv(r){const t=r.get("Content-Range");if(t){const i=gv(t);if(q(i))return i}const e=r.get("Content-Length");if(e)return parseInt(e)}function vv(r,t){return new self.Request(r.url,t)}class yv extends Error{constructor(t,e,i){super(t),this.code=void 0,this.details=void 0,this.code=e,this.details=i}}const Ev=/\s/,bv={newCue(r,t,e,i){const s=[];let n,a,o,l,h;const c=self.VTTCue||self.TextTrackCue;for(let u=0;u<i.rows.length;u++)if(n=i.rows[u],o=!0,l=0,h="",!n.isEmpty()){var d;for(let g=0;g<n.chars.length;g++)Ev.test(n.chars[g].uchar)&&o?l++:(h+=n.chars[g].uchar,o=!1);n.cueStartTime=t,t===e&&(e+=1e-4),l>=16?l--:l++;const f=sc(h.trim()),p=ca(t,e,f);r!=null&&(d=r.cues)!=null&&d.getCueById(p)||(a=new c(t,e,f),a.id=p,a.line=u+1,a.align="left",a.position=10+Math.min(80,Math.floor(l*8/32)*10),s.push(a))}return r&&s.length&&(s.sort((u,f)=>u.line==="auto"||f.line==="auto"?0:u.line>8&&f.line>8?f.line-u.line:u.line-f.line),s.forEach(u=>nh(r,u))),s}},Tv={maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null},Av=Qt(Qt({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,maxBufferSize:60*1e3*1e3,maxBufferHole:.1,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,maxFragLookUpTolerance:.25,liveSyncDurationCount:3,liveMaxLatencyDurationCount:1/0,liveSyncDuration:void 0,liveMaxLatencyDuration:void 0,maxLiveSyncPlaybackRate:1,liveDurationInfinity:!1,liveBackBufferLength:null,maxMaxBufferLength:600,enableWorker:!0,workerPath:null,enableSoftwareAES:!0,startLevel:void 0,startFragPrefetch:!1,fpsDroppedMonitoringPeriod:5e3,fpsDroppedMonitoringThreshold:.2,appendErrorMaxRetry:3,loader:fc,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:Rm,bufferController:$m,capLevelController:ga,errorController:yg,fpsController:av,stretchShortVideoTrack:!1,maxAudioFramesDrift:1,forceKeyFrameOnDiscontinuity:!0,abrEwmaFastLive:3,abrEwmaSlowLive:9,abrEwmaFastVoD:3,abrEwmaSlowVoD:9,abrEwmaDefaultEstimate:5e5,abrBandWidthFactor:.95,abrBandWidthUpFactor:.7,abrMaxWithRealBitrate:!1,maxStarvationDelay:4,maxLoadingDelay:4,minAutoBitrate:0,emeEnabled:!1,widevineLicenseUrl:void 0,drmSystems:{},drmSystemOptions:{},requestMediaKeySystemAccessFunc:xl,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableID3MetadataCues:!0,certLoadPolicy:{default:Tv},keyLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"},errorRetry:{maxNumRetry:8,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"}}},manifestLoadPolicy:{default:{maxTimeToFirstByteMs:1/0,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},playlistLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:2,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},fragLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:12e4,timeoutRetry:{maxNumRetry:4,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:6,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},steeringManifestLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},manifestLoadingTimeOut:1e4,manifestLoadingMaxRetry:1,manifestLoadingRetryDelay:1e3,manifestLoadingMaxRetryTimeout:64e3,levelLoadingTimeOut:1e4,levelLoadingMaxRetry:4,levelLoadingRetryDelay:1e3,levelLoadingMaxRetryTimeout:64e3,fragLoadingTimeOut:2e4,fragLoadingMaxRetry:6,fragLoadingRetryDelay:1e3,fragLoadingMaxRetryTimeout:64e3},wv()),{},{subtitleStreamController:Dm,subtitleTrackController:Pm,timelineController:sv,audioStreamController:km,audioTrackController:Im,emeController:Pi,cmcdController:Ye,contentSteeringController:cv});function wv(){return{cueHandler:bv,enableWebVTT:!0,enableIMSC1:!0,enableCEA708Captions:!0,captionsTextTrack1Label:"English",captionsTextTrack1LanguageCode:"en",captionsTextTrack2Label:"Spanish",captionsTextTrack2LanguageCode:"es",captionsTextTrack3Label:"Unknown CC",captionsTextTrack3LanguageCode:"",captionsTextTrack4Label:"Unknown CC",captionsTextTrack4LanguageCode:"",renderTextTracksNatively:!0}}function Sv(r,t){if((t.liveSyncDurationCount||t.liveMaxLatencyDurationCount)&&(t.liveSyncDuration||t.liveMaxLatencyDuration))throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");if(t.liveMaxLatencyDurationCount!==void 0&&(t.liveSyncDurationCount===void 0||t.liveMaxLatencyDurationCount<=t.liveSyncDurationCount))throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(t.liveMaxLatencyDuration!==void 0&&(t.liveSyncDuration===void 0||t.liveMaxLatencyDuration<=t.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');const e=ma(r),i=["manifest","level","frag"],s=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return i.forEach(n=>{const a=`${n==="level"?"playlist":n}LoadPolicy`,o=t[a]===void 0,l=[];s.forEach(h=>{const c=`${n}Loading${h}`,d=t[c];if(d!==void 0&&o){l.push(c);const u=e[a].default;switch(t[a]={default:u},h){case"TimeOut":u.maxLoadTimeMs=d,u.maxTimeToFirstByteMs=d;break;case"MaxRetry":u.errorRetry.maxNumRetry=d,u.timeoutRetry.maxNumRetry=d;break;case"RetryDelay":u.errorRetry.retryDelayMs=d,u.timeoutRetry.retryDelayMs=d;break;case"MaxRetryTimeout":u.errorRetry.maxRetryDelayMs=d,u.timeoutRetry.maxRetryDelayMs=d;break}}}),l.length&&_.warn(`hls.js config: "${l.join('", "')}" setting(s) are deprecated, use "${a}": ${JSON.stringify(t[a])}`)}),Qt(Qt({},e),t)}function ma(r){return r&&typeof r=="object"?Array.isArray(r)?r.map(ma):Object.keys(r).reduce((t,e)=>(t[e]=ma(r[e]),t),{}):r}function Lv(r){const t=r.loader;t!==pc&&t!==fc?(_.log("[config]: Custom loader detected, cannot enable progressive streaming"),r.progressive=!1):uv()&&(r.loader=pc,r.progressive=!0,r.enableSoftwareAES=!0,_.log("[config]: Progressive streaming enabled, using FetchLoader"))}class Ne{static get version(){return"1.4.12"}static isSupported(){return Fg()}static get Events(){return m}static get ErrorTypes(){return Q}static get ErrorDetails(){return $}static get DefaultConfig(){return Ne.defaultConfig?Ne.defaultConfig:Av}static set DefaultConfig(t){Ne.defaultConfig=t}constructor(t={}){this.config=void 0,this.userConfig=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this._emitter=new ea,this._autoLevelCapping=void 0,this._maxHdcpLevel=null,this.abrController=void 0,this.bufferController=void 0,this.capLevelController=void 0,this.latencyController=void 0,this.levelController=void 0,this.streamController=void 0,this.audioTrackController=void 0,this.subtitleTrackController=void 0,this.emeController=void 0,this.cmcdController=void 0,this._media=null,this.url=null,hp(t.debug||!1,"Hls instance");const e=this.config=Sv(Ne.DefaultConfig,t);this.userConfig=t,this._autoLevelCapping=-1,e.progressive&&Lv(e);const{abrController:i,bufferController:s,capLevelController:n,errorController:a,fpsController:o}=e,l=new a(this),h=this.abrController=new i(this),c=this.bufferController=new s(this),d=this.capLevelController=new n(this),u=new o(this),f=new Jp(this),p=new rg(this),g=e.contentSteeringController,v=g?new g(this):null,E=this.levelController=new bg(this,v),A=new Tg(this),L=new wg(this.config),y=this.streamController=new Sm(this,A,L);d.setStreamController(y),u.setStreamController(y);const S=[f,E,y];v&&S.splice(1,0,v),this.networkControllers=S;const R=[h,c,d,u,p,A];this.audioTrackController=this.createController(e.audioTrackController,S);const C=e.audioStreamController;C&&S.push(new C(this,A,L)),this.subtitleTrackController=this.createController(e.subtitleTrackController,S);const M=e.subtitleStreamController;M&&S.push(new M(this,A,L)),this.createController(e.timelineController,R),L.emeController=this.emeController=this.createController(e.emeController,R),this.cmcdController=this.createController(e.cmcdController,R),this.latencyController=this.createController(ng,R),this.coreComponents=R,S.push(l);const D=l.onErrorOut;typeof D=="function"&&this.on(m.ERROR,D,l)}createController(t,e){if(t){const i=new t(this);return e&&e.push(i),i}return null}on(t,e,i=this){this._emitter.on(t,e,i)}once(t,e,i=this){this._emitter.once(t,e,i)}removeAllListeners(t){this._emitter.removeAllListeners(t)}off(t,e,i=this,s){this._emitter.off(t,e,i,s)}listeners(t){return this._emitter.listeners(t)}emit(t,e,i){return this._emitter.emit(t,e,i)}trigger(t,e){if(this.config.debug)return this.emit(t,t,e);try{return this.emit(t,t,e)}catch(i){_.error("An internal error happened while handling event "+t+'. Error message: "'+i.message+'". Here is a stacktrace:',i),this.trigger(m.ERROR,{type:Q.OTHER_ERROR,details:$.INTERNAL_EXCEPTION,fatal:!1,event:t,error:i})}return!1}listenerCount(t){return this._emitter.listenerCount(t)}destroy(){_.log("destroy"),this.trigger(m.DESTROYING,void 0),this.detachMedia(),this.removeAllListeners(),this._autoLevelCapping=-1,this.url=null,this.networkControllers.forEach(e=>e.destroy()),this.networkControllers.length=0,this.coreComponents.forEach(e=>e.destroy()),this.coreComponents.length=0;const t=this.config;t.xhrSetup=t.fetchSetup=void 0,this.userConfig=null}attachMedia(t){_.log("attachMedia"),this._media=t,this.trigger(m.MEDIA_ATTACHING,{media:t})}detachMedia(){_.log("detachMedia"),this.trigger(m.MEDIA_DETACHING,void 0),this._media=null}loadSource(t){this.stopLoad();const e=this.media,i=this.url,s=this.url=An.buildAbsoluteURL(self.location.href,t,{alwaysNormalize:!0});_.log(`loadSource:${s}`),e&&i&&(i!==s||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(e)),this.trigger(m.MANIFEST_LOADING,{url:t})}startLoad(t=-1){_.log(`startLoad(${t})`),this.networkControllers.forEach(e=>{e.startLoad(t)})}stopLoad(){_.log("stopLoad"),this.networkControllers.forEach(t=>{t.stopLoad()})}swapAudioCodec(){_.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){_.log("recoverMediaError");const t=this._media;this.detachMedia(),t&&this.attachMedia(t)}removeLevel(t,e=0){this.levelController.removeLevel(t,e)}get levels(){return this.levelController.levels||[]}get currentLevel(){return this.streamController.currentLevel}set currentLevel(t){_.log(`set currentLevel:${t}`),this.loadLevel=t,this.abrController.clearTimer(),this.streamController.immediateLevelSwitch()}get nextLevel(){return this.streamController.nextLevel}set nextLevel(t){_.log(`set nextLevel:${t}`),this.levelController.manualLevel=t,this.streamController.nextLevelSwitch()}get loadLevel(){return this.levelController.level}set loadLevel(t){_.log(`set loadLevel:${t}`),this.levelController.manualLevel=t}get nextLoadLevel(){return this.levelController.nextLoadLevel}set nextLoadLevel(t){this.levelController.nextLoadLevel=t}get firstLevel(){return Math.max(this.levelController.firstLevel,this.minAutoLevel)}set firstLevel(t){_.log(`set firstLevel:${t}`),this.levelController.firstLevel=t}get startLevel(){return this.levelController.startLevel}set startLevel(t){_.log(`set startLevel:${t}`),t!==-1&&(t=Math.max(t,this.minAutoLevel)),this.levelController.startLevel=t}get capLevelToPlayerSize(){return this.config.capLevelToPlayerSize}set capLevelToPlayerSize(t){const e=!!t;e!==this.config.capLevelToPlayerSize&&(e?this.capLevelController.startCapping():(this.capLevelController.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=e)}get autoLevelCapping(){return this._autoLevelCapping}get bandwidthEstimate(){const{bwEstimator:t}=this.abrController;return t?t.getEstimate():NaN}get ttfbEstimate(){const{bwEstimator:t}=this.abrController;return t?t.getEstimateTTFB():NaN}set autoLevelCapping(t){this._autoLevelCapping!==t&&(_.log(`set autoLevelCapping:${t}`),this._autoLevelCapping=t)}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(t){Mn.indexOf(t)>-1&&(this._maxHdcpLevel=t)}get autoLevelEnabled(){return this.levelController.manualLevel===-1}get manualLevel(){return this.levelController.manualLevel}get minAutoLevel(){const{levels:t,config:{minAutoBitrate:e}}=this;if(!t)return 0;const i=t.length;for(let s=0;s<i;s++)if(t[s].maxBitrate>=e)return s;return 0}get maxAutoLevel(){const{levels:t,autoLevelCapping:e,maxHdcpLevel:i}=this;let s;if(e===-1&&t&&t.length?s=t.length-1:s=e,i)for(let n=s;n--;){const a=t[n].attrs["HDCP-LEVEL"];if(a&&a<=i)return n}return s}get nextAutoLevel(){return Math.min(Math.max(this.abrController.nextAutoLevel,this.minAutoLevel),this.maxAutoLevel)}set nextAutoLevel(t){this.abrController.nextAutoLevel=Math.max(this.minAutoLevel,t)}get playingDate(){return this.streamController.currentProgramDateTime}get mainForwardBufferInfo(){return this.streamController.getMainFwdBufferInfo()}get audioTracks(){const t=this.audioTrackController;return t?t.audioTracks:[]}get audioTrack(){const t=this.audioTrackController;return t?t.audioTrack:-1}set audioTrack(t){const e=this.audioTrackController;e&&(e.audioTrack=t)}get subtitleTracks(){const t=this.subtitleTrackController;return t?t.subtitleTracks:[]}get subtitleTrack(){const t=this.subtitleTrackController;return t?t.subtitleTrack:-1}get media(){return this._media}set subtitleTrack(t){const e=this.subtitleTrackController;e&&(e.subtitleTrack=t)}get subtitleDisplay(){const t=this.subtitleTrackController;return t?t.subtitleDisplay:!1}set subtitleDisplay(t){const e=this.subtitleTrackController;e&&(e.subtitleDisplay=t)}get lowLatencyMode(){return this.config.lowLatencyMode}set lowLatencyMode(t){this.config.lowLatencyMode=t}get liveSyncPosition(){return this.latencyController.liveSyncPosition}get latency(){return this.latencyController.latency}get maxLatency(){return this.latencyController.maxLatency}get targetLatency(){return this.latencyController.targetLatency}get drift(){return this.latencyController.drift}get forceStartLoad(){return this.streamController.forceStartLoad}}Ne.defaultConfig=void 0;function Rv(){return/^((?!chrome|android).)*safari/i.test(navigator.userAgent)}function _v(){return["iPad Simulator","iPhone Simulator","iPod Simulator","iPad","iPhone","iPod"].includes(navigator.platform)||navigator.userAgent.includes("Mac")&&"ontouchend"in document}const kv=os(async function(r){return new FontFace(r.name,`url(${r.url})`,{style:r.style,weight:r.weight}).load()},{cacheKey:([r])=>JSON.stringify(r)});async function Iv(r){return r.duration===1/0?new Promise(t=>{r.currentTime=Number.MAX_SAFE_INTEGER,r.ontimeupdate=()=>{r.ontimeupdate=null,t(r.duration),r.currentTime=0}}):r.duration}class Cv{constructor(t){this._memoKey=null,this._lastDeps=null,this._duration=0,this._processing=!1,this._scenes=null,this._videos={},this._videoMeta={},this._videoState={},this._resolveVideo=os(e=>{const{id:i,src:s,playlist:n,duration:a}=e;return this._cleanupVideo(i),new Promise(o=>{let l=null;const h=document.createElement("video");h.playsInline=!0,h.muted=!0,h.loop=!1,h.volume=this.host.volume,h.playbackRate=this.host.playbackRate;const c={loadeddata:this._handleLoadedData,waiting:this._handleWaiting,canplay:this._handleCanPlay,progress:this._handleProgress,seeked:this._handleSeeked,play:this._handlePlay,playing:this._handlePlaying,pause:this._handlePause,stalled:this._handleStalled,timeupdate:this._handleTimeUpdate,ended:this._handleEnded,error:this._handleError},d=Object.keys(c).reduce((u,f)=>{const p=f,g=c[p](i,h);return u[p]=g,h.addEventListener(f,g),u},{});if(n&&!Rv()&&Ne.isSupported()){let u=!1;l=new Ne({autoStartLoad:!0,xhrSetup:f=>{const{open:p}=f,g=n.split("?")[1];f.open=function(v,E,A){E.toString().includes("?")||(E+="?"+g),p.apply(this,[v,E,A])}}}),l.loadSource(n),l.attachMedia(h),l.startLoadOnce=(f=-1)=>{l&&!u&&(l.startLoad(f),u=!0)},l.on(Ne.Events.LEVEL_LOADED,async()=>{u||l==null||l.stopLoad(),o({id:i,hls:l,node:h})})}else{h.src=s;let u=!1;if(h.startLoadOnce=()=>{u||(h.preload="auto",h.load(),u=!0)},a)h.preload="none",o({id:i,hls:l,node:h});else{h.preload="metadata";const f=async()=>{o({id:i,hls:l,node:h}),h.removeEventListener("loadedmetadata",f)};h.addEventListener("loadedmetadata",f)}}this.videos[i]={id:i,hls:l,node:h,listeners:d},this.videoState[i]={initialised:!1,waiting:!0,buffered:[]}})},{cacheKey:([{id:e,src:i,playlist:s}])=>JSON.stringify({id:e,src:i.split("?")[0],playlist:s==null?void 0:s.split("?")[0]})}),this._resolveVideoMeta=os(async(e,i)=>{const{id:s,captions:n,duration:a,startOffset:o,endOffset:l}=e,h=a??await Iv(i),c=(o??0)*h,d=(1-(l??0))*h,u={id:s,captions:n,start:c,duration:d};return this.videoMeta[s]=u,u},{cacheKey:([{id:e,captions:i,duration:s,startOffset:n,endOffset:a}])=>JSON.stringify({id:e,captions:i,duration:s,startOffset:n,endOffset:a})}),this._handleLoadedData=(e,i)=>()=>{const s=this.videoState[e];s!=null&&s.initialised||(this.videoState={...this.videoState,[e]:{...s,initialised:!0,waiting:!1,buffered:(s==null?void 0:s.buffered)??[]}},this.setVideosCurrentTime(this.host.currentTime),this.host.dispatchEvent(new CustomEvent("video:loadeddata",{detail:{id:e,node:i}})))},this._handleWaiting=e=>()=>{const i=this.videoState[e];i!=null&&i.initialised&&!(i!=null&&i.waiting)&&(this.videoState={...this.videoState,[e]:{...i,waiting:!0}})},this._handleCanPlay=e=>()=>{const i=this.videoState[e];i!=null&&i.initialised&&i!=null&&i.waiting&&(this.videoState={...this.videoState,[e]:{...i,waiting:!1}})},this._handleProgress=(e,i)=>()=>{var s;const n=i==null?void 0:i.buffered,a=[],{start:o,video:l,videoMeta:h}=((s=this.scenes)==null?void 0:s.scenes.find(({video:c})=>e===(c==null?void 0:c.id)))??{};if(i&&n&&l&&h&&typeof o<"u"){for(let d=0;d<n.length;d++){const u=n.start(d),f=n.end(d);Math.max(u,h.start)<=Math.min(f,h.start+h.duration)&&a.push({start:Math.max(0,(Math.max(u-h.start,0)+o)/this.host.duration*100),end:Math.min((Math.min(f-h.start,h.duration)+o)/this.host.duration*100,100)})}const c=this.videoState[e];this.videoState={...this.videoState,[e]:{...c,buffered:a}}}},this._handleSeeked=(e,i)=>()=>{const s=this.videoState[e];s!=null&&s.initialised&&(this.host.draw(),this.host.dispatchEvent(new CustomEvent("video:seeked",{detail:{id:e,node:i}})))},this._handlePlay=(e,i)=>()=>{this.host.dispatchEvent(new CustomEvent("video:play",{detail:{id:e,node:i}}))},this._handlePlaying=(e,i)=>()=>{this.host.dispatchEvent(new CustomEvent("video:playing",{detail:{id:e,node:i}}))},this._handlePause=(e,i)=>()=>{this.host.dispatchEvent(new CustomEvent("video:pause",{detail:{id:e,node:i}}))},this._handleStalled=(e,i)=>()=>{this.host.dispatchEvent(new CustomEvent("video:stalled",{detail:{id:e,node:i}}))},this._handleTimeUpdate=(e,i)=>()=>{this.host.dispatchEvent(new CustomEvent("video:timeupdate",{detail:{id:e,node:i}}))},this._handleEnded=(e,i)=>()=>{this.host.dispatchEvent(new CustomEvent("video:ended",{detail:{id:e,node:i}}))},this._handleError=(e,i)=>()=>{this.host.dispatchEvent(new CustomEvent("video:error",{detail:{id:e,node:i}}))},this.host=t,this.host.addController(this)}set processing(t){t!==this._processing&&(this._processing=t,this.host.requestUpdate())}get processing(){return this._processing}set duration(t){!isNaN(t)&&t!==this._duration&&(this._duration=t,this.host.requestUpdate(),this.host.dispatchEvent(new CustomEvent("durationchange",{detail:this._duration})))}get duration(){return this._duration}set scenes(t){this._scenes=t,this.host.requestUpdate()}get scenes(){return this._scenes}set videos(t){this._videos=t,this.host.requestUpdate()}get videos(){return this._videos}set videoMeta(t){this._videoMeta=t,this.host.requestUpdate()}get videoMeta(){return this._videoMeta}set videoState(t){this._videoState=t,this.host.requestUpdate()}get videoState(){return this._videoState}_setupTask(){new So(this.host,async([t,e,i,s,n])=>{try{if(i||t){if(this.processing=!0,i){let a=null;if(s)try{a=await(await fetch(s,{method:"GET"})).text()}catch{this.host.dispatchEvent(new ErrorEvent("error",new Error("Track failed to fetch")))}const o=i.includes(".m3u8")?"playlist":"video";this.scenes=await $o({data:{questions:{items:[{answer:{id:"source",media:{[o]:i},captions:{current:a}}}]}},template:e,burnCaptions:n},this._resolveVideo,this._resolveVideoMeta)}else this.scenes=await $o({data:t,template:e,burnCaptions:n},this._resolveVideo,this._resolveVideoMeta);(await Promise.all(this.scenes.fonts.map(a=>kv(a)))).forEach(a=>{document.fonts.add(a)}),this.duration=this.scenes.duration,this.host.paused&&this.host.reset(this.host.currentTime,!this.host.paused),this.host.autoplay&&this.host.play()}}catch(a){this.scenes=null,this.duration=0,this.host.dispatchEvent(new ErrorEvent("error",a))}finally{this.processing=!1}},()=>{const t=JSON.stringify({data:this.host.data,template:this.host.template,src:this.host.src,track:this.host.track,burnCaptions:this.host.burnCaptions});if(this._lastDeps&&this._memoKey===t)return this._lastDeps;const e=[this.host.data,this.host.template,this.host.src,this.host.track,this.host.burnCaptions];return this._memoKey=t,this._lastDeps=e,e})}_setVideoCurrentTime({time:t,scene:e}){const{start:i,video:s,videoMeta:n}=e;if(s&&s.node&&n&&typeof i<"u"){const a=t-i;s.node.currentTime=Math.max(n.start,Math.min(n.start+n.duration,a+n.start))}}setVideosCurrentTime(t){var e;(e=this.scenes)==null||e.scenes.forEach(i=>{this._setVideoCurrentTime({time:t,scene:i})})}_cleanupVideo(t){var e;const i=this.videos[t];i&&((e=i.hls)==null||e.destroy(),i.node.pause(),i.node.src="",Object.keys(i.listeners).forEach(s=>{var n;if((n=this.videos)!=null&&n[t]){const a=i.listeners[s];i.node.removeEventListener(s,a)}}),delete this.videos[t])}hostConnected(){this._setupTask()}hostDisconnected(){Object.keys(this.videos).forEach(t=>{this._cleanupVideo(t)}),this.videos={}}}function Dv(r){r.requestFullscreen?r.requestFullscreen():r.mozRequestFullScreen?r.mozRequestFullScreen():r.webkitRequestFullscreen?r.webkitRequestFullscreen():r.msRequestFullscreen&&r.msRequestFullscreen()}function xv(){document.exitFullscreen?document.exitFullscreen():document.mozCancelFullScreen?document.mozCancelFullScreen():document.webkitExitFullscreen&&document.webkitExitFullscreen()}const va=["progress","play-large","navigation","play","volume","current-time","duration","speed","captions","fullscreen"],Pv={id:"captions",event:"captions:click",label:"Closed Captions"},Ov={id:"fullscreen",event:"fullscreen:click",label:"Full Screen"},gc={title:"Playback Speed",items:[{id:"playback-rate-0.5",event:"playbackRate:click",label:"0.5x",value:.5},{id:"playback-rate-1",event:"playbackRate:click",label:"1.0x",value:1},{id:"playback-rate-1.5",event:"playbackRate:click",label:"1.5x",value:1.5},{id:"playback-rate-2",event:"playbackRate:click",label:"2.0x",value:2}]},$v={id:"playbackRate",label:"Playback playbackRate",subItems:gc};class Mv extends yo{constructor(t){if(super(t),this.element=null,this.observer=void 0,t.type!==es.ELEMENT)throw new Error("Resize directive must be used in an Element expression")}disconnected(){var t;(t=this.observer)==null||t.disconnect(),this.observer=void 0}reconnected(){var t;this.element&&((t=this.observer)==null||t.observe(this.element))}update(t,[e]){return this.isConnected&&!this.observer&&(this.observer=new ResizeObserver(e),this.element=t.element,this.observer.observe(this.element)),Ge}}const ya=is(Mv),_e={"red-120":"#feeded","red-130":"#fcd5d0","red-400":"#e84a4a","red-500":"#c51c3a","red-700":"#a21c39","red-800":"#850231","red-900":"#580A2D","teal-100":"#a5e9ed","teal-600":"#006776","purple-100":"#d7cfff","purple-700":"#5f2fe9","green-200":"#a4d7aa","green-500":"#38b319","green-800":"#2b3c2f","grey-100":"#f0f0f0","light-50":"rgba(255, 255, 255, .05)","light-100":"rgba(255, 255, 255, .1)","light-200":"rgba(255, 255, 255, .2)","light-400":"rgba(255, 255, 255, .4)","light-500":"rgba(255, 255, 255, .5)","light-640":"rgba(255, 255, 255, .64)","light-800":"rgba(255, 255, 255, .8)","light-1000":"#fff","dark-50":"rgba(0, 0, 0, .05)","dark-80":"rgba(0, 0, 0, .08)","dark-100":"rgba(0, 0, 0, .1)","dark-200":"rgba(0, 0, 0, .2)","dark-250":"rgba(0, 0, 0, .25)","dark-400":"rgba(0, 0, 0, .4)","dark-500":"rgba(0, 0, 0, .5)","dark-640":"rgba(0, 0, 0, .64)","dark-800":"rgba(0, 0, 0, .8)","dark-900":"rgba(0, 0, 0, .9)","dark-1000":"#000"},Fv={colors:_e,space:{xxs:".25rem",xs:".5rem",small:".75rem",medium:"1rem",large:"1.5rem",xl:"2.5rem"},sizes:{xxs:"1rem",xs:"1.5rem",small:"2rem",medium:"2.5rem",large:"3rem"},fontWeights:{regular:400,semibold:600},lineHeights:{small:1.1,medium:1.25,large:1.4},letterSpacings:{xxs:"-.04rem",xs:"-.03rem",small:"-.02rem",medium:"-.01rem",large:0},fontSizes:{micro:".625rem",small:".75rem",medium:".875rem",large:"1rem",xl:"1.25rem",xxl:"1.5rem",xxxl:"2rem",huge:"2.75rem"},fontFamilies:{sans:'Roobert, "Times New Roman", -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial,"Noto Sans", sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji"',mono:'"Maison Neue Mono", Menlo, Monaco, Consolas, Liberation Mono, "Courier New", monospace'},borderWidths:{thin:".0625rem"},radii:{small:".25rem",medium:".5rem",large:".75rem",xl:"1rem"},shadows:{small:`.25rem .25rem .25rem ${_e["dark-100"]}`,medium:`0 .125rem .625rem ${_e["dark-100"]}`,large:`0 .25rem 1rem ${_e["dark-50"]}`,xl:`.25rem .25rem 1rem ${_e["dark-250"]}`,xxl:`0 .25rem 2rem ${_e["dark-100"]}`,xxxl:`.25rem .25rem 3rem ${_e["dark-250"]}`,toolbar:`0 -.625rem .625rem ${_e["dark-50"]}`,text:`0 0 .25rem ${_e["dark-250"]}`},timings:{fast:".1s",normal:".2s",slow:".3s"},easings:{linear:"linear"},focusOutline:{width:".2rem",color:_e["dark-400"]},iconSizes:{small:"0.75rem",medium:"1rem",large:"1.5rem"}},mc=Su.flatten(Fv,{delimiter:"-"}),Nv=Object.keys(mc).map(r=>Yi(`:host { --${r}: ${mc[r]}; }`)),Uv=r=>{class t extends r{firstUpdated(){const i=new FontFace("Roobert","url(https://media-player-fonts.s3.ap-southeast-2.amazonaws.com/Roobert-Regular.woff2)",{style:"normal",weight:"400"}),s=new FontFace("Roobert","url(https://media-player-fonts.s3.ap-southeast-2.amazonaws.com/Roobert-SemiBold.woff2)",{style:"normal",weight:"600"});document.fonts.add(i),document.fonts.add(s)}}return t.styles=[(r==null?void 0:r.styles)??[],Nv,jt`
186
174
  :host {
187
175
  font-family: var(--fontFamilies-sans);
188
176
  font-size: var(--fontSizes-medium);
189
177
  line-height: var(--lineHeights-medium);
190
178
  font-weight: var(--fontWeights-regular);
191
179
  }
192
- `,Ft`
180
+ `,jt`
193
181
  *,
194
182
  *::before,
195
183
  *::after,
@@ -263,12 +251,12 @@ ${t}`,r0=Object.getOwnPropertyDescriptor(Function.prototype,"toString"),n0=Objec
263
251
  scroll-behavior: auto !important;
264
252
  }
265
253
  }
266
- `],t},ot=b0(pi),A0=(r,t)=>(typeof window<"u"&&(window.customElements.get(r)??window.customElements.define(r,t)),t),w0=(r,t)=>{const{kind:e,elements:i}=t;return{kind:e,elements:i,finisher(s){typeof window<"u"&&(window.customElements.get(r)??window.customElements.define(r,s))}}},qt=r=>t=>typeof t=="function"?A0(r,t):w0(r,t);class S0 extends zs{constructor(t){if(super(t),t.type!==Qi.ELEMENT)throw new Error("Resize directive must be used in an Element expression")}update(t,[e]){return e==null||e(t.element),he}}const Bd=Zi(S0);class L0{constructor(t){this.hiddenControls=[],this._measureRef=de(),this._prevControlsWidth=0,this._hideables={},this._showables={},this._onResize=e=>{var i,s,n;const a=this._measureRef.value,o=(n=(s=(i=e==null?void 0:e[0])==null?void 0:i.borderBoxSize)==null?void 0:s[0])==null?void 0:n.inlineSize;if(a&&o&&o!==this._prevControlsWidth){Object.keys(this._hideables).forEach(h=>{this._hideables[h].element.style.display=""}),Object.keys(this._showables).forEach(h=>{this._showables[h].element.style.display="none"});const l=[];for(;a.scrollWidth>a.offsetWidth;){const h=Object.keys(this._hideables).find(d=>this._hideables[d].hideIndex===l.length);if(h){const d=this._hideables[h].element;d&&(d.style.display="none"),l.push(h)}Object.keys(this._showables).forEach(d=>{this._showables[d].showOn.some(c=>l.includes(c))&&(this._showables[d].element.style.display="flex")})}this.hiddenControls=l,this._prevControlsWidth=o,this.host.requestUpdate()}},this.host=t}measure(){return ce(this._measureRef)}contain(){return Da(this._onResize)}hide(t,e){return Bd(i=>{this._hideables[t]={element:i,hideIndex:e}})}show(t,e){return Bd(i=>{this._showables[t]={element:i,showOn:e}})}}function Hd(r,t={}){const e=Math.max(0,r||0),i=Math.floor(e/3600),s=Math.floor(e%3600/60),n=Math.floor(e%3600%60),a=Math.floor(e%1*1e3);let o=i?`${i}:${`${s}`.padStart(2,"0")}:${`${n}`.padStart(2,"0")}`:`${s}:${`${n}`.padStart(2,"0")}`;return t.includeMs&&(o+=`:${`${a}`.padStart(3,"0")}`),o}var R0=Object.defineProperty,_0=Object.getOwnPropertyDescriptor,_i=(r,t,e,i)=>{for(var s=i>1?void 0:i?_0(t,e):t,n=r.length-1,a;n>=0;n--)(a=r[n])&&(s=(i?a(t,e,s):a(s))||s);return i&&s&&R0(t,e,s),s};let Fe=class extends ot{constructor(){super(...arguments),this.active=!1,this.size="small",this.rounded="medium",this.weight="light"}render(){return J`<button
267
- class=${ht({active:this.active,"size-tiny":this.size==="tiny","size-small":this.size==="small","size-large":this.size==="large","radius-medium":this.rounded==="medium","radius-full":this.rounded==="full","weight-light":this.weight==="light","weight-heavy":this.weight==="heavy"})}
254
+ `],t},yt=Uv(Ti),Bv=(r,t)=>(typeof window<"u"&&(window.customElements.get(r)??window.customElements.define(r,t)),t),Hv=(r,t)=>{const{kind:e,elements:i}=t;return{kind:e,elements:i,finisher(s){typeof window<"u"&&(window.customElements.get(r)??window.customElements.define(r,s))}}},se=r=>t=>typeof t=="function"?Bv(r,t):Hv(r,t);class Gv extends Fs{constructor(t){if(super(t),t.type!==es.ELEMENT)throw new Error("Resize directive must be used in an Element expression")}update(t,[e]){return e==null||e(t.element),Ge}}const vc=is(Gv);class Vv{constructor(t){this.hiddenControls=[],this._measureRef=ae(),this._prevControlsWidth=0,this._hideables={},this._showables={},this._onResize=e=>{var i,s,n;const a=this._measureRef.value,o=(n=(s=(i=e==null?void 0:e[0])==null?void 0:i.borderBoxSize)==null?void 0:s[0])==null?void 0:n.inlineSize;if(a&&o&&o!==this._prevControlsWidth){Object.keys(this._hideables).forEach(h=>{this._hideables[h].element.style.display=""}),Object.keys(this._showables).forEach(h=>{this._showables[h].element.style.display="none"});const l=[];for(;a.scrollWidth>a.offsetWidth;){const h=Object.keys(this._hideables).find(c=>this._hideables[c].hideIndex===l.length);if(h){const c=this._hideables[h].element;c&&(c.style.display="none"),l.push(h)}Object.keys(this._showables).forEach(c=>{this._showables[c].showOn.some(d=>l.includes(d))&&(this._showables[c].element.style.display="flex")})}this.hiddenControls=l,this._prevControlsWidth=o,this.host.requestUpdate()}},this.host=t}measure(){return oe(this._measureRef)}contain(){return ya(this._onResize)}hide(t,e){return vc(i=>{this._hideables[t]={element:i,hideIndex:e}})}show(t,e){return vc(i=>{this._showables[t]={element:i,showOn:e}})}}function yc(r,t={}){const e=Math.max(0,r||0),i=Math.floor(e/3600),s=Math.floor(e%3600/60),n=Math.floor(e%3600%60),a=Math.floor(e%1*1e3);let o=i?`${i}:${`${s}`.padStart(2,"0")}:${`${n}`.padStart(2,"0")}`:`${s}:${`${n}`.padStart(2,"0")}`;return t.includeMs&&(o+=`:${`${a}`.padStart(3,"0")}`),o}var Kv=Object.defineProperty,jv=Object.getOwnPropertyDescriptor,Oi=(r,t,e,i)=>{for(var s=i>1?void 0:i?jv(t,e):t,n=r.length-1,a;n>=0;n--)(a=r[n])&&(s=(i?a(t,e,s):a(s))||s);return i&&s&&Kv(t,e,s),s};let ze=class extends yt{constructor(){super(...arguments),this.active=!1,this.size="small",this.rounded="medium",this.weight="light"}render(){return st`<button
255
+ class=${wt({active:this.active,"size-tiny":this.size==="tiny","size-small":this.size==="small","size-large":this.size==="large","radius-medium":this.rounded==="medium","radius-full":this.rounded==="full","weight-light":this.weight==="light","weight-heavy":this.weight==="heavy"})}
268
256
  >
269
257
  <slot></slot>
270
- ${this.icon&&J`<vmp-new-icon icon=${this.icon}></vmp-new-icon>`}
271
- </button>`}};Fe.styles=[ot.styles??[],Ft`
258
+ ${this.icon&&st`<vmp-new-icon icon=${this.icon}></vmp-new-icon>`}
259
+ </button>`}};ze.styles=[yt.styles??[],jt`
272
260
  :host {
273
261
  --button-color: var(--vu-button-color, var(--colors-dark-640));
274
262
  --button-background: var(--vu-button-background, var(--colors-light-1000));
@@ -344,37 +332,37 @@ ${t}`,r0=Object.getOwnPropertyDescriptor(Function.prototype,"toString"),n0=Objec
344
332
  .weight-light:focus {
345
333
  background: #9d9d9d;
346
334
  }
347
- `],_i([G({type:Boolean})],Fe.prototype,"active",2),_i([G({type:String})],Fe.prototype,"size",2),_i([G({type:String})],Fe.prototype,"rounded",2),_i([G({type:String})],Fe.prototype,"weight",2),_i([G({type:String})],Fe.prototype,"icon",2),Fe=_i([qt("vmp-new-button")],Fe);const Gd={"arrow-left":()=>J`<svg width="20" height="20" viewBox="0 0 20 20" fill="none" part="svg">
335
+ `],Oi([j({type:Boolean})],ze.prototype,"active",2),Oi([j({type:String})],ze.prototype,"size",2),Oi([j({type:String})],ze.prototype,"rounded",2),Oi([j({type:String})],ze.prototype,"weight",2),Oi([j({type:String})],ze.prototype,"icon",2),ze=Oi([se("vmp-new-button")],ze);const Ec={"arrow-left":()=>st`<svg width="20" height="20" viewBox="0 0 20 20" fill="none" part="svg">
348
336
  <path
349
337
  d="M16.6666 9.21875H6.52492L11.1833 4.85156L9.99992 3.75L3.33325 10L9.99992 16.25L11.1749 15.1484L6.52492 10.7812H16.6666V9.21875Z"
350
338
  fill="currentColor"
351
339
  />
352
- </svg>`,"arrow-right":()=>J`<svg width="20" height="20" viewBox="0 0 20 20" fill="none" part="svg">
340
+ </svg>`,"arrow-right":()=>st`<svg width="20" height="20" viewBox="0 0 20 20" fill="none" part="svg">
353
341
  <path
354
342
  d="M3.75 9.21875H13.2578L8.89062 4.85156L10 3.75L16.25 10L10 16.25L8.89844 15.1484L13.2578 10.7812H3.75V9.21875Z"
355
343
  fill="currentColor"
356
344
  />
357
- </svg>`,"captions-cross":()=>J`<svg width="20" height="20" viewBox="0 0 20 20" fill="none" part="svg">
345
+ </svg>`,"captions-cross":()=>st`<svg width="20" height="20" viewBox="0 0 20 20" fill="none" part="svg">
358
346
  <path
359
347
  d="M17.0625 19.4167L14.3125 16.6667H3.33333C2.875 16.6667 2.4825 16.5036 2.15583 16.1775C1.82972 15.8509 1.66667 15.4584 1.66667 15V4.16669C1.66667 4.13891 1.66667 4.11446 1.66667 4.09335C1.66667 4.0728 1.66667 4.04863 1.66667 4.02085L0.5625 2.91669L1.75 1.72919L18.25 18.2292L17.0625 19.4167ZM18.3333 15.9375L14.7083 12.3125C14.8056 12.2431 14.8786 12.1495 14.9275 12.0317C14.9758 11.9134 15 11.7917 15 11.6667V10.8334H13.75V11.25H13.6458L12.0833 9.68752V8.75002H13.75V9.16669H15V8.33335C15 8.09724 14.92 7.89919 14.76 7.73919C14.6006 7.57974 14.4028 7.50002 14.1667 7.50002H11.6667C11.4306 7.50002 11.2328 7.57974 11.0733 7.73919C10.9133 7.89919 10.8333 8.09724 10.8333 8.33335V8.43752L5.72917 3.33335H16.6667C17.125 3.33335 17.5175 3.49669 17.8442 3.82335C18.1703 4.14946 18.3333 4.54169 18.3333 5.00002V15.9375ZM5.83333 12.5H8.33333C8.56944 12.5 8.7675 12.42 8.9275 12.26C9.08694 12.1006 9.16667 11.9028 9.16667 11.6667V11.5209L8.47917 10.8334H7.91667V11.25H6.25V8.60419L5.3125 7.66669C5.21528 7.73613 5.13889 7.82974 5.08333 7.94752C5.02778 8.06585 5 8.19446 5 8.33335V11.6667C5 11.9028 5.07972 12.1006 5.23917 12.26C5.39917 12.42 5.59722 12.5 5.83333 12.5Z"
360
348
  fill="currentColor"
361
349
  />
362
- </svg>`,captions:()=>J`<svg width="20" height="20" viewBox="0 0 20 20" fill="none" part="svg">
350
+ </svg>`,captions:()=>st`<svg width="20" height="20" viewBox="0 0 20 20" fill="none" part="svg">
363
351
  <path
364
352
  d="M5.83342 12.5H8.33342C8.56953 12.5 8.76758 12.42 8.92758 12.26C9.08703 12.1005 9.16675 11.9028 9.16675 11.6666V10.8333H7.91675V11.25H6.25008V8.74998H7.91675V9.16665H9.16675V8.33331C9.16675 8.0972 9.08703 7.89915 8.92758 7.73915C8.76758 7.5797 8.56953 7.49998 8.33342 7.49998H5.83342C5.5973 7.49998 5.39925 7.5797 5.23925 7.73915C5.0798 7.89915 5.00008 8.0972 5.00008 8.33331V11.6666C5.00008 11.9028 5.0798 12.1005 5.23925 12.26C5.39925 12.42 5.5973 12.5 5.83342 12.5ZM11.6667 12.5H14.1667C14.4029 12.5 14.6006 12.42 14.7601 12.26C14.9201 12.1005 15.0001 11.9028 15.0001 11.6666V10.8333H13.7501V11.25H12.0834V8.74998H13.7501V9.16665H15.0001V8.33331C15.0001 8.0972 14.9201 7.89915 14.7601 7.73915C14.6006 7.5797 14.4029 7.49998 14.1667 7.49998H11.6667C11.4306 7.49998 11.2329 7.5797 11.0734 7.73915C10.9134 7.89915 10.8334 8.0972 10.8334 8.33331V11.6666C10.8334 11.9028 10.9134 12.1005 11.0734 12.26C11.2329 12.42 11.4306 12.5 11.6667 12.5ZM3.33341 16.6666C2.87508 16.6666 2.48258 16.5036 2.15591 16.1775C1.8298 15.8508 1.66675 15.4583 1.66675 15V4.99998C1.66675 4.54165 1.8298 4.14942 2.15591 3.82331C2.48258 3.49665 2.87508 3.33331 3.33341 3.33331H16.6667C17.1251 3.33331 17.5176 3.49665 17.8442 3.82331C18.1704 4.14942 18.3334 4.54165 18.3334 4.99998V15C18.3334 15.4583 18.1704 15.8508 17.8442 16.1775C17.5176 16.5036 17.1251 16.6666 16.6667 16.6666H3.33341Z"
365
353
  fill="currentColor"
366
354
  />
367
- </svg>`,"chevron-down":()=>J`<svg width="16" height="16" viewBox="0 0 16 16" fill="none" part="svg">
355
+ </svg>`,"chevron-down":()=>st`<svg width="16" height="16" viewBox="0 0 16 16" fill="none" part="svg">
368
356
  <path
369
357
  d="M11.8032 7.13666L10.8632 6.19666L7.80322 9.24999L4.74322 6.19666L3.80322 7.13666L7.80322 11.1367L11.8032 7.13666Z"
370
358
  fill="currentColor"
371
359
  />
372
- </svg>`,close:()=>J`<svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg" part="svg">
360
+ </svg>`,close:()=>st`<svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg" part="svg">
373
361
  <path
374
362
  d="M15.8334 5.34163L14.6584 4.16663L10 8.82496L5.34169 4.16663L4.16669 5.34163L8.82502 9.99996L4.16669 14.6583L5.34169 15.8333L10 11.175L14.6584 15.8333L15.8334 14.6583L11.175 9.99996L15.8334 5.34163Z"
375
363
  fill="currentColor"
376
364
  />
377
- </svg>`,loading:()=>J`<svg class="spinner" width="50" height="50" viewBox="0 0 50 50" part="svg">
365
+ </svg>`,loading:()=>st`<svg class="spinner" width="50" height="50" viewBox="0 0 50 50" part="svg">
378
366
  <style>
379
367
  /* SVG spinner icon animation */
380
368
  .spinner {
@@ -434,62 +422,62 @@ ${t}`,r0=Object.getOwnPropertyDescriptor(Function.prototype,"toString"),n0=Objec
434
422
  }
435
423
  </style>
436
424
  <circle class="path" cx="25" cy="25" r="20" fill="none" stroke-width="5" />
437
- </svg>`,maximize:()=>J`<svg width="20" height="20" viewBox="0 0 20 20" fill="none" part="svg">
425
+ </svg>`,maximize:()=>st`<svg width="20" height="20" viewBox="0 0 20 20" fill="none" part="svg">
438
426
  <path
439
427
  fill-rule="evenodd"
440
428
  clip-rule="evenodd"
441
429
  d="M6.66675 3.33331H3.33341H1.66675V4.99998V8.33331H3.33341V4.99998H6.66675V3.33331ZM6.66675 15H3.33341V11.6666H1.66675V15V16.6666H3.33341H6.66675V15ZM13.3334 3.33331H16.6667H18.3334V4.99998V8.33331H16.6667V4.99998H13.3334V3.33331ZM16.6667 15H13.3334V16.6666H16.6667H18.3334V15V11.6666H16.6667V15Z"
442
430
  fill="currentColor"
443
431
  />
444
- </svg>`,minimize:()=>J`<svg width="20" height="20" viewBox="0 0 20 20" fill="none" part="svg">
432
+ </svg>`,minimize:()=>st`<svg width="20" height="20" viewBox="0 0 20 20" fill="none" part="svg">
445
433
  <path
446
434
  fill-rule="evenodd"
447
435
  clip-rule="evenodd"
448
436
  d="M5.00008 3.33331H6.66675V6.66665V8.33331H5.00008H1.66675V6.66665H5.00008V3.33331ZM5.00008 11.6666H1.66675V13.3333H5.00008V16.6666H6.66675V13.3333V11.6666H5.00008ZM15.0001 6.66665H18.3334V8.33331H15.0001H13.3334V6.66665V3.33331H15.0001V6.66665ZM18.3334 11.6666H15.0001H13.3334V13.3333V16.6666H15.0001V13.3333H18.3334V11.6666Z"
449
437
  fill="currentColor"
450
438
  />
451
- </svg>`,muted:()=>J`<svg width="20" height="20" viewBox="0 0 20 20" fill="none" part="svg">
439
+ </svg>`,muted:()=>st`<svg width="20" height="20" viewBox="0 0 20 20" fill="none" part="svg">
452
440
  <path
453
441
  d="M13.75 10C13.75 8.525 12.9 7.25833 11.6667 6.64167V8.48333L13.7083 10.525C13.7333 10.3583 13.75 10.1833 13.75 10ZM15.8333 10C15.8333 10.7833 15.6667 11.5167 15.3833 12.2L16.6417 13.4583C17.1917 12.425 17.5 11.25 17.5 10C17.5 6.43333 15.0083 3.45 11.6667 2.69167V4.40833C14.075 5.125 15.8333 7.35833 15.8333 10ZM3.55833 2.5L2.5 3.55833L6.44167 7.5H2.5V12.5H5.83333L10 16.6667V11.0583L13.5417 14.6C12.9833 15.0333 12.3583 15.375 11.6667 15.5833V17.3C12.8167 17.0417 13.8583 16.5083 14.7417 15.7917L16.4417 17.5L17.5 16.4417L10 8.94167L3.55833 2.5ZM10 3.33333L8.25833 5.075L10 6.81667V3.33333Z"
454
442
  fill="currentColor"
455
443
  />
456
- </svg>`,pause:()=>J`<svg width="20" height="20" viewBox="0 0 20 20" fill="none" part="svg">
444
+ </svg>`,pause:()=>st`<svg width="20" height="20" viewBox="0 0 20 20" fill="none" part="svg">
457
445
  <path
458
446
  fill-rule="evenodd"
459
447
  clip-rule="evenodd"
460
448
  d="M8.33333 2.5H5V17.5H8.33333V2.5ZM15 2.5H11.6667V17.5H15V2.5Z"
461
449
  fill="currentColor"
462
450
  />
463
- </svg>`,"play-large":()=>J`<svg width="45" height="53" viewBox="0 0 45 53" fill="none" part="svg">
451
+ </svg>`,"play-large":()=>st`<svg width="45" height="53" viewBox="0 0 45 53" fill="none" part="svg">
464
452
  <path
465
453
  d="M43.5 23.8319C45.5 25.0083 45.5 27.9492 43.5 29.1256L4.5 52.0647C2.5 53.2411 0 51.7706 0 49.4179V3.53961C0 1.18687 2.5 -0.283582 4.5 0.892785L43.5 23.8319Z"
466
454
  fill="currentColor"
467
455
  />
468
- </svg>`,play:()=>J`<svg width="20" height="20" viewBox="0 0 20 20" fill="none" part="svg">
456
+ </svg>`,play:()=>st`<svg width="20" height="20" viewBox="0 0 20 20" fill="none" part="svg">
469
457
  <path d="M17.3803 9.99998L5.83325 16.6666V3.33331L17.3803 9.99998Z" fill="currentColor" />
470
- </svg>`,settings:()=>J`<svg width="20" height="20" viewBox="0 0 20 20" fill="none" part="svg">
458
+ </svg>`,settings:()=>st`<svg width="20" height="20" viewBox="0 0 20 20" fill="none" part="svg">
471
459
  <path
472
460
  d="M7.70833 18.3334L7.375 15.6667C7.19445 15.5972 7.02444 15.5139 6.865 15.4167C6.705 15.3195 6.54861 15.2153 6.39583 15.1042L3.91667 16.1459L1.625 12.1875L3.77083 10.5625C3.75694 10.4653 3.75 10.3714 3.75 10.2809C3.75 10.1909 3.75 10.0972 3.75 10C3.75 9.9028 3.75 9.80891 3.75 9.71835C3.75 9.62835 3.75694 9.53474 3.77083 9.43752L1.625 7.81252L3.91667 3.85419L6.39583 4.89585C6.54861 4.78474 6.70833 4.68058 6.875 4.58335C7.04167 4.48613 7.20833 4.4028 7.375 4.33335L7.70833 1.66669H12.2917L12.625 4.33335C12.8056 4.4028 12.9758 4.48613 13.1358 4.58335C13.2953 4.68058 13.4514 4.78474 13.6042 4.89585L16.0833 3.85419L18.375 7.81252L16.2292 9.43752C16.2431 9.53474 16.25 9.62835 16.25 9.71835C16.25 9.80891 16.25 9.9028 16.25 10C16.25 10.0972 16.25 10.1909 16.25 10.2809C16.25 10.3714 16.2361 10.4653 16.2083 10.5625L18.3542 12.1875L16.0625 16.1459L13.6042 15.1042C13.4514 15.2153 13.2917 15.3195 13.125 15.4167C12.9583 15.5139 12.7917 15.5972 12.625 15.6667L12.2917 18.3334H7.70833ZM10.0417 12.9167C10.8472 12.9167 11.5347 12.632 12.1042 12.0625C12.6736 11.4931 12.9583 10.8056 12.9583 10C12.9583 9.19447 12.6736 8.50696 12.1042 7.93752C11.5347 7.36808 10.8472 7.08335 10.0417 7.08335C9.22222 7.08335 8.53111 7.36808 7.96833 7.93752C7.40611 8.50696 7.125 9.19447 7.125 10C7.125 10.8056 7.40611 11.4931 7.96833 12.0625C8.53111 12.632 9.22222 12.9167 10.0417 12.9167ZM10.0417 11.25C9.69445 11.25 9.39945 11.1284 9.15667 10.885C8.91333 10.6422 8.79167 10.3472 8.79167 10C8.79167 9.6528 8.91333 9.3578 9.15667 9.11502C9.39945 8.87169 9.69445 8.75002 10.0417 8.75002C10.3889 8.75002 10.6842 8.87169 10.9275 9.11502C11.1703 9.3578 11.2917 9.6528 11.2917 10C11.2917 10.3472 11.1703 10.6422 10.9275 10.885C10.6842 11.1284 10.3889 11.25 10.0417 11.25ZM9.16667 16.6667H10.8125L11.1042 14.4584C11.5347 14.3472 11.9342 14.1839 12.3025 13.9684C12.6703 13.7534 13.0069 13.4931 13.3125 13.1875L15.375 14.0417L16.1875 12.625L14.3958 11.2709C14.4653 11.0764 14.5139 10.8714 14.5417 10.6559C14.5694 10.4409 14.5833 10.2222 14.5833 10C14.5833 9.7778 14.5694 9.55891 14.5417 9.34335C14.5139 9.12835 14.4653 8.92363 14.3958 8.72919L16.1875 7.37502L15.375 5.95835L13.3125 6.83335C13.0069 6.51391 12.6703 6.24641 12.3025 6.03085C11.9342 5.81585 11.5347 5.6528 11.1042 5.54169L10.8333 3.33335H9.1875L8.89583 5.54169C8.46528 5.6528 8.06611 5.81585 7.69833 6.03085C7.33 6.24641 6.99306 6.50697 6.6875 6.81252L4.625 5.95835L3.8125 7.37502L5.60417 8.70835C5.53472 8.91669 5.48611 9.12502 5.45833 9.33335C5.43056 9.54169 5.41667 9.76391 5.41667 10C5.41667 10.2222 5.43056 10.4375 5.45833 10.6459C5.48611 10.8542 5.53472 11.0625 5.60417 11.2709L3.8125 12.625L4.625 14.0417L6.6875 13.1667C6.99306 13.4861 7.33 13.7534 7.69833 13.9684C8.06611 14.1839 8.46528 14.3472 8.89583 14.4584L9.16667 16.6667Z"
473
461
  fill="currentColor"
474
462
  />
475
- </svg>`,tick:()=>J`<svg width="20" height="21" viewBox="0 0 20 21" fill="none" part="svg">
463
+ </svg>`,tick:()=>st`<svg width="20" height="21" viewBox="0 0 20 21" fill="none" part="svg">
476
464
  <path
477
465
  d="M7.50016 14.0001L4.00016 10.5001L2.8335 11.6667L7.50016 16.3334L17.5002 6.33341L16.3335 5.16675L7.50016 14.0001Z"
478
466
  fill="currentColor"
479
467
  />
480
- </svg>`,"volume-high":()=>J`<svg width="20" height="20" viewBox="0 0 20 20" fill="none" part="svg">
468
+ </svg>`,"volume-high":()=>st`<svg width="20" height="20" viewBox="0 0 20 20" fill="none" part="svg">
481
469
  <path
482
470
  d="M2.5 7.49998V12.5H5.83333L10 16.6667V3.33332L5.83333 7.49998H2.5ZM13.75 9.99998C13.75 8.52498 12.9 7.25832 11.6667 6.64165V13.35C12.9 12.7417 13.75 11.475 13.75 9.99998ZM11.6667 2.69165V4.40832C14.075 5.12498 15.8333 7.35832 15.8333 9.99998C15.8333 12.6417 14.075 14.875 11.6667 15.5917V17.3083C15.0083 16.55 17.5 13.5667 17.5 9.99998C17.5 6.43332 15.0083 3.44998 11.6667 2.69165Z"
483
471
  fill="currentColor"
484
472
  />
485
- </svg>`,"volume-low":()=>J`<svg width="20" height="20" viewBox="0 0 20 20" fill="none" part="svg">
473
+ </svg>`,"volume-low":()=>st`<svg width="20" height="20" viewBox="0 0 20 20" fill="none" part="svg">
486
474
  <path d="M5.83325 7.49998V12.5H9.16658L13.3333 16.6666V3.33331L9.16658 7.49998H5.83325Z" fill="currentColor" />
487
- </svg>`,"volume-medium":()=>J`<svg width="20" height="20" viewBox="0 0 20 20" fill="none" part="svg">
475
+ </svg>`,"volume-medium":()=>st`<svg width="20" height="20" viewBox="0 0 20 20" fill="none" part="svg">
488
476
  <path
489
477
  d="M15.4167 9.99998C15.4167 8.52498 14.5667 7.25831 13.3334 6.64165V13.35C14.5667 12.7416 15.4167 11.475 15.4167 9.99998ZM4.16675 7.49998V12.5H7.50008L11.6667 16.6666V3.33331L7.50008 7.49998H4.16675Z"
490
478
  fill="currentColor"
491
479
  />
492
- </svg>`,vouch:()=>J`<svg
480
+ </svg>`,vouch:()=>st`<svg
493
481
  xmlns="http://www.w3.org/2000/svg"
494
482
  height="28"
495
483
  width="105"
@@ -500,26 +488,26 @@ ${t}`,r0=Object.getOwnPropertyDescriptor(Function.prototype,"toString"),n0=Objec
500
488
  <path
501
489
  d="M9.853 23.246L4.86 7.688H0L7 27.42h5.52l7.265-19.733h-4.65L9.854 23.246zM95.12 7.08a8.905 8.905 0 00-4.648 1.294V0H86.14v27.419h4.332V16.087a4.656 4.656 0 014.649-4.65 4.656 4.656 0 014.649 4.65v11.332h4.332V16.087c.026-4.966-4.015-9.008-8.981-9.008zM57.188 19.02a4.656 4.656 0 01-4.649 4.649 4.656 4.656 0 01-4.649-4.65V7.689h-4.332V19.02c0 4.966 4.041 8.98 8.981 8.98 4.94 0 8.981-4.04 8.981-8.98V7.688h-4.332V19.02zM30.483 7.133c-5.732 0-10.408 4.675-10.408 10.407s4.676 10.408 10.408 10.408c5.732 0 10.408-4.676 10.408-10.408 0-5.732-4.676-10.407-10.408-10.407zm0 16.483a6.076 6.076 0 116.075-6.076c0 3.355-2.747 6.076-6.075 6.076zM74.517 23.616a6.076 6.076 0 010-12.151 6.132 6.132 0 015.045 2.668l3.592-2.43a10.473 10.473 0 00-8.637-4.57c-5.732 0-10.408 4.675-10.408 10.407s4.676 10.408 10.408 10.408a10.35 10.35 0 008.611-4.596l-3.593-2.43a5.975 5.975 0 01-5.018 2.694z"
502
490
  />
503
- </svg>`};var I0=Object.defineProperty,k0=Object.getOwnPropertyDescriptor,Vd=(r,t,e,i)=>{for(var s=i>1?void 0:i?k0(t,e):t,n=r.length-1,a;n>=0;n--)(a=r[n])&&(s=(i?a(t,e,s):a(s))||s);return i&&s&&I0(t,e,s),s};let wr=class extends ot{render(){return!this.icon||!Object.keys(Gd).includes(this.icon)?null:Gd[this.icon]()}};wr.styles=[ot.styles??[],Ft`
491
+ </svg>`};var Wv=Object.defineProperty,Yv=Object.getOwnPropertyDescriptor,bc=(r,t,e,i)=>{for(var s=i>1?void 0:i?Yv(t,e):t,n=r.length-1,a;n>=0;n--)(a=r[n])&&(s=(i?a(t,e,s):a(s))||s);return i&&s&&Wv(t,e,s),s};let wr=class extends yt{render(){return!this.icon||!Object.keys(Ec).includes(this.icon)?null:Ec[this.icon]()}};wr.styles=[yt.styles??[],jt`
504
492
  :host {
505
493
  display: flex;
506
494
  align-items: center;
507
495
  justify-content: center;
508
496
  flex-shrink: 0;
509
497
  }
510
- `],Vd([G({type:String})],wr.prototype,"icon",2),wr=Vd([qt("vmp-new-icon")],wr);var C0=Object.defineProperty,D0=Object.getOwnPropertyDescriptor,Ii=(r,t,e,i)=>{for(var s=i>1?void 0:i?D0(t,e):t,n=r.length-1,a;n>=0;n--)(a=r[n])&&(s=(i?a(t,e,s):a(s))||s);return i&&s&&C0(t,e,s),s};let Ne=class extends ot{constructor(){super(...arguments),this.active=!1,this.size="small",this.rounded="medium",this.weight="light"}render(){return J`
498
+ `],bc([j({type:String})],wr.prototype,"icon",2),wr=bc([se("vmp-new-icon")],wr);var zv=Object.defineProperty,qv=Object.getOwnPropertyDescriptor,$i=(r,t,e,i)=>{for(var s=i>1?void 0:i?qv(t,e):t,n=r.length-1,a;n>=0;n--)(a=r[n])&&(s=(i?a(t,e,s):a(s))||s);return i&&s&&zv(t,e,s),s};let qe=class extends yt{constructor(){super(...arguments),this.active=!1,this.size="small",this.rounded="medium",this.weight="light"}render(){return st`
511
499
  <vmp-new-button
512
500
  ?active=${this.active}
513
- size=${Ji(this.size)}
514
- rounded=${Ji(this.rounded)}
515
- weight=${Ji(this.weight)}
501
+ size=${ri(this.size)}
502
+ rounded=${ri(this.rounded)}
503
+ weight=${ri(this.weight)}
516
504
  >
517
505
  <vmp-new-icon
518
- class=${ht({tiny:this.size==="tiny",small:this.size==="small",large:this.size==="large"})}
519
- icon=${Ji(this.icon)}
506
+ class=${wt({tiny:this.size==="tiny",small:this.size==="small",large:this.size==="large"})}
507
+ icon=${ri(this.icon)}
520
508
  ></vmp-new-icon>
521
509
  </vmp-new-button>
522
- `}};Ne.styles=[ot.styles??[],Ft`
510
+ `}};qe.styles=[yt.styles??[],jt`
523
511
  .tiny::part(svg) {
524
512
  height: 12px;
525
513
  width: 12px;
@@ -534,15 +522,15 @@ ${t}`,r0=Object.getOwnPropertyDescriptor(Function.prototype,"toString"),n0=Objec
534
522
  height: 32px;
535
523
  width: 32px;
536
524
  }
537
- `],Ii([G({type:Boolean})],Ne.prototype,"active",2),Ii([G({type:String})],Ne.prototype,"size",2),Ii([G({type:String})],Ne.prototype,"rounded",2),Ii([G({type:String})],Ne.prototype,"weight",2),Ii([G({type:String})],Ne.prototype,"icon",2),Ne=Ii([qt("vmp-new-icon-button")],Ne);const xa=`.tippy-box[data-animation=shift-away-subtle][data-state=hidden]{opacity:0}.tippy-box[data-animation=shift-away-subtle][data-state=hidden][data-placement^=top]{transform:translateY(5px)}.tippy-box[data-animation=shift-away-subtle][data-state=hidden][data-placement^=bottom]{transform:translateY(-5px)}.tippy-box[data-animation=shift-away-subtle][data-state=hidden][data-placement^=left]{transform:translate(5px)}.tippy-box[data-animation=shift-away-subtle][data-state=hidden][data-placement^=right]{transform:translate(-5px)}
538
- `;var x0=Object.defineProperty,P0=Object.getOwnPropertyDescriptor,ys=(r,t,e,i)=>{for(var s=i>1?void 0:i?P0(t,e):t,n=r.length-1,a;n>=0;n--)(a=r[n])&&(s=(i?a(t,e,s):a(s))||s);return i&&s&&x0(t,e,s),s};let ni=class extends ot{constructor(){super(...arguments),this.semibold=!1,this.truncate=!1,this.size="medium",this.content=""}render(){return J`
525
+ `],$i([j({type:Boolean})],qe.prototype,"active",2),$i([j({type:String})],qe.prototype,"size",2),$i([j({type:String})],qe.prototype,"rounded",2),$i([j({type:String})],qe.prototype,"weight",2),$i([j({type:String})],qe.prototype,"icon",2),qe=$i([se("vmp-new-icon-button")],qe);const Ea=`.tippy-box[data-animation=shift-away-subtle][data-state=hidden]{opacity:0}.tippy-box[data-animation=shift-away-subtle][data-state=hidden][data-placement^=top]{transform:translateY(5px)}.tippy-box[data-animation=shift-away-subtle][data-state=hidden][data-placement^=bottom]{transform:translateY(-5px)}.tippy-box[data-animation=shift-away-subtle][data-state=hidden][data-placement^=left]{transform:translate(5px)}.tippy-box[data-animation=shift-away-subtle][data-state=hidden][data-placement^=right]{transform:translate(-5px)}
526
+ `;var Xv=Object.defineProperty,Qv=Object.getOwnPropertyDescriptor,Ls=(r,t,e,i)=>{for(var s=i>1?void 0:i?Qv(t,e):t,n=r.length-1,a;n>=0;n--)(a=r[n])&&(s=(i?a(t,e,s):a(s))||s);return i&&s&&Xv(t,e,s),s};let gi=class extends yt{constructor(){super(...arguments),this.semibold=!1,this.truncate=!1,this.size="medium",this.content=""}render(){return st`
539
527
  <div
540
528
  part="content"
541
- class=${ht({semibold:this.semibold,truncate:this.truncate,[this.size]:!0})}
529
+ class=${wt({semibold:this.semibold,truncate:this.truncate,[this.size]:!0})}
542
530
  >
543
531
  ${this.content}
544
532
  </div>
545
- `}};ni.styles=[ot.styles??[],Ft`
533
+ `}};gi.styles=[yt.styles??[],jt`
546
534
  :host {
547
535
  --text-size: var(--fontSizes-medium);
548
536
  --text-line-height: var(--lineHeights-medium);
@@ -580,11 +568,11 @@ ${t}`,r0=Object.getOwnPropertyDescriptor(Function.prototype,"toString"),n0=Objec
580
568
  text-overflow: ellipsis;
581
569
  overflow: hidden;
582
570
  }
583
- `],ys([G({type:Boolean})],ni.prototype,"semibold",2),ys([G({type:Boolean})],ni.prototype,"truncate",2),ys([G({type:String})],ni.prototype,"size",2),ys([G({type:String})],ni.prototype,"content",2),ni=ys([qt("vmp-new-text")],ni);var O0=Object.defineProperty,M0=Object.getOwnPropertyDescriptor,Es=(r,t,e,i)=>{for(var s=i>1?void 0:i?M0(t,e):t,n=r.length-1,a;n>=0;n--)(a=r[n])&&(s=(i?a(t,e,s):a(s))||s);return i&&s&&O0(t,e,s),s};let ai=class extends ot{constructor(){super(...arguments),this.activeItems=[],this.visibleItems=null,this.subItemsActive=null,this.tippy=null,this._contentRef=de()}_handleBackClick(){this.subItemsActive=null,this.visibleItems=this.items??null}willUpdate(){this.visibleItems=this.visibleItems??this.items??null}updated(){var r,t;const e=(t=(r=this.items)==null?void 0:r.items.find(({id:i})=>this.subItemsActive===i))==null?void 0:t.subItems;this.visibleItems=e??this.items??null,e||(this.subItemsActive=null)}connectedCallback(){super.connectedCallback(),requestAnimationFrame(()=>{var r;const t=(r=this.shadowRoot)==null?void 0:r.querySelector("slot"),e=t==null?void 0:t.assignedElements()[0];e&&this._contentRef.value&&(this.tippy=ti(e,{content:this._contentRef.value,allowHTML:!0,arrow:!1,animation:"shift-away-subtle",interactive:!0,placement:"top",trigger:"click",onShow:()=>{this.dispatchEvent(new CustomEvent("menu:toggle",{detail:!0}))},onHide:()=>{this.dispatchEvent(new CustomEvent("menu:toggle",{detail:!1}))},appendTo:()=>this.shadowRoot}))})}disconnectedCallback(){var r;super.disconnectedCallback(),(r=this.tippy)==null||r.destroy()}render(){var r,t;return J`
571
+ `],Ls([j({type:Boolean})],gi.prototype,"semibold",2),Ls([j({type:Boolean})],gi.prototype,"truncate",2),Ls([j({type:String})],gi.prototype,"size",2),Ls([j({type:String})],gi.prototype,"content",2),gi=Ls([se("vmp-new-text")],gi);var Zv=Object.defineProperty,Jv=Object.getOwnPropertyDescriptor,Rs=(r,t,e,i)=>{for(var s=i>1?void 0:i?Jv(t,e):t,n=r.length-1,a;n>=0;n--)(a=r[n])&&(s=(i?a(t,e,s):a(s))||s);return i&&s&&Zv(t,e,s),s};let mi=class extends yt{constructor(){super(...arguments),this.activeItems=[],this.visibleItems=null,this.subItemsActive=null,this.tippy=null,this._contentRef=ae()}_handleBackClick(){this.subItemsActive=null,this.visibleItems=this.items??null}willUpdate(){this.visibleItems=this.visibleItems??this.items??null}updated(){var r,t;const e=(t=(r=this.items)==null?void 0:r.items.find(({id:i})=>this.subItemsActive===i))==null?void 0:t.subItems;this.visibleItems=e??this.items??null,e||(this.subItemsActive=null)}connectedCallback(){super.connectedCallback(),requestAnimationFrame(()=>{var r;const t=(r=this.shadowRoot)==null?void 0:r.querySelector("slot"),e=t==null?void 0:t.assignedElements()[0];e&&this._contentRef.value&&(this.tippy=ci(e,{content:this._contentRef.value,allowHTML:!0,arrow:!1,animation:"shift-away-subtle",interactive:!0,placement:"top",trigger:"click",onShow:()=>{this.dispatchEvent(new CustomEvent("menu:toggle",{detail:!0}))},onHide:()=>{this.dispatchEvent(new CustomEvent("menu:toggle",{detail:!1}))},appendTo:()=>this.shadowRoot}))})}disconnectedCallback(){var r;super.disconnectedCallback(),(r=this.tippy)==null||r.destroy()}render(){var r,t;return st`
584
572
  <slot></slot>
585
- <div ${ce(this._contentRef)} class="content">
573
+ <div ${oe(this._contentRef)} class="content">
586
574
  <div class="title">
587
- ${this.subItemsActive?J`
575
+ ${this.subItemsActive?st`
588
576
  <button class="back" @click=${this._handleBackClick}>
589
577
  <vmp-new-icon icon="chevron-down"></vmp-new-icon>
590
578
  </button>
@@ -596,17 +584,17 @@ ${t}`,r0=Object.getOwnPropertyDescriptor(Function.prototype,"toString"),n0=Objec
596
584
  .content=${((r=this.visibleItems)==null?void 0:r.title)??"Sub Menu"}
597
585
  ></vmp-new-text>
598
586
  </div>
599
- ${ll(((t=this.visibleItems)==null?void 0:t.items)??[],({id:e})=>e,e=>J`
587
+ ${Bo(((t=this.visibleItems)==null?void 0:t.items)??[],({id:e})=>e,e=>st`
600
588
  <button
601
589
  class="item"
602
590
  @click=${()=>{e.subItems&&(this.subItemsActive=e.id,this.visibleItems=e.subItems),e.event&&this.dispatchEvent(new CustomEvent(e.event,{detail:e,bubbles:!0,composed:!0}))}}
603
591
  >
604
592
  <vmp-new-text ?semibold=${!0} size="small" content=${e.label}></vmp-new-text>
605
- ${e.subItems?J`<vmp-new-icon class="forward" icon="chevron-down"></vmp-new-icon>`:this.activeItems.includes(e.id)?J`<vmp-new-icon icon="tick"></vmp-new-icon>`:null}
593
+ ${e.subItems?st`<vmp-new-icon class="forward" icon="chevron-down"></vmp-new-icon>`:this.activeItems.includes(e.id)?st`<vmp-new-icon icon="tick"></vmp-new-icon>`:null}
606
594
  </button>
607
595
  `)}
608
596
  </div>
609
- `}};ai.styles=[ot.styles??[],Oi(xa),Ft`
597
+ `}};mi.styles=[yt.styles??[],Yi(Ea),jt`
610
598
  :host {
611
599
  display: flex;
612
600
  }
@@ -664,12 +652,12 @@ ${t}`,r0=Object.getOwnPropertyDescriptor(Function.prototype,"toString"),n0=Objec
664
652
  height: 20px;
665
653
  width: 20px;
666
654
  }
667
- `],Es([G({type:Object})],ai.prototype,"items",2),Es([G({type:Array})],ai.prototype,"activeItems",2),Es([Nt()],ai.prototype,"visibleItems",2),Es([Nt()],ai.prototype,"subItemsActive",2),ai=Es([qt("vmp-new-menu")],ai);var $0=Object.defineProperty,F0=Object.getOwnPropertyDescriptor,Pa=(r,t,e,i)=>{for(var s=i>1?void 0:i?F0(t,e):t,n=r.length-1,a;n>=0;n--)(a=r[n])&&(s=(i?a(t,e,s):a(s))||s);return i&&s&&$0(t,e,s),s};let Ts=class extends ot{constructor(){super(...arguments),this.content="",this.disabled=!1,this.tippy=null,this._contentRef=de()}connectedCallback(){super.connectedCallback(),requestAnimationFrame(()=>{var r;const t=(r=this.shadowRoot)==null?void 0:r.querySelector("slot"),e=t==null?void 0:t.assignedElements()[0];e&&this._contentRef.value&&(this.tippy=ti(e,{content:this._contentRef.value,allowHTML:!0,arrow:!1,animation:"shift-away-subtle",interactive:!1,placement:"top",zIndex:1e4,appendTo:()=>this.shadowRoot}))})}disconnectedCallback(){var r;super.disconnectedCallback(),(r=this.tippy)==null||r.destroy()}updated(){var r,t;this.disabled?(r=this.tippy)==null||r.disable():(t=this.tippy)==null||t.enable()}render(){return J`
655
+ `],Rs([j({type:Object})],mi.prototype,"items",2),Rs([j({type:Array})],mi.prototype,"activeItems",2),Rs([Wt()],mi.prototype,"visibleItems",2),Rs([Wt()],mi.prototype,"subItemsActive",2),mi=Rs([se("vmp-new-menu")],mi);var t0=Object.defineProperty,e0=Object.getOwnPropertyDescriptor,ba=(r,t,e,i)=>{for(var s=i>1?void 0:i?e0(t,e):t,n=r.length-1,a;n>=0;n--)(a=r[n])&&(s=(i?a(t,e,s):a(s))||s);return i&&s&&t0(t,e,s),s};let _s=class extends yt{constructor(){super(...arguments),this.content="",this.disabled=!1,this.tippy=null,this._contentRef=ae()}connectedCallback(){super.connectedCallback(),requestAnimationFrame(()=>{var r;const t=(r=this.shadowRoot)==null?void 0:r.querySelector("slot"),e=t==null?void 0:t.assignedElements()[0];e&&this._contentRef.value&&(this.tippy=ci(e,{content:this._contentRef.value,allowHTML:!0,arrow:!1,animation:"shift-away-subtle",interactive:!1,placement:"top",zIndex:1e4,appendTo:()=>this.shadowRoot}))})}disconnectedCallback(){var r;super.disconnectedCallback(),(r=this.tippy)==null||r.destroy()}updated(){var r,t;this.disabled?(r=this.tippy)==null||r.disable():(t=this.tippy)==null||t.enable()}render(){return st`
668
656
  <slot></slot>
669
- <div ${ce(this._contentRef)} class="content">
657
+ <div ${oe(this._contentRef)} class="content">
670
658
  <vmp-new-text content=${this.content}></vmp-new-text>
671
659
  </div>
672
- `}};Ts.styles=[ot.styles??[],Oi(xa),Ft`
660
+ `}};_s.styles=[yt.styles??[],Yi(Ea),jt`
673
661
  :host {
674
662
  display: flex;
675
663
  }
@@ -683,19 +671,19 @@ ${t}`,r0=Object.getOwnPropertyDescriptor(Function.prototype,"toString"),n0=Objec
683
671
  background: var(--colors-dark-800);
684
672
  border-radius: var(--radii-medium);
685
673
  }
686
- `],Pa([G({type:String})],Ts.prototype,"content",2),Pa([G({type:Boolean})],Ts.prototype,"disabled",2),Ts=Pa([qt("vmp-new-tooltip")],Ts);var N0=Object.defineProperty,U0=Object.getOwnPropertyDescriptor,Oa=(r,t,e,i)=>{for(var s=i>1?void 0:i?U0(t,e):t,n=r.length-1,a;n>=0;n--)(a=r[n])&&(s=(i?a(t,e,s):a(s))||s);return i&&s&&N0(t,e,s),s};let bs=class extends ot{constructor(){super(...arguments),this.volume=1,this.muted=!1,this.tippy=null,this._contentRef=de(),this._anchorRef=de(),this._menuOpen=!1}connectedCallback(){super.connectedCallback(),requestAnimationFrame(()=>{this._anchorRef.value&&this._contentRef.value&&(this.tippy=ti(this._anchorRef.value,{content:this._contentRef.value,allowHTML:!0,arrow:!1,animation:"shift-away-subtle",interactive:!0,placement:"top",interactiveBorder:20,onShow:()=>{this._menuOpen=!0,this.dispatchEvent(new CustomEvent("menu:toggle",{detail:!0}))},onHide:()=>{this._menuOpen=!1,this.dispatchEvent(new CustomEvent("menu:toggle",{detail:!1}))},appendTo:()=>this.shadowRoot}))})}disconnectedCallback(){var r;super.disconnectedCallback(),(r=this.tippy)==null||r.destroy()}render(){return J`
674
+ `],ba([j({type:String})],_s.prototype,"content",2),ba([j({type:Boolean})],_s.prototype,"disabled",2),_s=ba([se("vmp-new-tooltip")],_s);var i0=Object.defineProperty,s0=Object.getOwnPropertyDescriptor,Ta=(r,t,e,i)=>{for(var s=i>1?void 0:i?s0(t,e):t,n=r.length-1,a;n>=0;n--)(a=r[n])&&(s=(i?a(t,e,s):a(s))||s);return i&&s&&i0(t,e,s),s};let ks=class extends yt{constructor(){super(...arguments),this.volume=1,this.muted=!1,this.tippy=null,this._contentRef=ae(),this._anchorRef=ae(),this._menuOpen=!1}connectedCallback(){super.connectedCallback(),requestAnimationFrame(()=>{this._anchorRef.value&&this._contentRef.value&&(this.tippy=ci(this._anchorRef.value,{content:this._contentRef.value,allowHTML:!0,arrow:!1,animation:"shift-away-subtle",interactive:!0,placement:"top",interactiveBorder:20,onShow:()=>{this._menuOpen=!0,this.dispatchEvent(new CustomEvent("menu:toggle",{detail:!0}))},onHide:()=>{this._menuOpen=!1,this.dispatchEvent(new CustomEvent("menu:toggle",{detail:!1}))},appendTo:()=>this.shadowRoot}))})}disconnectedCallback(){var r;super.disconnectedCallback(),(r=this.tippy)==null||r.destroy()}render(){return st`
687
675
  <vmp-new-icon-button
688
- ${ce(this._anchorRef)}
676
+ ${oe(this._anchorRef)}
689
677
  icon=${this.muted||this.volume===0?"muted":this.volume<1/3?"volume-low":this.volume<2/3?"volume-medium":"volume-high"}
690
678
  weight="heavy"
691
679
  rounded="full"
692
680
  @pointerdown=${r=>{this._menuOpen&&r.preventDefault()}}
693
681
  @click=${()=>{this._menuOpen&&this.dispatchEvent(new CustomEvent("volume:click",{bubbles:!0,composed:!0,detail:this.muted}))}}
694
682
  ></vmp-new-icon-button>
695
- <div ${ce(this._contentRef)} class="content">
683
+ <div ${oe(this._contentRef)} class="content">
696
684
  <input key="volume" type="range" min="0" max="1" step="0.01" .value=${this.volume.toString()} />
697
685
  </div>
698
- `}};bs.styles=[ot.styles??[],Oi(xa),Ft`
686
+ `}};ks.styles=[yt.styles??[],Yi(Ea),jt`
699
687
  .content {
700
688
  --volume-slider-height: 4px;
701
689
  --volume-slider-width: 78px;
@@ -823,7 +811,7 @@ ${t}`,r0=Object.getOwnPropertyDescriptor(Function.prototype,"toString"),n0=Objec
823
811
  --volume-slider-height: 8px;
824
812
  color: var(--colors-light-800);
825
813
  }
826
- `],Oa([G({type:Number})],bs.prototype,"volume",2),Oa([G({type:Boolean})],bs.prototype,"muted",2),bs=Oa([qt("vmp-new-volume-button")],bs);var B0=Object.defineProperty,H0=Object.getOwnPropertyDescriptor,Sr=(r,t,e,i)=>{for(var s=i>1?void 0:i?H0(t,e):t,n=r.length-1,a;n>=0;n--)(a=r[n])&&(s=(i?a(t,e,s):a(s))||s);return i&&s&&B0(t,e,s),s};let ki=class extends ot{constructor(){super(...arguments),this.duration=0,this.currentTime=0,this.buffer=[]}render(){var r;const t=((r=this.buffer)==null?void 0:r.sort((e,i)=>e.start<i.start?-1:i.start<e.start?1:0).reduce((e,{start:i,end:s},n)=>{const a=e[n-1],o=Math.floor(i),l=Math.ceil(s);return e.push({id:i,start:Math.max(0,o),end:Math.min(l,100)}),a&&a.end>=i-1&&(e[n].start=a.end),e},[]))??[];return J`
814
+ `],Ta([j({type:Number})],ks.prototype,"volume",2),Ta([j({type:Boolean})],ks.prototype,"muted",2),ks=Ta([se("vmp-new-volume-button")],ks);var r0=Object.defineProperty,n0=Object.getOwnPropertyDescriptor,Sr=(r,t,e,i)=>{for(var s=i>1?void 0:i?n0(t,e):t,n=r.length-1,a;n>=0;n--)(a=r[n])&&(s=(i?a(t,e,s):a(s))||s);return i&&s&&r0(t,e,s),s};let Mi=class extends yt{constructor(){super(...arguments),this.duration=0,this.currentTime=0,this.buffer=[]}render(){var r;const t=((r=this.buffer)==null?void 0:r.sort((e,i)=>e.start<i.start?-1:i.start<e.start?1:0).reduce((e,{start:i,end:s},n)=>{const a=e[n-1],o=Math.floor(i),l=Math.ceil(s);return e.push({id:i,start:Math.max(0,o),end:Math.min(l,100)}),a&&a.end>=i-1&&(e[n].start=a.end),e},[]))??[];return st`
827
815
  <div class="container">
828
816
  <input
829
817
  key="scrubber"
@@ -835,11 +823,11 @@ ${t}`,r0=Object.getOwnPropertyDescriptor(Function.prototype,"toString"),n0=Objec
835
823
  .value=${this.currentTime.toString()}
836
824
  data-testid="scrubber"
837
825
  />
838
- ${ll(t,({id:e})=>e,e=>J`
826
+ ${Bo(t,({id:e})=>e,e=>st`
839
827
  <div class="buffer" style=${`left: ${e.start}%; width: ${e.end-e.start}%`}></div>
840
828
  `)}
841
829
  </div>
842
- `}};ki.styles=[ot.styles??[],Ft`
830
+ `}};Mi.styles=[yt.styles??[],jt`
843
831
  :host {
844
832
  --player-scrubber-height: 8px;
845
833
  --player-scrubber-shadow-width: 4000px;
@@ -972,17 +960,17 @@ ${t}`,r0=Object.getOwnPropertyDescriptor(Function.prototype,"toString"),n0=Objec
972
960
  --player-scrubber-height: 16px;
973
961
  color: var(--colors-light-800);
974
962
  }
975
- `],Sr([G({type:Number})],ki.prototype,"duration",2),Sr([G({type:Number})],ki.prototype,"currentTime",2),Sr([G({type:Array})],ki.prototype,"buffer",2),ki=Sr([qt("vmp-new-progress-scrubber")],ki);var G0=Object.defineProperty,V0=Object.getOwnPropertyDescriptor,Dt=(r,t,e,i)=>{for(var s=i>1?void 0:i?V0(t,e):t,n=r.length-1,a;n>=0;n--)(a=r[n])&&(s=(i?a(t,e,s):a(s))||s);return i&&s&&G0(t,e,s),s};let wt=class extends ot{constructor(){super(...arguments),this.resizeHider=new L0(this),this.playing=!1,this.volume=1,this.muted=!1,this.currentTime=0,this.duration=0,this.level=-1,this.playbackRate=1,this.buffer=[],this.levels=[],this.captions=!1,this.fullscreen=!1,this.controls=Ca,this.volumeMenuOpen=!1,this.levelsMenuOpen=!1,this.playbackRateMenuOpen=!1,this.settingsMenuOpen=!1}_handleNavigateBackClick(){this.dispatchEvent(new CustomEvent("navigate:back",{bubbles:!0,composed:!0}))}_handleNavigateForwardClick(){this.dispatchEvent(new CustomEvent("navigate:forward",{bubbles:!0,composed:!0}))}_handlePlayClick(){this.dispatchEvent(new CustomEvent("play:click",{bubbles:!0,composed:!0,detail:this.playing}))}_handleCaptionsClick(){this.dispatchEvent(new CustomEvent("captions:click",{bubbles:!0,composed:!0,detail:this.captions}))}_handleFullscreenClick(){this.dispatchEvent(new CustomEvent("fullscreen:click",{bubbles:!0,composed:!0,detail:this.fullscreen}))}_handleVolumeMenuToggle({detail:r}){this.volumeMenuOpen=r}_handleLevelsMenuOpen({detail:r}){this.levelsMenuOpen=r}_handlePlaybackMenuToggle({detail:r}){this.playbackRateMenuOpen=r}_handleSettingsMenuToggle({detail:r}){this.settingsMenuOpen=r}hideMenus(){var r,t;(t=Array.from((r=this.shadowRoot)==null?void 0:r.querySelectorAll("vmp-new-menu, vmp-new-tooltip, vmp-new-volume-button")))==null||t.forEach(e=>{var i;(i=e.tippy)==null||i.hide()})}render(){var r,t,e,i,s,n,a,o,l,h,d,c,u;const f=((r=this.levels)==null?void 0:r.map((w,C)=>{const U=Math.min(w.width,w.height);return{id:`level-${C.toString()}`,event:"level:click",label:`${U}p`,value:{resolution:U,level:C}}}))??[],p={title:"Quality",items:[...f.reverse(),{id:"level--1",event:"level:click",label:"Auto",value:{level:-1,resolution:"auto"}}]},g={id:"levels",label:"Quality",subItems:p},v=(t=p.items)==null?void 0:t.find(({value:w})=>w.level===this.level),E=["levels","playback-rate","captions","fullscreen"].filter(w=>{var C;return(C=this.controls)==null?void 0:C.includes(w)}),T={title:"Settings",items:[g0,m0,g,v0].filter(({id:w})=>E.includes(w)&&this.resizeHider.hiddenControls.includes(w))},A=(e=this.controls)==null?void 0:e.includes("progress"),y=(i=this.controls)==null?void 0:i.includes("navigation"),b=(s=this.controls)==null?void 0:s.includes("play"),S=(n=this.controls)==null?void 0:n.includes("volume"),R=(a=this.controls)==null?void 0:a.includes("current-time"),D=(o=this.controls)==null?void 0:o.includes("duration"),_=(l=this.controls)==null?void 0:l.includes("levels"),I=(h=this.controls)==null?void 0:h.includes("speed"),N=(d=this.controls)==null?void 0:d.includes("captions"),P=(c=this.controls)==null?void 0:c.includes("fullscreen"),F=b||S||R||D||_||I||N||P,K=[`level-${(u=this.level)==null?void 0:u.toString()}`,`playback-rate-${this.playbackRate.toString()}`,this.captions&&"captions",this.fullscreen&&"fullscreen"].filter(Boolean);return J`
963
+ `],Sr([j({type:Number})],Mi.prototype,"duration",2),Sr([j({type:Number})],Mi.prototype,"currentTime",2),Sr([j({type:Array})],Mi.prototype,"buffer",2),Mi=Sr([se("vmp-new-progress-scrubber")],Mi);var a0=Object.defineProperty,o0=Object.getOwnPropertyDescriptor,Bt=(r,t,e,i)=>{for(var s=i>1?void 0:i?o0(t,e):t,n=r.length-1,a;n>=0;n--)(a=r[n])&&(s=(i?a(t,e,s):a(s))||s);return i&&s&&a0(t,e,s),s};let xt=class extends yt{constructor(){super(...arguments),this.resizeHider=new Vv(this),this.playing=!1,this.volume=1,this.muted=!1,this.currentTime=0,this.duration=0,this.level=-1,this.playbackRate=1,this.buffer=[],this.levels=[],this.captions=!1,this.fullscreen=!1,this.controls=va,this.volumeMenuOpen=!1,this.levelsMenuOpen=!1,this.playbackRateMenuOpen=!1,this.settingsMenuOpen=!1}_handleNavigateBackClick(){this.dispatchEvent(new CustomEvent("navigate:back",{bubbles:!0,composed:!0}))}_handleNavigateForwardClick(){this.dispatchEvent(new CustomEvent("navigate:forward",{bubbles:!0,composed:!0}))}_handlePlayClick(){this.dispatchEvent(new CustomEvent("play:click",{bubbles:!0,composed:!0,detail:this.playing}))}_handleCaptionsClick(){this.dispatchEvent(new CustomEvent("captions:click",{bubbles:!0,composed:!0,detail:this.captions}))}_handleFullscreenClick(){this.dispatchEvent(new CustomEvent("fullscreen:click",{bubbles:!0,composed:!0,detail:this.fullscreen}))}_handleVolumeMenuToggle({detail:r}){this.volumeMenuOpen=r}_handleLevelsMenuOpen({detail:r}){this.levelsMenuOpen=r}_handlePlaybackMenuToggle({detail:r}){this.playbackRateMenuOpen=r}_handleSettingsMenuToggle({detail:r}){this.settingsMenuOpen=r}hideMenus(){var r,t;(t=Array.from((r=this.shadowRoot)==null?void 0:r.querySelectorAll("vmp-new-menu, vmp-new-tooltip, vmp-new-volume-button")))==null||t.forEach(e=>{var i;(i=e.tippy)==null||i.hide()})}render(){var r,t,e,i,s,n,a,o,l,h,c,d,u;const f=((r=this.levels)==null?void 0:r.map((w,P)=>{const H=Math.min(w.width,w.height);return{id:`level-${P.toString()}`,event:"level:click",label:`${H}p`,value:{resolution:H,level:P}}}))??[],p={title:"Quality",items:[...f.reverse(),{id:"level--1",event:"level:click",label:"Auto",value:{level:-1,resolution:"auto"}}]},g={id:"levels",label:"Quality",subItems:p},v=(t=p.items)==null?void 0:t.find(({value:w})=>w.level===this.level),E=["levels","playback-rate","captions","fullscreen"].filter(w=>{var P;return(P=this.controls)==null?void 0:P.includes(w)}),A={title:"Settings",items:[Pv,Ov,g,$v].filter(({id:w})=>E.includes(w)&&this.resizeHider.hiddenControls.includes(w))},L=(e=this.controls)==null?void 0:e.includes("progress"),y=(i=this.controls)==null?void 0:i.includes("navigation"),S=(s=this.controls)==null?void 0:s.includes("play"),R=(n=this.controls)==null?void 0:n.includes("volume"),C=(a=this.controls)==null?void 0:a.includes("current-time"),M=(o=this.controls)==null?void 0:o.includes("duration"),D=(l=this.controls)==null?void 0:l.includes("levels"),I=(h=this.controls)==null?void 0:h.includes("speed"),G=(c=this.controls)==null?void 0:c.includes("captions"),F=(d=this.controls)==null?void 0:d.includes("fullscreen"),V=S||R||C||M||D||I||G||F,z=[`level-${(u=this.level)==null?void 0:u.toString()}`,`playback-rate-${this.playbackRate.toString()}`,this.captions&&"captions",this.fullscreen&&"fullscreen"].filter(Boolean);return st`
976
964
  <div
977
965
  ${this.resizeHider.measure()}
978
966
  ${this.resizeHider.contain()}
979
- class=${ht({container:!0,hidden:!A&&!F})}
967
+ class=${wt({container:!0,hidden:!L&&!V})}
980
968
  >
981
969
  <div
982
- class=${ht({"scrubber-container":!0,hidden:!A})}
970
+ class=${wt({"scrubber-container":!0,hidden:!L})}
983
971
  >
984
972
  <vmp-new-progress-scrubber
985
- class=${ht({scrubber:!0,invisible:this.volumeMenuOpen||this.levelsMenuOpen||this.playbackRateMenuOpen||this.settingsMenuOpen})}
973
+ class=${wt({scrubber:!0,invisible:this.volumeMenuOpen||this.levelsMenuOpen||this.playbackRateMenuOpen||this.settingsMenuOpen})}
986
974
  duration=${this.duration}
987
975
  currentTime=${this.currentTime}
988
976
  .buffer=${this.buffer}
@@ -990,12 +978,12 @@ ${t}`,r0=Object.getOwnPropertyDescriptor(Function.prototype,"toString"),n0=Objec
990
978
  </div>
991
979
  <div
992
980
  ${this.resizeHider.contain()}
993
- class=${ht({buttons:!0,hidden:!F})}
981
+ class=${wt({buttons:!0,hidden:!V})}
994
982
  >
995
983
  <div class="section">
996
984
  <div
997
985
  ${this.resizeHider.hide("navigation",6)}
998
- class=${ht({navigation:!0,hidden:!y})}
986
+ class=${wt({navigation:!0,hidden:!y})}
999
987
  >
1000
988
  <vmp-new-icon-button
1001
989
  icon="arrow-left"
@@ -1011,7 +999,7 @@ ${t}`,r0=Object.getOwnPropertyDescriptor(Function.prototype,"toString"),n0=Objec
1011
999
  ></vmp-new-icon-button>
1012
1000
  </div>
1013
1001
  <vmp-new-icon-button
1014
- class=${ht({hidden:!b})}
1002
+ class=${wt({hidden:!S})}
1015
1003
  icon=${this.playing?"pause":"play"}
1016
1004
  weight="heavy"
1017
1005
  rounded="full"
@@ -1019,7 +1007,7 @@ ${t}`,r0=Object.getOwnPropertyDescriptor(Function.prototype,"toString"),n0=Objec
1019
1007
  @click=${this._handlePlayClick}
1020
1008
  ></vmp-new-icon-button>
1021
1009
  <vmp-new-volume-button
1022
- class=${ht({hidden:!S})}
1010
+ class=${wt({hidden:!R})}
1023
1011
  ?muted=${this.muted}
1024
1012
  volume=${this.volume}
1025
1013
  @menu:toggle=${this._handleVolumeMenuToggle}
@@ -1027,24 +1015,24 @@ ${t}`,r0=Object.getOwnPropertyDescriptor(Function.prototype,"toString"),n0=Objec
1027
1015
  <div class="time">
1028
1016
  <vmp-new-text
1029
1017
  ${this.resizeHider.hide("current-time",1)}
1030
- class=${ht({hidden:!R})}
1018
+ class=${wt({hidden:!C})}
1031
1019
  ?semibold=${!0}
1032
- content="${Hd(this.currentTime)}${D?"/":null}"
1020
+ content="${yc(this.currentTime)}${M?"/":null}"
1033
1021
  ></vmp-new-text>
1034
1022
  <vmp-new-text
1035
1023
  ${this.resizeHider.hide("duration",5)}
1036
- class=${ht({hidden:!D})}
1024
+ class=${wt({hidden:!M})}
1037
1025
  ?semibold=${!0}
1038
- content=${Hd(this.duration)}
1026
+ content=${yc(this.duration)}
1039
1027
  ></vmp-new-text>
1040
1028
  </div>
1041
1029
  </div>
1042
1030
  <div class="section">
1043
1031
  <vmp-new-menu
1044
1032
  ${this.resizeHider.hide("levels",0)}
1045
- class=${ht({hidden:!_||f.length<=0})}
1033
+ class=${wt({hidden:!D||f.length<=0})}
1046
1034
  .items=${p}
1047
- .activeItems=${K}
1035
+ .activeItems=${z}
1048
1036
  @menu:toggle=${this._handleLevelsMenuOpen}
1049
1037
  >
1050
1038
  <vmp-new-tooltip content="Quality" ?disabled=${this.levelsMenuOpen}>
@@ -1055,9 +1043,9 @@ ${t}`,r0=Object.getOwnPropertyDescriptor(Function.prototype,"toString"),n0=Objec
1055
1043
  </vmp-new-menu>
1056
1044
  <vmp-new-menu
1057
1045
  ${this.resizeHider.hide("playback-rate",4)}
1058
- class=${ht({hidden:!I})}
1059
- .items=${Nd}
1060
- .activeItems=${K}
1046
+ class=${wt({hidden:!I})}
1047
+ .items=${gc}
1048
+ .activeItems=${z}
1061
1049
  @menu:toggle=${this._handlePlaybackMenuToggle}
1062
1050
  >
1063
1051
  <vmp-new-tooltip content="Playback speed" ?disabled=${this.playbackRateMenuOpen}>
@@ -1068,7 +1056,7 @@ ${t}`,r0=Object.getOwnPropertyDescriptor(Function.prototype,"toString"),n0=Objec
1068
1056
  </vmp-new-menu>
1069
1057
  <vmp-new-tooltip
1070
1058
  ${this.resizeHider.hide("captions",3)}
1071
- class=${ht({hidden:!N})}
1059
+ class=${wt({hidden:!G})}
1072
1060
  content="Captions"
1073
1061
  >
1074
1062
  <vmp-new-icon-button
@@ -1081,7 +1069,7 @@ ${t}`,r0=Object.getOwnPropertyDescriptor(Function.prototype,"toString"),n0=Objec
1081
1069
  <vmp-new-tooltip
1082
1070
  ${this.resizeHider.hide("fullscreen",2)}
1083
1071
  content="Fullscreen"
1084
- class=${ht({hidden:!P})}
1072
+ class=${wt({hidden:!F})}
1085
1073
  >
1086
1074
  <vmp-new-icon-button
1087
1075
  ?active=${this.fullscreen}
@@ -1093,8 +1081,8 @@ ${t}`,r0=Object.getOwnPropertyDescriptor(Function.prototype,"toString"),n0=Objec
1093
1081
  </vmp-new-tooltip>
1094
1082
  <vmp-new-menu
1095
1083
  ${this.resizeHider.show("settings",["levels","playback-rate","captions","fullscreen"])}
1096
- .items=${T}
1097
- .activeItems=${K}
1084
+ .items=${A}
1085
+ .activeItems=${z}
1098
1086
  @menu:toggle=${this._handleSettingsMenuToggle}
1099
1087
  >
1100
1088
  <vmp-new-tooltip content="Settings" ?disabled=${this.settingsMenuOpen}>
@@ -1108,7 +1096,7 @@ ${t}`,r0=Object.getOwnPropertyDescriptor(Function.prototype,"toString"),n0=Objec
1108
1096
  </div>
1109
1097
  </div>
1110
1098
  </div>
1111
- `}};wt.styles=[ot.styles??[],Ft`
1099
+ `}};xt.styles=[yt.styles??[],jt`
1112
1100
  :host {
1113
1101
  --controls-border-radius: var(--player-border-radius, 0px);
1114
1102
 
@@ -1179,17 +1167,17 @@ ${t}`,r0=Object.getOwnPropertyDescriptor(Function.prototype,"toString"),n0=Objec
1179
1167
  .hidden {
1180
1168
  display: none;
1181
1169
  }
1182
- `],Dt([G({type:Boolean})],wt.prototype,"playing",2),Dt([G({type:Number})],wt.prototype,"volume",2),Dt([G({type:Boolean})],wt.prototype,"muted",2),Dt([G({type:Number})],wt.prototype,"currentTime",2),Dt([G({type:Number})],wt.prototype,"duration",2),Dt([G({type:Number})],wt.prototype,"level",2),Dt([G({type:Number})],wt.prototype,"playbackRate",2),Dt([G({type:Array})],wt.prototype,"buffer",2),Dt([G({type:Array,attribute:!1})],wt.prototype,"levels",2),Dt([G({type:Boolean})],wt.prototype,"captions",2),Dt([G({type:Boolean})],wt.prototype,"fullscreen",2),Dt([G({type:Array})],wt.prototype,"controls",2),Dt([Nt()],wt.prototype,"volumeMenuOpen",2),Dt([Nt()],wt.prototype,"levelsMenuOpen",2),Dt([Nt()],wt.prototype,"playbackRateMenuOpen",2),Dt([Nt()],wt.prototype,"settingsMenuOpen",2),wt=Dt([qt("vmp-new-player-controls")],wt);var K0=Object.defineProperty,j0=Object.getOwnPropertyDescriptor,W0=(r,t,e,i)=>{for(var s=i>1?void 0:i?j0(t,e):t,n=r.length-1,a;n>=0;n--)(a=r[n])&&(s=(i?a(t,e,s):a(s))||s);return i&&s&&K0(t,e,s),s};let Ma=class extends ot{render(){return J`<vmp-new-icon icon="loading"></vmp-new-icon>`}};Ma.styles=[ot.styles??[],Ft`
1170
+ `],Bt([j({type:Boolean})],xt.prototype,"playing",2),Bt([j({type:Number})],xt.prototype,"volume",2),Bt([j({type:Boolean})],xt.prototype,"muted",2),Bt([j({type:Number})],xt.prototype,"currentTime",2),Bt([j({type:Number})],xt.prototype,"duration",2),Bt([j({type:Number})],xt.prototype,"level",2),Bt([j({type:Number})],xt.prototype,"playbackRate",2),Bt([j({type:Array})],xt.prototype,"buffer",2),Bt([j({type:Array,attribute:!1})],xt.prototype,"levels",2),Bt([j({type:Boolean})],xt.prototype,"captions",2),Bt([j({type:Boolean})],xt.prototype,"fullscreen",2),Bt([j({type:Array})],xt.prototype,"controls",2),Bt([Wt()],xt.prototype,"volumeMenuOpen",2),Bt([Wt()],xt.prototype,"levelsMenuOpen",2),Bt([Wt()],xt.prototype,"playbackRateMenuOpen",2),Bt([Wt()],xt.prototype,"settingsMenuOpen",2),xt=Bt([se("vmp-new-player-controls")],xt);var l0=Object.defineProperty,h0=Object.getOwnPropertyDescriptor,c0=(r,t,e,i)=>{for(var s=i>1?void 0:i?h0(t,e):t,n=r.length-1,a;n>=0;n--)(a=r[n])&&(s=(i?a(t,e,s):a(s))||s);return i&&s&&l0(t,e,s),s};let Aa=class extends yt{render(){return st`<vmp-new-icon icon="loading"></vmp-new-icon>`}};Aa.styles=[yt.styles??[],jt`
1183
1171
  :host {
1184
1172
  display: flex;
1185
1173
  align-items: center;
1186
1174
  justify-content: center;
1187
1175
  }
1188
- `],Ma=W0([qt("vmp-new-loading-spinner")],Ma);var Y0=Object.defineProperty,z0=Object.getOwnPropertyDescriptor,Kd=(r,t,e,i)=>{for(var s=i>1?void 0:i?z0(t,e):t,n=r.length-1,a;n>=0;n--)(a=r[n])&&(s=(i?a(t,e,s):a(s))||s);return i&&s&&Y0(t,e,s),s};let Lr=class extends ot{constructor(){super(...arguments),this.caption=""}render(){return J`
1176
+ `],Aa=c0([se("vmp-new-loading-spinner")],Aa);var d0=Object.defineProperty,u0=Object.getOwnPropertyDescriptor,Tc=(r,t,e,i)=>{for(var s=i>1?void 0:i?u0(t,e):t,n=r.length-1,a;n>=0;n--)(a=r[n])&&(s=(i?a(t,e,s):a(s))||s);return i&&s&&d0(t,e,s),s};let Lr=class extends yt{constructor(){super(...arguments),this.caption=""}render(){return st`
1189
1177
  <div class="container">
1190
1178
  <vmp-new-text content=${this.caption} size="large"></vmp-new-text>
1191
1179
  </div>
1192
- `}};Lr.styles=[ot.styles??[],Ft`
1180
+ `}};Lr.styles=[yt.styles??[],jt`
1193
1181
  .container {
1194
1182
  display: block;
1195
1183
  margin: 0 var(--space-small);
@@ -1208,37 +1196,37 @@ ${t}`,r0=Object.getOwnPropertyDescriptor(Function.prototype,"toString"),n0=Objec
1208
1196
  /* Line height controls the spacing between the cloned boxes so has to override the default */
1209
1197
  line-height: 2.2;
1210
1198
  }
1211
- `],Kd([G({type:String})],Lr.prototype,"caption",2),Lr=Kd([qt("vmp-new-captions")],Lr);var q0=Object.defineProperty,X0=Object.getOwnPropertyDescriptor,$t=(r,t,e,i)=>{for(var s=i>1?void 0:i?X0(t,e):t,n=r.length-1,a;n>=0;n--)(a=r[n])&&(s=(i?a(t,e,s):a(s))||s);return i&&s&&q0(t,e,s),s};const Q0=3e3;let Rt=class extends ot{constructor(){super(...arguments),this.loading=!1,this.playing=!1,this.volume=1,this.muted=!1,this.currentTime=0,this.duration=0,this.levels=[],this.level=-1,this.playbackRate=1,this.caption="",this.buffer=[],this.captions=!1,this.fullscreen=!1,this.controls=Ca,this.showControls=!0,this._hasTouched=!1,this._playerControlsRef=de()}_startHideControls(){clearTimeout(this._controlHideTimeout),this._controlHideTimeout=setTimeout(()=>{this.showControls=!1,this._hasTouched=!1},Q0)}_immediateShowControls(){this.showControls=!0,clearTimeout(this._controlHideTimeout)}_immediateHideControls(){this.showControls=!1,this._hasTouched=!1,clearTimeout(this._controlHideTimeout)}willUpdate(r){var t;r.has("showControls")&&this.playing&&!this.showControls&&((t=this._playerControlsRef.value)==null||t.hideMenus())}render(){var r;const t=(r=this.controls)==null?void 0:r.includes("play-large"),e=this.playing&&!this.showControls,i=!!(t&&!this.playing);return J`
1199
+ `],Tc([j({type:String})],Lr.prototype,"caption",2),Lr=Tc([se("vmp-new-captions")],Lr);var f0=Object.defineProperty,p0=Object.getOwnPropertyDescriptor,Kt=(r,t,e,i)=>{for(var s=i>1?void 0:i?p0(t,e):t,n=r.length-1,a;n>=0;n--)(a=r[n])&&(s=(i?a(t,e,s):a(s))||s);return i&&s&&f0(t,e,s),s};const g0=3e3;let Mt=class extends yt{constructor(){super(...arguments),this.loading=!1,this.playing=!1,this.volume=1,this.muted=!1,this.currentTime=0,this.duration=0,this.levels=[],this.level=-1,this.playbackRate=1,this.caption="",this.buffer=[],this.captions=!1,this.fullscreen=!1,this.controls=va,this.showControls=!0,this._hasTouched=!1,this._playerControlsRef=ae()}_startHideControls(){clearTimeout(this._controlHideTimeout),this._controlHideTimeout=setTimeout(()=>{this.showControls=!1,this._hasTouched=!1},g0)}_immediateShowControls(){this.showControls=!0,clearTimeout(this._controlHideTimeout)}_immediateHideControls(){this.showControls=!1,this._hasTouched=!1,clearTimeout(this._controlHideTimeout)}willUpdate(r){var t;r.has("showControls")&&this.playing&&!this.showControls&&((t=this._playerControlsRef.value)==null||t.hideMenus())}render(){var r;const t=(r=this.controls)==null?void 0:r.includes("play-large"),e=this.playing&&!this.showControls,i=!!(t&&!this.playing);return st`
1212
1200
  <div
1213
- class=${ht({container:!0,hide:e})}
1201
+ class=${wt({container:!0,hide:e})}
1214
1202
  @mousemove=${()=>{this._immediateShowControls(),this._startHideControls()}}
1215
1203
  @mouseleave=${this._immediateHideControls}
1216
1204
  @touchstart=${s=>{this.playing&&!this.showControls&&!this._hasTouched&&(s.preventDefault(),this._hasTouched=!0,this._immediateShowControls(),this._startHideControls())}}
1217
1205
  >
1218
1206
  <div
1219
- class=${ht({fixtures:!0,invisible:!this.loading&&!i})}
1207
+ class=${wt({fixtures:!0,invisible:!this.loading&&!i})}
1220
1208
  @click=${()=>{this.showControls&&this.dispatchEvent(new CustomEvent("play:click",{bubbles:!0,composed:!0,detail:this.playing}))}}
1221
1209
  >
1222
1210
  <vmp-new-icon
1223
- class=${ht({hidden:!i})}
1211
+ class=${wt({hidden:!i})}
1224
1212
  icon="play-large"
1225
1213
  ></vmp-new-icon>
1226
1214
  <vmp-new-loading-spinner
1227
- class=${ht({hidden:!this.loading||i})}
1215
+ class=${wt({hidden:!this.loading||i})}
1228
1216
  ></vmp-new-loading-spinner>
1229
1217
  </div>
1230
1218
  <div
1231
- class=${ht({controls:!0,hide:e})}
1219
+ class=${wt({controls:!0,hide:e})}
1232
1220
  @focusin=${this._immediateShowControls}
1233
1221
  @mousemove=${s=>{s.stopPropagation(),this._immediateShowControls()}}
1234
1222
  @click=${this._immediateShowControls}
1235
1223
  >
1236
- ${this.captions?J`<vmp-new-captions
1237
- class=${ht({hidden:!this.caption,hiddenControls:e})}
1224
+ ${this.captions?st`<vmp-new-captions
1225
+ class=${wt({hidden:!this.caption,hiddenControls:e})}
1238
1226
  caption=${this.caption}
1239
1227
  ></vmp-new-captions>`:null}
1240
1228
  <vmp-new-player-controls
1241
- ${ce(this._playerControlsRef)}
1229
+ ${oe(this._playerControlsRef)}
1242
1230
  ?playing=${this.playing}
1243
1231
  ?muted=${this.muted}
1244
1232
  volume=${this.volume}
@@ -1254,7 +1242,7 @@ ${t}`,r0=Object.getOwnPropertyDescriptor(Function.prototype,"toString"),n0=Objec
1254
1242
  ></vmp-new-player-controls>
1255
1243
  </div>
1256
1244
  </div>
1257
- `}};Rt.styles=[ot.styles??[],Ft`
1245
+ `}};Mt.styles=[yt.styles??[],jt`
1258
1246
  :host {
1259
1247
  --overlay-border-radius: var(--player-border-radius, 0px);
1260
1248
  }
@@ -1326,16 +1314,16 @@ ${t}`,r0=Object.getOwnPropertyDescriptor(Function.prototype,"toString"),n0=Objec
1326
1314
  vmp-new-captions.hiddenControls {
1327
1315
  transform: translateY(calc(var(--space-small) * -1));
1328
1316
  }
1329
- `],$t([G({type:Boolean})],Rt.prototype,"loading",2),$t([G({type:Boolean})],Rt.prototype,"playing",2),$t([G({type:Number})],Rt.prototype,"volume",2),$t([G({type:Boolean})],Rt.prototype,"muted",2),$t([G({type:Number})],Rt.prototype,"currentTime",2),$t([G({type:Number})],Rt.prototype,"duration",2),$t([G({type:Array,attribute:!1})],Rt.prototype,"levels",2),$t([G({type:Number})],Rt.prototype,"level",2),$t([G({type:Number})],Rt.prototype,"playbackRate",2),$t([G({type:String})],Rt.prototype,"caption",2),$t([G({type:Array})],Rt.prototype,"buffer",2),$t([G({type:Boolean})],Rt.prototype,"captions",2),$t([G({type:Boolean})],Rt.prototype,"fullscreen",2),$t([G({type:Array})],Rt.prototype,"controls",2),$t([Nt()],Rt.prototype,"showControls",2),Rt=$t([qt("vmp-new-player-overlay")],Rt);var Z0=Object.defineProperty,J0=Object.getOwnPropertyDescriptor,_t=(r,t,e,i)=>{for(var s=i>1?void 0:i?J0(t,e):t,n=r.length-1,a;n>=0;n--)(a=r[n])&&(s=(i?a(t,e,s):a(s))||s);return i&&s&&Z0(t,e,s),s};let vt=class extends ot{constructor(){super(...arguments),this.burnCaptions=!1,this.propAspectRatio=0,this.preload="auto",this.autoplay=!1,this.loading=!1,this.compilation=_u,this._sceneController=new u0(this),this._drawController=new Cp(this),this._wasPlaying=!1,this._manualMute=this.muted,this._seekerRAF=null,this._lastWaiting=!1,this._lastTimestamp=null,this._lastTimeUpdate=null,this._playerRef=de(),this._canvasRef=de(),this._aspectRatio=this.propAspectRatio,this._waiting=!1,this._stalled=!1,this._seeking=!1,this._captions=!1,this._fullscreen=!1,this._paused=!0,this._playbackRate=1,this._volume=null,this._muted=null,this._videoResolution=-1,this._handleContainerResize=()=>{this._playerRef.value&&(this.propAspectRatio||(this._aspectRatio=this._playerRef.value.offsetWidth/this._playerRef.value.offsetHeight))},this._handleCanvasResize=()=>{this.draw()},this._seeker=r=>{var t;this.sceneConfig&&this.scenes.length>0&&(this._waiting=this._drawController.activeScenes.some(({video:e})=>{if(e){const i=this._sceneController.videoState[e.id];return!i||!i.initialised||i.waiting}}),this.waiting?(this._lastTimestamp=null,this._lastWaiting||this.dispatchEvent(new CustomEvent("waiting"))):this._lastWaiting&&this.dispatchEvent(new CustomEvent("playing")),!this.stalled&&r-(this._lastTimestamp??0)>1e3/this.sceneConfig.frameRate&&(this._drawController.currentTime=this._drawController.currentTime+(r-(this._lastTimestamp??r))/1e3*this.playbackRate,this._lastTimestamp=r),this._lastWaiting=this._waiting,this._drawController.currentTime>=this.duration&&(this.pause(),this.dispatchEvent(new CustomEvent("ended")))),this.paused||((t=this.scene)!=null&&t.video?this._lastTimeUpdate&&r-this._lastTimeUpdate>1e3&&(this._stalled=!0):(this._stalled=!1,this._lastTimeUpdate=r),this._seekerRAF=requestAnimationFrame(this._seeker))},this._handleFullscreenChange=()=>{document.fullscreenElement?this._fullscreen=!0:this._fullscreen=!1}}get aspectRatio(){return this._aspectRatio}get waiting(){return!this.paused&&this._waiting}get stalled(){return this._stalled}get seeking(){return this._seeking}get captions(){return this._captions}get fullscreen(){return this._fullscreen}get processing(){return this._sceneController.processing}get duration(){return this._sceneController.duration}get scene(){return this._drawController.activeScenes[this._drawController.activeScenes.length-1]}get scenes(){var r;return((r=this._sceneController.scenes)==null?void 0:r.scenes)??[]}get sceneConfig(){return this._sceneController.scenes}get videos(){return this._sceneController.videos??{}}get videoState(){return this._sceneController.videoState}set paused(r){r!==this._paused&&(this._paused=r,this.requestUpdate(),this.dispatchEvent(new CustomEvent(r?"pause":"play")))}get paused(){return this._paused}set playbackRate(r){r!==this._playbackRate&&(this._playbackRate=r,this.scenes.forEach(({video:t})=>{t&&(t.node.playbackRate=r)}),this.requestUpdate(),this.dispatchEvent(new CustomEvent("ratechange",{detail:r})))}get playbackRate(){return this._playbackRate}set volume(r){const t=Math.min(1,Math.max(0,r));t!==this._volume&&(this.scenes.forEach(({video:e})=>{e&&(e.node.volume=t)}),localStorage.setItem("vmp-new-player-volume",t.toString()),this._volume=t,t>0&&(this.muted=!1),this.requestUpdate(),this.dispatchEvent(new CustomEvent("volumechange",{detail:r})))}get volume(){return this._volume??(this._volume=parseFloat(localStorage.getItem("vmp-new-player-volume")??"1"))}set muted(r){this.scenes.forEach(({video:t})=>{t&&(t.node.muted=r)}),r!==this._muted&&(this._muted=r,localStorage.setItem("vmp-new-player-muted",r.toString()),this.requestUpdate(),this.dispatchEvent(new CustomEvent("volumechange",{detail:r?0:this.volume})))}get muted(){return this._muted??(this._muted=this.autoplay||localStorage.getItem("vmp-new-player-muted")==="true")}set videoResolution(r){r!==this._videoResolution&&(this._videoResolution=r,this.scenes.forEach(({video:t})=>{if(t!=null&&t.hls){const e=t.hls.levels.findIndex(i=>Math.min(i.height,i.width)===r);t.hls.currentLevel=e??-1}}),this.requestUpdate())}get videoResolution(){return this._videoResolution}set currentTime(r){r!==this._drawController.currentTime&&(this._drawController.currentTime=r,this._sceneController.setVideosCurrentTime(r))}get currentTime(){return this._drawController.currentTime}reset(r=0,t=!1){this._lastTimestamp=null,this._drawController.currentTime=r,this._sceneController.setVideosCurrentTime(r),t?this.play():this.pause()}clear(){this._drawController.clear()}play(){this.paused=!1,this._lastTimestamp=null,this._lastTimeUpdate=1/0,this.duration>0&&this._drawController.currentTime>=this.duration&&this.reset(0,!0),this._seekerRAF||(this._seekerRAF=requestAnimationFrame(this._seeker))}pause(){this._seekerRAF&&(cancelAnimationFrame(this._seekerRAF),this._seekerRAF=null),this.paused=!0,this.scenes.forEach(({video:r})=>{r&&r.node.pause()})}draw(r){return this._drawController.draw(r)}setScene(r){var t,e;if((t=this._sceneController)!=null&&t.scenes){const i=(e=this.scenes)==null?void 0:e[r];if(!i)return this.dispatchEvent(new ErrorEvent("error",new Error(`No scene at index: ${r}`)));this.reset(i.start+this._sceneController.scenes.transitionDuration,!this.paused)}}toggleFullscreen(r){r??this.fullscreen?p0():this._playerRef.value&&f0(this._playerRef.value)}connectedCallback(){super.connectedCallback(),document.addEventListener("fullscreenchange",this._handleFullscreenChange),this.addEventListener("video:timeupdate",r=>{this._stalled=!1,this._lastTimeUpdate=r.timeStamp})}willUpdate(){this.propAspectRatio&&(this._aspectRatio=this.propAspectRatio)}updated(r){r.has("_stalled")&&this.stalled&&this.dispatchEvent(new CustomEvent("stalled")),r.has("propAspectRatio")&&!this.propAspectRatio&&this._handleContainerResize()}disconnectedCallback(){super.disconnectedCallback(),document.removeEventListener("fullscreenchange",this._handleFullscreenChange)}render(){var r,t,e,i,s,n;const a=this.loading||!this.scenes||this.duration<=0,{height:o,width:l}=gi({resolution:((r=this.sceneConfig)==null?void 0:r.resolution)??720,aspectRatio:this.aspectRatio}),h=Object.keys(this.videoState).reduce((p,g)=>p.concat(this.videoState[g].buffered??[]),[...this._drawController.fakeBufferSegments]),d=a?[]:(t=this.controls??Ca)==null?void 0:t.filter(p=>!(p==="fullscreen"&&d0()||p==="navigation"&&(!this.scenes||this.scenes.length<=1))),c=(((e=this.scenes)==null?void 0:e.length)??0)-1,u=((i=this.scenes)==null?void 0:i.findIndex(p=>p===this._drawController.activeScenes[0]))??0,f=(n=(s=this._drawController.activeScenes[0])==null?void 0:s.video)==null?void 0:n.hls;return J`
1317
+ `],Kt([j({type:Boolean})],Mt.prototype,"loading",2),Kt([j({type:Boolean})],Mt.prototype,"playing",2),Kt([j({type:Number})],Mt.prototype,"volume",2),Kt([j({type:Boolean})],Mt.prototype,"muted",2),Kt([j({type:Number})],Mt.prototype,"currentTime",2),Kt([j({type:Number})],Mt.prototype,"duration",2),Kt([j({type:Array,attribute:!1})],Mt.prototype,"levels",2),Kt([j({type:Number})],Mt.prototype,"level",2),Kt([j({type:Number})],Mt.prototype,"playbackRate",2),Kt([j({type:String})],Mt.prototype,"caption",2),Kt([j({type:Array})],Mt.prototype,"buffer",2),Kt([j({type:Boolean})],Mt.prototype,"captions",2),Kt([j({type:Boolean})],Mt.prototype,"fullscreen",2),Kt([j({type:Array})],Mt.prototype,"controls",2),Kt([Wt()],Mt.prototype,"showControls",2),Mt=Kt([se("vmp-new-player-overlay")],Mt);var m0=Object.defineProperty,v0=Object.getOwnPropertyDescriptor,Ft=(r,t,e,i)=>{for(var s=i>1?void 0:i?v0(t,e):t,n=r.length-1,a;n>=0;n--)(a=r[n])&&(s=(i?a(t,e,s):a(s))||s);return i&&s&&m0(t,e,s),s};let It=class extends yt{constructor(){super(...arguments),this.burnCaptions=!1,this.propAspectRatio=0,this.preload="auto",this.autoplay=!1,this.loading=!1,this.compilation=lu,this._sceneController=new Cv(this),this._drawController=new ip(this),this._wasPlaying=!1,this._manualMute=this.muted,this._seekerRAF=null,this._lastWaiting=!1,this._lastTimestamp=null,this._lastTimeUpdate=null,this._playerRef=ae(),this._canvasRef=ae(),this._aspectRatio=this.propAspectRatio,this._waiting=!1,this._stalled=!1,this._seeking=!1,this._captions=!1,this._fullscreen=!1,this._paused=!0,this._playbackRate=1,this._volume=null,this._muted=null,this._videoResolution=-1,this._handleContainerResize=()=>{this._playerRef.value&&(this.propAspectRatio||(this._aspectRatio=this._playerRef.value.offsetWidth/this._playerRef.value.offsetHeight))},this._handleCanvasResize=()=>{this.draw()},this._seeker=r=>{var t;this.sceneConfig&&this.scenes.length>0&&(this._waiting=this._drawController.activeScenes.some(({video:e})=>{if(e){const i=this._sceneController.videoState[e.id];return!i||!i.initialised||i.waiting}}),this.waiting?(this._lastTimestamp=null,this._lastWaiting||this.dispatchEvent(new CustomEvent("waiting"))):this._lastWaiting&&this.dispatchEvent(new CustomEvent("playing")),!this.stalled&&r-(this._lastTimestamp??0)>1e3/this.sceneConfig.frameRate&&(this._drawController.currentTime=this._drawController.currentTime+(r-(this._lastTimestamp??r))/1e3*this.playbackRate,this._lastTimestamp=r),this._lastWaiting=this._waiting,this._drawController.currentTime>=this.duration&&(this.pause(),this.dispatchEvent(new CustomEvent("ended")))),this.paused||((t=this.scene)!=null&&t.video?this._lastTimeUpdate&&r-this._lastTimeUpdate>1e3&&(this._stalled=!0):(this._stalled=!1,this._lastTimeUpdate=r),this._seekerRAF=requestAnimationFrame(this._seeker))},this._handleFullscreenChange=()=>{document.fullscreenElement?this._fullscreen=!0:this._fullscreen=!1}}get aspectRatio(){return this._aspectRatio}get waiting(){return!this.paused&&this._waiting}get stalled(){return this._stalled}get seeking(){return this._seeking}get captions(){return this._captions}get fullscreen(){return this._fullscreen}get processing(){return this._sceneController.processing}get duration(){return this._sceneController.duration}get scene(){return this._drawController.activeScenes[this._drawController.activeScenes.length-1]}get scenes(){var r;return((r=this._sceneController.scenes)==null?void 0:r.scenes)??[]}get sceneConfig(){return this._sceneController.scenes}get videos(){return this._sceneController.videos??{}}get videoState(){return this._sceneController.videoState}set paused(r){r!==this._paused&&(this._paused=r,this.requestUpdate(),this.dispatchEvent(new CustomEvent(r?"pause":"play")))}get paused(){return this._paused}set playbackRate(r){r!==this._playbackRate&&(this._playbackRate=r,this.scenes.forEach(({video:t})=>{t&&(t.node.playbackRate=r)}),this.requestUpdate(),this.dispatchEvent(new CustomEvent("ratechange",{detail:r})))}get playbackRate(){return this._playbackRate}set volume(r){const t=Math.min(1,Math.max(0,r));t!==this._volume&&(this.scenes.forEach(({video:e})=>{e&&(e.node.volume=t)}),localStorage.setItem("vmp-new-player-volume",t.toString()),this._volume=t,t>0&&(this.muted=!1),this.requestUpdate(),this.dispatchEvent(new CustomEvent("volumechange",{detail:r})))}get volume(){return this._volume??(this._volume=parseFloat(localStorage.getItem("vmp-new-player-volume")??"1"))}set muted(r){this.scenes.forEach(({video:t})=>{t&&(t.node.muted=r)}),r!==this._muted&&(this._muted=r,localStorage.setItem("vmp-new-player-muted",r.toString()),this.requestUpdate(),this.dispatchEvent(new CustomEvent("volumechange",{detail:r?0:this.volume})))}get muted(){return this._muted??(this._muted=this.autoplay||localStorage.getItem("vmp-new-player-muted")==="true")}set videoResolution(r){r!==this._videoResolution&&(this._videoResolution=r,this.scenes.forEach(({video:t})=>{if(t!=null&&t.hls){const e=t.hls.levels.findIndex(i=>Math.min(i.height,i.width)===r);t.hls.currentLevel=e??-1}}),this.requestUpdate())}get videoResolution(){return this._videoResolution}set currentTime(r){r!==this._drawController.currentTime&&(this._drawController.currentTime=r,this._sceneController.setVideosCurrentTime(r))}get currentTime(){return this._drawController.currentTime}reset(r=0,t=!1){this._lastTimestamp=null,this._drawController.currentTime=r,this._sceneController.setVideosCurrentTime(r),t?this.play():this.pause()}clear(){this._drawController.clear()}play(){this.paused=!1,this._lastTimestamp=null,this._lastTimeUpdate=1/0,this.duration>0&&this._drawController.currentTime>=this.duration&&this.reset(0,!0),this._seekerRAF||(this._seekerRAF=requestAnimationFrame(this._seeker))}pause(){this._seekerRAF&&(cancelAnimationFrame(this._seekerRAF),this._seekerRAF=null),this.paused=!0,this.scenes.forEach(({video:r})=>{r&&r.node.pause()})}draw(r){return this._drawController.draw(r)}setScene(r){var t,e;if((t=this._sceneController)!=null&&t.scenes){const i=(e=this.scenes)==null?void 0:e[r];if(!i)return this.dispatchEvent(new ErrorEvent("error",new Error(`No scene at index: ${r}`)));this.reset(i.start+this._sceneController.scenes.transitionDuration,!this.paused)}}toggleFullscreen(r){r??this.fullscreen?xv():this._playerRef.value&&Dv(this._playerRef.value)}connectedCallback(){super.connectedCallback(),document.addEventListener("fullscreenchange",this._handleFullscreenChange),this.addEventListener("video:timeupdate",r=>{this._stalled=!1,this._lastTimeUpdate=r.timeStamp})}willUpdate(){this.propAspectRatio&&(this._aspectRatio=this.propAspectRatio)}updated(r){r.has("_stalled")&&this.stalled&&this.dispatchEvent(new CustomEvent("stalled")),r.has("propAspectRatio")&&!this.propAspectRatio&&this._handleContainerResize()}disconnectedCallback(){super.disconnectedCallback(),document.removeEventListener("fullscreenchange",this._handleFullscreenChange)}render(){var r,t,e,i,s,n;const a=this.loading||!this.scenes||this.duration<=0,{height:o,width:l}=Ai({resolution:((r=this.sceneConfig)==null?void 0:r.resolution)??720,aspectRatio:this.aspectRatio}),h=Object.keys(this.videoState).reduce((p,g)=>p.concat(this.videoState[g].buffered??[]),[...this._drawController.fakeBufferSegments]),c=a?[]:(t=this.controls??va)==null?void 0:t.filter(p=>!(p==="fullscreen"&&_v()||p==="navigation"&&(!this.scenes||this.scenes.length<=1))),d=(((e=this.scenes)==null?void 0:e.length)??0)-1,u=((i=this.scenes)==null?void 0:i.findIndex(p=>p===this._drawController.activeScenes[0]))??0,f=(n=(s=this._drawController.activeScenes[0])==null?void 0:s.video)==null?void 0:n.hls;return st`
1330
1318
  <div
1331
- ${ce(this._playerRef)}
1332
- ${Da(this._handleContainerResize)}
1333
- class=${ht({player:!0,responsive:!this.propAspectRatio})}
1319
+ ${oe(this._playerRef)}
1320
+ ${ya(this._handleContainerResize)}
1321
+ class=${wt({player:!0,responsive:!this.propAspectRatio})}
1334
1322
  >
1335
1323
  <canvas
1336
- ${ce(this._canvasRef)}
1324
+ ${oe(this._canvasRef)}
1337
1325
  ${this._drawController.canvas()}
1338
- ${Da(this._handleCanvasResize)}
1326
+ ${ya(this._handleCanvasResize)}
1339
1327
  height=${o}
1340
1328
  width=${l}
1341
1329
  ></canvas>
@@ -1348,15 +1336,15 @@ ${t}`,r0=Object.getOwnPropertyDescriptor(Function.prototype,"toString"),n0=Objec
1348
1336
  volume=${this.volume}
1349
1337
  duration=${this.duration}
1350
1338
  .levels=${(f==null?void 0:f.levels)??[]}
1351
- level=${Ji(f!=null&&f.autoLevelEnabled?-1:f==null?void 0:f.currentLevel)}
1339
+ level=${ri(f!=null&&f.autoLevelEnabled?-1:f==null?void 0:f.currentLevel)}
1352
1340
  playbackRate=${this.playbackRate}
1353
1341
  caption=${this._drawController.caption}
1354
1342
  .buffer=${h}
1355
- .controls=${d}
1343
+ .controls=${c}
1356
1344
  ?captions=${this.captions}
1357
1345
  ?fullscreen=${this.fullscreen}
1358
- @navigate:back=${p=>{p.defaultPrevented||this.setScene(u<=0?c:u-1)}}
1359
- @navigate:forward=${p=>{p.defaultPrevented||this.setScene(u>=c?0:u+1)}}
1346
+ @navigate:back=${p=>{p.defaultPrevented||this.setScene(u<=0?d:u-1)}}
1347
+ @navigate:forward=${p=>{p.defaultPrevented||this.setScene(u>=d?0:u+1)}}
1360
1348
  @play:click=${({detail:p})=>{a||(p?this.pause():(this.muted=this._manualMute,this.play()))}}
1361
1349
  @volume:click=${({detail:p})=>{this.muted=!p,this._manualMute=!p}}
1362
1350
  @level:click=${({detail:p})=>{this.videoResolution=p.value.resolution}}
@@ -1368,7 +1356,7 @@ ${t}`,r0=Object.getOwnPropertyDescriptor(Function.prototype,"toString"),n0=Objec
1368
1356
  @pointerup=${p=>{p.composedPath()[0].getAttribute("key")==="scrubber"&&(this._seeking=!1,this._wasPlaying&&(this.play(),this._wasPlaying=!1),this.dispatchEvent(new CustomEvent("seeked",{detail:this._drawController.currentTime})))}}
1369
1357
  ></vmp-new-player-overlay>
1370
1358
  </div>
1371
- `}};vt.styles=[ot.styles??[],Ft`
1359
+ `}};It.styles=[yt.styles??[],jt`
1372
1360
  :host {
1373
1361
  --player-border-radius: var(--vouch-media-player-border-radius, 0px);
1374
1362
  }
@@ -1401,17 +1389,17 @@ ${t}`,r0=Object.getOwnPropertyDescriptor(Function.prototype,"toString"),n0=Objec
1401
1389
  right: 0;
1402
1390
  bottom: 0;
1403
1391
  }
1404
- `],_t([G({type:Object})],vt.prototype,"data",2),_t([G({type:Object})],vt.prototype,"template",2),_t([G({type:Boolean})],vt.prototype,"burnCaptions",2),_t([G({type:String})],vt.prototype,"src",2),_t([G({type:String})],vt.prototype,"track",2),_t([G({type:Number,attribute:"aspectratio"})],vt.prototype,"propAspectRatio",2),_t([G({type:String})],vt.prototype,"preload",2),_t([G({type:Boolean})],vt.prototype,"autoplay",2),_t([G({type:Boolean})],vt.prototype,"loading",2),_t([G({type:Array})],vt.prototype,"controls",2),_t([G({attribute:!1})],vt.prototype,"compilation",2),_t([Nt()],vt.prototype,"_aspectRatio",2),_t([Nt()],vt.prototype,"_waiting",2),_t([Nt()],vt.prototype,"_stalled",2),_t([Nt()],vt.prototype,"_seeking",2),_t([Nt()],vt.prototype,"_captions",2),_t([Nt()],vt.prototype,"_fullscreen",2),vt=_t([qt("vmp-new-media-player")],vt);var ty=Object.defineProperty,ey=Object.getOwnPropertyDescriptor,ie=(r,t,e,i)=>{for(var s=i>1?void 0:i?ey(t,e):t,n=r.length-1,a;n>=0;n--)(a=r[n])&&(s=(i?a(t,e,s):a(s))||s);return i&&s&&ty(t,e,s),s};ut.Embed=class extends pi{constructor(){super(...arguments),this._mediaPlayerRef=Io(),this.env="prod",this.apiKey="",this.preload="auto",this.autoplay=!1,this.aspectRatio=0,this.eventController=new xc(this,["durationchange","ended","error","loadeddata","pause","stalled","play","playing","ratechange","scenechange","seeking","seeked","timeupdate","volumechange","waiting","video:loadeddata","video:seeked","video:play","video:playing","video:pause","video:stalled","video:timeupdate","video:ended","video:error"]),this._fetcherController=new su(this),this._trackingController=new lu(this)}get fetching(){return this._fetcherController.fetching}get waiting(){var t;return(t=this._mediaPlayerRef.value)==null?void 0:t.waiting}get seeking(){var t;return(t=this._mediaPlayerRef.value)==null?void 0:t.seeking}get paused(){var t;return(t=this._mediaPlayerRef.value)==null?void 0:t.paused}get captions(){var t;return(t=this._mediaPlayerRef.value)==null?void 0:t.captions}get fullscreen(){var t;return(t=this._mediaPlayerRef.value)==null?void 0:t.fullscreen}get duration(){var t;return(t=this._mediaPlayerRef.value)==null?void 0:t.duration}set currentTime(t){this._mediaPlayerRef.value&&(this._mediaPlayerRef.value.currentTime=t)}get currentTime(){var t;return((t=this._mediaPlayerRef.value)==null?void 0:t.currentTime)??0}set playbackRate(t){this._mediaPlayerRef.value&&(this._mediaPlayerRef.value.playbackRate=t)}get playbackRate(){var t;return((t=this._mediaPlayerRef.value)==null?void 0:t.playbackRate)??1}set volume(t){this._mediaPlayerRef.value&&(this._mediaPlayerRef.value.volume=t)}get volume(){var t;return((t=this._mediaPlayerRef.value)==null?void 0:t.volume)??1}set muted(t){this._mediaPlayerRef.value&&(this._mediaPlayerRef.value.muted=t)}get muted(){var t;return((t=this._mediaPlayerRef.value)==null?void 0:t.muted)??!1}get scene(){var t;return((t=this._mediaPlayerRef.value)==null?void 0:t.scene)??null}get scenes(){var t;return((t=this._mediaPlayerRef.value)==null?void 0:t.scenes)??[]}get videoState(){var t;return(t=this._mediaPlayerRef.value)==null?void 0:t.videoState}get mediaPlayer(){return this._mediaPlayerRef.value}play(){var t;(t=this._mediaPlayerRef.value)==null||t.play()}pause(){var t;(t=this._mediaPlayerRef.value)==null||t.pause()}setScene(t){var e;(e=this._mediaPlayerRef.value)==null||e.setScene(t)}render(){return J`
1392
+ `],Ft([j({type:Object})],It.prototype,"data",2),Ft([j({type:Object})],It.prototype,"template",2),Ft([j({type:Boolean})],It.prototype,"burnCaptions",2),Ft([j({type:String})],It.prototype,"src",2),Ft([j({type:String})],It.prototype,"track",2),Ft([j({type:Number,attribute:"aspectratio"})],It.prototype,"propAspectRatio",2),Ft([j({type:String})],It.prototype,"preload",2),Ft([j({type:Boolean})],It.prototype,"autoplay",2),Ft([j({type:Boolean})],It.prototype,"loading",2),Ft([j({type:Array})],It.prototype,"controls",2),Ft([j({attribute:!1})],It.prototype,"compilation",2),Ft([Wt()],It.prototype,"_aspectRatio",2),Ft([Wt()],It.prototype,"_waiting",2),Ft([Wt()],It.prototype,"_stalled",2),Ft([Wt()],It.prototype,"_seeking",2),Ft([Wt()],It.prototype,"_captions",2),Ft([Wt()],It.prototype,"_fullscreen",2),It=Ft([se("vmp-new-media-player")],It);var y0=Object.defineProperty,E0=Object.getOwnPropertyDescriptor,re=(r,t,e,i)=>{for(var s=i>1?void 0:i?E0(t,e):t,n=r.length-1,a;n>=0;n--)(a=r[n])&&(s=(i?a(t,e,s):a(s))||s);return i&&s&&y0(t,e,s),s};At.Embed=class extends Ti{constructor(){super(...arguments),this._mediaPlayerRef=ae(),this.env="prod",this.apiKey="",this.trackingSource="embed",this.preload="auto",this.autoplay=!1,this.aspectRatio=0,this.eventController=new Sd(this,["durationchange","ended","error","loadeddata","pause","stalled","play","playing","ratechange","scenechange","seeking","seeked","timeupdate","volumechange","waiting","video:loadeddata","video:seeked","video:play","video:playing","video:pause","video:stalled","video:timeupdate","video:ended","video:error"]),this._fetcherController=new jd(this),this._trackingController=new Xd(this)}get fetching(){return this._fetcherController.fetching}get waiting(){var t;return(t=this._mediaPlayerRef.value)==null?void 0:t.waiting}get seeking(){var t;return(t=this._mediaPlayerRef.value)==null?void 0:t.seeking}get paused(){var t;return(t=this._mediaPlayerRef.value)==null?void 0:t.paused}get captions(){var t;return(t=this._mediaPlayerRef.value)==null?void 0:t.captions}get fullscreen(){var t;return(t=this._mediaPlayerRef.value)==null?void 0:t.fullscreen}get duration(){var t;return(t=this._mediaPlayerRef.value)==null?void 0:t.duration}set currentTime(t){this._mediaPlayerRef.value&&(this._mediaPlayerRef.value.currentTime=t)}get currentTime(){var t;return((t=this._mediaPlayerRef.value)==null?void 0:t.currentTime)??0}set playbackRate(t){this._mediaPlayerRef.value&&(this._mediaPlayerRef.value.playbackRate=t)}get playbackRate(){var t;return((t=this._mediaPlayerRef.value)==null?void 0:t.playbackRate)??1}set volume(t){this._mediaPlayerRef.value&&(this._mediaPlayerRef.value.volume=t)}get volume(){var t;return((t=this._mediaPlayerRef.value)==null?void 0:t.volume)??1}set muted(t){this._mediaPlayerRef.value&&(this._mediaPlayerRef.value.muted=t)}get muted(){var t;return((t=this._mediaPlayerRef.value)==null?void 0:t.muted)??!1}get scene(){var t;return((t=this._mediaPlayerRef.value)==null?void 0:t.scene)??null}get scenes(){var t;return((t=this._mediaPlayerRef.value)==null?void 0:t.scenes)??[]}get videoState(){var t;return(t=this._mediaPlayerRef.value)==null?void 0:t.videoState}get mediaPlayer(){return this._mediaPlayerRef.value}play(){var t;(t=this._mediaPlayerRef.value)==null||t.play()}pause(){var t;(t=this._mediaPlayerRef.value)==null||t.pause()}setScene(t){var e;(e=this._mediaPlayerRef.value)==null||e.setScene(t)}render(){return st`
1405
1393
  <vmp-new-media-player
1406
- ${ko(this._mediaPlayerRef)}
1394
+ ${oe(this._mediaPlayerRef)}
1407
1395
  ${this.eventController.register()}
1408
1396
  ?autoplay=${this.autoplay}
1409
1397
  ?loading=${this.fetching}
1410
1398
  .data=${this.vouch}
1411
1399
  .template=${this.template}
1412
- aspectRatio=${Ro(this.aspectRatio)}
1413
- preload=${Ro(this.preload)}
1400
+ aspectRatio=${ri(this.aspectRatio)}
1401
+ preload=${ri(this.preload)}
1414
1402
  .controls=${this.controls}
1415
1403
  ></vmp-new-media-player>
1416
- `}},ie([G({type:Object,attribute:"data"})],ut.Embed.prototype,"data",2),ie([G({type:String})],ut.Embed.prototype,"vouchId",2),ie([G({type:String})],ut.Embed.prototype,"templateId",2),ie([G({type:String})],ut.Embed.prototype,"env",2),ie([G({type:String})],ut.Embed.prototype,"apiKey",2),ie([G({type:Array})],ut.Embed.prototype,"controls",2),ie([G({type:String})],ut.Embed.prototype,"preload",2),ie([G({type:Boolean})],ut.Embed.prototype,"autoplay",2),ie([G({type:Number})],ut.Embed.prototype,"aspectRatio",2),ie([Nt()],ut.Embed.prototype,"vouch",2),ie([Nt()],ut.Embed.prototype,"template",2),ut.Embed=ie([Ec("vouch-embed")],ut.Embed);function Ee(r){if(typeof r!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(r))}function jd(r,t){for(var e="",i=0,s=-1,n=0,a,o=0;o<=r.length;++o){if(o<r.length)a=r.charCodeAt(o);else{if(a===47)break;a=47}if(a===47){if(!(s===o-1||n===1))if(s!==o-1&&n===2){if(e.length<2||i!==2||e.charCodeAt(e.length-1)!==46||e.charCodeAt(e.length-2)!==46){if(e.length>2){var l=e.lastIndexOf("/");if(l!==e.length-1){l===-1?(e="",i=0):(e=e.slice(0,l),i=e.length-1-e.lastIndexOf("/")),s=o,n=0;continue}}else if(e.length===2||e.length===1){e="",i=0,s=o,n=0;continue}}t&&(e.length>0?e+="/..":e="..",i=2)}else e.length>0?e+="/"+r.slice(s+1,o):e=r.slice(s+1,o),i=o-s-1;s=o,n=0}else a===46&&n!==-1?++n:n=-1}return e}function iy(r,t){var e=t.dir||t.root,i=t.base||(t.name||"")+(t.ext||"");return e?e===t.root?e+i:e+r+i:i}var Ci={resolve:function(){for(var t="",e=!1,i,s=arguments.length-1;s>=-1&&!e;s--){var n;s>=0?n=arguments[s]:(i===void 0&&(i=process.cwd()),n=i),Ee(n),n.length!==0&&(t=n+"/"+t,e=n.charCodeAt(0)===47)}return t=jd(t,!e),e?t.length>0?"/"+t:"/":t.length>0?t:"."},normalize:function(t){if(Ee(t),t.length===0)return".";var e=t.charCodeAt(0)===47,i=t.charCodeAt(t.length-1)===47;return t=jd(t,!e),t.length===0&&!e&&(t="."),t.length>0&&i&&(t+="/"),e?"/"+t:t},isAbsolute:function(t){return Ee(t),t.length>0&&t.charCodeAt(0)===47},join:function(){if(arguments.length===0)return".";for(var t,e=0;e<arguments.length;++e){var i=arguments[e];Ee(i),i.length>0&&(t===void 0?t=i:t+="/"+i)}return t===void 0?".":Ci.normalize(t)},relative:function(t,e){if(Ee(t),Ee(e),t===e||(t=Ci.resolve(t),e=Ci.resolve(e),t===e))return"";for(var i=1;i<t.length&&t.charCodeAt(i)===47;++i);for(var s=t.length,n=s-i,a=1;a<e.length&&e.charCodeAt(a)===47;++a);for(var o=e.length,l=o-a,h=n<l?n:l,d=-1,c=0;c<=h;++c){if(c===h){if(l>h){if(e.charCodeAt(a+c)===47)return e.slice(a+c+1);if(c===0)return e.slice(a+c)}else n>h&&(t.charCodeAt(i+c)===47?d=c:c===0&&(d=0));break}var u=t.charCodeAt(i+c),f=e.charCodeAt(a+c);if(u!==f)break;u===47&&(d=c)}var p="";for(c=i+d+1;c<=s;++c)(c===s||t.charCodeAt(c)===47)&&(p.length===0?p+="..":p+="/..");return p.length>0?p+e.slice(a+d):(a+=d,e.charCodeAt(a)===47&&++a,e.slice(a))},_makeLong:function(t){return t},dirname:function(t){if(Ee(t),t.length===0)return".";for(var e=t.charCodeAt(0),i=e===47,s=-1,n=!0,a=t.length-1;a>=1;--a)if(e=t.charCodeAt(a),e===47){if(!n){s=a;break}}else n=!1;return s===-1?i?"/":".":i&&s===1?"//":t.slice(0,s)},basename:function(t,e){if(e!==void 0&&typeof e!="string")throw new TypeError('"ext" argument must be a string');Ee(t);var i=0,s=-1,n=!0,a;if(e!==void 0&&e.length>0&&e.length<=t.length){if(e.length===t.length&&e===t)return"";var o=e.length-1,l=-1;for(a=t.length-1;a>=0;--a){var h=t.charCodeAt(a);if(h===47){if(!n){i=a+1;break}}else l===-1&&(n=!1,l=a+1),o>=0&&(h===e.charCodeAt(o)?--o===-1&&(s=a):(o=-1,s=l))}return i===s?s=l:s===-1&&(s=t.length),t.slice(i,s)}else{for(a=t.length-1;a>=0;--a)if(t.charCodeAt(a)===47){if(!n){i=a+1;break}}else s===-1&&(n=!1,s=a+1);return s===-1?"":t.slice(i,s)}},extname:function(t){Ee(t);for(var e=-1,i=0,s=-1,n=!0,a=0,o=t.length-1;o>=0;--o){var l=t.charCodeAt(o);if(l===47){if(!n){i=o+1;break}continue}s===-1&&(n=!1,s=o+1),l===46?e===-1?e=o:a!==1&&(a=1):e!==-1&&(a=-1)}return e===-1||s===-1||a===0||a===1&&e===s-1&&e===i+1?"":t.slice(e,s)},format:function(t){if(t===null||typeof t!="object")throw new TypeError('The "pathObject" argument must be of type Object. Received type '+typeof t);return iy("/",t)},parse:function(t){Ee(t);var e={root:"",dir:"",base:"",ext:"",name:""};if(t.length===0)return e;var i=t.charCodeAt(0),s=i===47,n;s?(e.root="/",n=1):n=0;for(var a=-1,o=0,l=-1,h=!0,d=t.length-1,c=0;d>=n;--d){if(i=t.charCodeAt(d),i===47){if(!h){o=d+1;break}continue}l===-1&&(h=!1,l=d+1),i===46?a===-1?a=d:c!==1&&(c=1):a!==-1&&(c=-1)}return a===-1||l===-1||c===0||c===1&&a===l-1&&a===o+1?l!==-1&&(o===0&&s?e.base=e.name=t.slice(1,l):e.base=e.name=t.slice(o,l)):(o===0&&s?(e.name=t.slice(1,a),e.base=t.slice(1,l)):(e.name=t.slice(o,a),e.base=t.slice(o,l)),e.ext=t.slice(a,l)),o>0?e.dir=t.slice(0,o-1):s&&(e.dir="/"),e},sep:"/",delimiter:":",win32:null,posix:null};Ci.posix=Ci;var sy=Ci;const{basename:Wd,extname:ry}=sy;class ny{constructor(){let t=(()=>typeof cn>"u")(),e="image/png",i="image/jpeg",s="image/jpeg",n="image/webp",a="application/pdf",o="image/svg+xml";Object.assign(this,{toMime:this.toMime.bind(this),fromMime:this.fromMime.bind(this),expected:t?'"png", "jpg", or "webp"':'"png", "jpg", "pdf", or "svg"',formats:t?{png:e,jpg:i,jpeg:s,webp:n}:{png:e,jpg:i,jpeg:s,pdf:a,svg:o},mimes:t?{[e]:"png",[i]:"jpg",[n]:"webp"}:{[e]:"png",[i]:"jpg",[a]:"pdf",[o]:"svg"}})}toMime(t){return this.formats[(t||"").replace(/^\./,"").toLowerCase()]}fromMime(t){return this.mimes[t]}}function ay(r,{filename:t="",extension:e="",format:g,page:s,quality:n,matte:a,density:o,outline:l,archive:f}={}){var{fromMime:d,toMime:c,expected:u}=new ny,f=f||"canvas",p=g||e.replace(/@\d+x$/i,"")||ry(t),g=d(c(p)||p),v=c(g),E=r.length;if(!p)throw new Error("Cannot determine image format (use a filename extension or 'format' argument)");if(!g)throw new Error(`Unsupported file format "${p}" (expected ${u})`);if(!E)throw new RangeError("Canvas has no associated contexts (try calling getContext or newPage first)");let T,A,y=t.replace(/{(\d*)}/g,(S,R)=>(A=!0,R=parseInt(R,10),T=isFinite(R)?R:isFinite(T)?T:-1,"{}")),b=s>0?s-1:s<0?E+s:void 0;if(isFinite(b)&&b<0||b>=E)throw new RangeError(E==1?`Canvas only has a ‘page 1’ (${b} is out of bounds)`:`Canvas has pages 1–${E} (${b} is out of bounds)`);if(r=isFinite(b)?[r[b]]:A||g=="pdf"?r:r.slice(-1),n===void 0)n=.92;else if(typeof n!="number"||!isFinite(n)||n<0||n>1)throw new TypeError("The quality option must be an number in the 0.0–1.0 range");if(o===void 0){let S=(e||Wd(t,p)).match(/@(\d+)x$/i);o=S?parseInt(S[1],10):1}else if(typeof o!="number"||!Number.isInteger(o)||o<1)throw new TypeError("The density option must be a non-negative integer");return l===void 0?l=!0:g=="svg"&&(l=!!l),{filename:t,pattern:y,format:g,mime:v,pages:r,padding:T,quality:n,matte:a,density:o,outline:l,archive:f}}class Rr{static for(t){return new Rr().append(t).get()}constructor(){this.crc=-1}get(){return~this.crc}append(t){for(var e=this.crc|0,i=this.table,s=0,n=t.length|0;s<n;s++)e=e>>>8^i[(e^t[s])&255];return this.crc=e,this}}Rr.prototype.table=(()=>{var r,t,e,i=[];for(r=0;r<256;r++){for(e=r,t=0;t<8;t++)e=e&1?e>>>1^3988292384:e>>>1;i[r]=e}return i})();function $a(r){let t=new Uint8Array(r),e=new DataView(t.buffer),i={array:t,view:e,size:r,set8(s,n){return e.setUint8(s,n),i},set16(s,n){return e.setUint16(s,n,!0),i},set32(s,n){return e.setUint32(s,n,!0),i},bytes(s,n){return t.set(n,s),i}};return i}const _r=class _r{constructor(t){let e=new Date;Object.assign(this,{directory:t,offset:0,files:[],time:(e.getHours()<<6|e.getMinutes())<<5|e.getSeconds()/2,date:(e.getFullYear()-1980<<4|e.getMonth()+1)<<5|e.getDate()}),this.add(t)}async add(t,e){let i=!e,s=_r.encoder.encode(`${this.directory}/${i?"":t}`),n=new Uint8Array(i?0:await e.arrayBuffer()),a=30+s.length,o=a+n.length,l=16,{offset:h}=this,d=$a(26).set32(0,134742036).set16(6,this.time).set16(8,this.date).set32(10,Rr.for(n)).set32(14,n.length).set32(18,n.length).set16(22,s.length);h+=a;let c=$a(a+n.length+l).set32(0,67324752).bytes(4,d.array).bytes(30,s).bytes(a,n);h+=n.length,c.set32(o,134695760).bytes(o+4,d.array.slice(10,22)),h+=l,this.files.push({offset:h,folder:i,name:s,header:d,payload:c}),this.offset=h}toBuffer(){let t=this.files.reduce((c,{name:u})=>46+u.length+c,0),e=$a(t+22),i=0;for(var{offset:s,name:n,header:a,folder:o}of this.files)e.set32(i,33639248).set16(i+4,20).bytes(i+6,a.array).set8(i+38,o?16:0).set32(i+42,s).bytes(i+46,n),i+=46+n.length;e.set32(i,101010256).set16(i+8,this.files.length).set16(i+10,this.files.length).set32(i+12,t).set32(i+16,this.offset);let l=new Uint8Array(this.offset+e.size),h=0;for(var{payload:d}of this.files)l.set(d.array,h),h+=d.size;return l.set(e.array,h),l}get blob(){return new Blob([this.toBuffer()],{type:"application/zip"})}};Jd(_r,"encoder",new TextEncoder);let Fa=_r;const Na=(r,t,e,i)=>{if(i){let{width:s,height:n}=r,a=Object.assign(document.createElement("canvas"),{width:s,height:n}),o=a.getContext("2d");o.fillStyle=i,o.fillRect(0,0,s,n),o.drawImage(r,0,0),r=a}return new Promise((s,n)=>r.toBlob(s,t,e))},oy=(...r)=>Na(...r).then(t=>t.arrayBuffer()),ly=async(r,t,e,i,s)=>{Yd(s,await Na(r,t,e,i))},hy=async(r,t,e,i,s,n,a)=>{let o=d=>n.replace("{}",String(d+1).padStart(a,"0")),l=Wd(s,".zip")||"archive",h=new Fa(l);await Promise.all(r.map(async(d,c)=>{let u=o(c);await h.add(u,await Na(d,t,e,i))})),Yd(`${l}.zip`,h.blob)},Yd=(r,t)=>{const e=window.URL.createObjectURL(t),i=document.createElement("a");i.style.display="none",i.href=e,i.setAttribute("download",r),typeof i.download>"u"&&i.setAttribute("target","_blank"),document.body.appendChild(i),i.click(),document.body.removeChild(i),setTimeout(()=>window.URL.revokeObjectURL(e),100)};var dy={asBuffer:oy,asDownload:ly,asZipDownload:hy,atScale:(r,t,e)=>r.map(i=>{if(t==1&&!e)return i.canvas;let s=document.createElement("canvas"),n=s.getContext("2d"),a=i.canvas?i.canvas:i;return s.width=a.width*t,s.height=a.height*t,e&&(n.fillStyle=e,n.fillRect(0,0,s.width,s.height)),n.scale(t,t),n.drawImage(a,0,0),s}),options:ay};const{asBuffer:Ua,asDownload:cy,asZipDownload:uy,atScale:Ba,options:Ha}=dy,zd=Symbol.for("toDataURL"),fy=r=>{let t=Object.assign(new qd,{crossOrigin:"Anonymous",src:r});return t.decode().then(()=>t)};class py{constructor(t,e){let i=document.createElement("canvas"),s=[];Object.defineProperty(i,"async",{value:!0,writable:!1,enumerable:!0});for(var[n,a]of Object.entries({png:()=>Ua(i,"image/png"),jpg:()=>Ua(i,"image/jpeg"),pages:()=>s.concat(i).map(o=>o.getContext("2d"))}))Object.defineProperty(i,n,{get:a});return Object.assign(i,{width:t,height:e,newPage(...o){var{width:h,height:d}=i,l=Object.assign(document.createElement("canvas"),{width:h,height:d});l.getContext("2d").drawImage(i,0,0),s.push(l);var[h,d]=o.length?o:[h,d];return Object.assign(i,{width:h,height:d}).getContext("2d")},saveAs(o,l){l=typeof l=="number"?{quality:l}:l;let h=Ha(this.pages,{filename:o,...l}),{pattern:d,padding:c,mime:u,quality:f,matte:p,density:g,archive:v}=h,E=Ba(h.pages,g);return c==null?cy(E[0],u,f,p,o):uy(E,u,f,p,v,d,c)},toBuffer(o="png",l={}){l=typeof l=="number"?{quality:l}:l;let h=Ha(this.pages,{extension:o,...l}),{mime:d,quality:c,matte:u,pages:f,density:p}=h,g=Ba(f,p,u)[0];return Ua(g,d,c,u)},[zd]:i.toDataURL.bind(i),toDataURL(o="png",l={}){l=typeof l=="number"?{quality:l}:l;let h=Ha(this.pages,{extension:o,...l}),{mime:d,quality:c,matte:u,pages:f,density:p}=h,g=Ba(f,p,u)[0],v=g[g===i?zd:"toDataURL"](d,c);return Promise.resolve(v)}})}}const{CanvasRenderingContext2D:gy,CanvasGradient:my,CanvasPattern:vy,Image:qd,ImageData:yy,Path2D:Ey,DOMMatrix:Ty,DOMRect:by,DOMPoint:Ay}=window;var Xd={Canvas:py,loadImage:fy,CanvasRenderingContext2D:gy,CanvasGradient:my,CanvasPattern:vy,Image:qd,ImageData:yy,Path2D:Ey,DOMMatrix:Ty,DOMRect:by,DOMPoint:Ay};const Qd=be({__proto__:null,default:un(Xd)},[Xd]);return Object.defineProperty(ut,Symbol.toStringTag,{value:"Module"}),ut}({});
1404
+ `}},re([j({type:Object,attribute:"data"})],At.Embed.prototype,"data",2),re([j({type:String})],At.Embed.prototype,"vouchId",2),re([j({type:String})],At.Embed.prototype,"templateId",2),re([j({type:String})],At.Embed.prototype,"env",2),re([j({type:String})],At.Embed.prototype,"apiKey",2),re([j({type:String})],At.Embed.prototype,"trackingSource",2),re([j({type:Array})],At.Embed.prototype,"controls",2),re([j({type:String})],At.Embed.prototype,"preload",2),re([j({type:Boolean})],At.Embed.prototype,"autoplay",2),re([j({type:Number})],At.Embed.prototype,"aspectRatio",2),re([Wt()],At.Embed.prototype,"vouch",2),re([Wt()],At.Embed.prototype,"template",2),At.Embed=re([dd("vouch-embed")],At.Embed);function ke(r){if(typeof r!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(r))}function Ac(r,t){for(var e="",i=0,s=-1,n=0,a,o=0;o<=r.length;++o){if(o<r.length)a=r.charCodeAt(o);else{if(a===47)break;a=47}if(a===47){if(!(s===o-1||n===1))if(s!==o-1&&n===2){if(e.length<2||i!==2||e.charCodeAt(e.length-1)!==46||e.charCodeAt(e.length-2)!==46){if(e.length>2){var l=e.lastIndexOf("/");if(l!==e.length-1){l===-1?(e="",i=0):(e=e.slice(0,l),i=e.length-1-e.lastIndexOf("/")),s=o,n=0;continue}}else if(e.length===2||e.length===1){e="",i=0,s=o,n=0;continue}}t&&(e.length>0?e+="/..":e="..",i=2)}else e.length>0?e+="/"+r.slice(s+1,o):e=r.slice(s+1,o),i=o-s-1;s=o,n=0}else a===46&&n!==-1?++n:n=-1}return e}function b0(r,t){var e=t.dir||t.root,i=t.base||(t.name||"")+(t.ext||"");return e?e===t.root?e+i:e+r+i:i}var Fi={resolve:function(){for(var t="",e=!1,i,s=arguments.length-1;s>=-1&&!e;s--){var n;s>=0?n=arguments[s]:(i===void 0&&(i=process.cwd()),n=i),ke(n),n.length!==0&&(t=n+"/"+t,e=n.charCodeAt(0)===47)}return t=Ac(t,!e),e?t.length>0?"/"+t:"/":t.length>0?t:"."},normalize:function(t){if(ke(t),t.length===0)return".";var e=t.charCodeAt(0)===47,i=t.charCodeAt(t.length-1)===47;return t=Ac(t,!e),t.length===0&&!e&&(t="."),t.length>0&&i&&(t+="/"),e?"/"+t:t},isAbsolute:function(t){return ke(t),t.length>0&&t.charCodeAt(0)===47},join:function(){if(arguments.length===0)return".";for(var t,e=0;e<arguments.length;++e){var i=arguments[e];ke(i),i.length>0&&(t===void 0?t=i:t+="/"+i)}return t===void 0?".":Fi.normalize(t)},relative:function(t,e){if(ke(t),ke(e),t===e||(t=Fi.resolve(t),e=Fi.resolve(e),t===e))return"";for(var i=1;i<t.length&&t.charCodeAt(i)===47;++i);for(var s=t.length,n=s-i,a=1;a<e.length&&e.charCodeAt(a)===47;++a);for(var o=e.length,l=o-a,h=n<l?n:l,c=-1,d=0;d<=h;++d){if(d===h){if(l>h){if(e.charCodeAt(a+d)===47)return e.slice(a+d+1);if(d===0)return e.slice(a+d)}else n>h&&(t.charCodeAt(i+d)===47?c=d:d===0&&(c=0));break}var u=t.charCodeAt(i+d),f=e.charCodeAt(a+d);if(u!==f)break;u===47&&(c=d)}var p="";for(d=i+c+1;d<=s;++d)(d===s||t.charCodeAt(d)===47)&&(p.length===0?p+="..":p+="/..");return p.length>0?p+e.slice(a+c):(a+=c,e.charCodeAt(a)===47&&++a,e.slice(a))},_makeLong:function(t){return t},dirname:function(t){if(ke(t),t.length===0)return".";for(var e=t.charCodeAt(0),i=e===47,s=-1,n=!0,a=t.length-1;a>=1;--a)if(e=t.charCodeAt(a),e===47){if(!n){s=a;break}}else n=!1;return s===-1?i?"/":".":i&&s===1?"//":t.slice(0,s)},basename:function(t,e){if(e!==void 0&&typeof e!="string")throw new TypeError('"ext" argument must be a string');ke(t);var i=0,s=-1,n=!0,a;if(e!==void 0&&e.length>0&&e.length<=t.length){if(e.length===t.length&&e===t)return"";var o=e.length-1,l=-1;for(a=t.length-1;a>=0;--a){var h=t.charCodeAt(a);if(h===47){if(!n){i=a+1;break}}else l===-1&&(n=!1,l=a+1),o>=0&&(h===e.charCodeAt(o)?--o===-1&&(s=a):(o=-1,s=l))}return i===s?s=l:s===-1&&(s=t.length),t.slice(i,s)}else{for(a=t.length-1;a>=0;--a)if(t.charCodeAt(a)===47){if(!n){i=a+1;break}}else s===-1&&(n=!1,s=a+1);return s===-1?"":t.slice(i,s)}},extname:function(t){ke(t);for(var e=-1,i=0,s=-1,n=!0,a=0,o=t.length-1;o>=0;--o){var l=t.charCodeAt(o);if(l===47){if(!n){i=o+1;break}continue}s===-1&&(n=!1,s=o+1),l===46?e===-1?e=o:a!==1&&(a=1):e!==-1&&(a=-1)}return e===-1||s===-1||a===0||a===1&&e===s-1&&e===i+1?"":t.slice(e,s)},format:function(t){if(t===null||typeof t!="object")throw new TypeError('The "pathObject" argument must be of type Object. Received type '+typeof t);return b0("/",t)},parse:function(t){ke(t);var e={root:"",dir:"",base:"",ext:"",name:""};if(t.length===0)return e;var i=t.charCodeAt(0),s=i===47,n;s?(e.root="/",n=1):n=0;for(var a=-1,o=0,l=-1,h=!0,c=t.length-1,d=0;c>=n;--c){if(i=t.charCodeAt(c),i===47){if(!h){o=c+1;break}continue}l===-1&&(h=!1,l=c+1),i===46?a===-1?a=c:d!==1&&(d=1):a!==-1&&(d=-1)}return a===-1||l===-1||d===0||d===1&&a===l-1&&a===o+1?l!==-1&&(o===0&&s?e.base=e.name=t.slice(1,l):e.base=e.name=t.slice(o,l)):(o===0&&s?(e.name=t.slice(1,a),e.base=t.slice(1,l)):(e.name=t.slice(o,a),e.base=t.slice(o,l)),e.ext=t.slice(a,l)),o>0?e.dir=t.slice(0,o-1):s&&(e.dir="/"),e},sep:"/",delimiter:":",win32:null,posix:null};Fi.posix=Fi;var T0=Fi;const{basename:wc,extname:A0}=T0;class w0{constructor(){let t=(()=>typeof Gs>"u")(),e="image/png",i="image/jpeg",s="image/jpeg",n="image/webp",a="application/pdf",o="image/svg+xml";Object.assign(this,{toMime:this.toMime.bind(this),fromMime:this.fromMime.bind(this),expected:t?'"png", "jpg", or "webp"':'"png", "jpg", "pdf", or "svg"',formats:t?{png:e,jpg:i,jpeg:s,webp:n}:{png:e,jpg:i,jpeg:s,pdf:a,svg:o},mimes:t?{[e]:"png",[i]:"jpg",[n]:"webp"}:{[e]:"png",[i]:"jpg",[a]:"pdf",[o]:"svg"}})}toMime(t){return this.formats[(t||"").replace(/^\./,"").toLowerCase()]}fromMime(t){return this.mimes[t]}}function S0(r,{filename:t="",extension:e="",format:g,page:s,quality:n,matte:a,density:o,outline:l,archive:f}={}){var{fromMime:c,toMime:d,expected:u}=new w0,f=f||"canvas",p=g||e.replace(/@\d+x$/i,"")||A0(t),g=c(d(p)||p),v=d(g),E=r.length;if(!p)throw new Error("Cannot determine image format (use a filename extension or 'format' argument)");if(!g)throw new Error(`Unsupported file format "${p}" (expected ${u})`);if(!E)throw new RangeError("Canvas has no associated contexts (try calling getContext or newPage first)");let A,L,y=t.replace(/{(\d*)}/g,(R,C)=>(L=!0,C=parseInt(C,10),A=isFinite(C)?C:isFinite(A)?A:-1,"{}")),S=s>0?s-1:s<0?E+s:void 0;if(isFinite(S)&&S<0||S>=E)throw new RangeError(E==1?`Canvas only has a ‘page 1’ (${S} is out of bounds)`:`Canvas has pages 1–${E} (${S} is out of bounds)`);if(r=isFinite(S)?[r[S]]:L||g=="pdf"?r:r.slice(-1),n===void 0)n=.92;else if(typeof n!="number"||!isFinite(n)||n<0||n>1)throw new TypeError("The quality option must be an number in the 0.0–1.0 range");if(o===void 0){let R=(e||wc(t,p)).match(/@(\d+)x$/i);o=R?parseInt(R[1],10):1}else if(typeof o!="number"||!Number.isInteger(o)||o<1)throw new TypeError("The density option must be a non-negative integer");return l===void 0?l=!0:g=="svg"&&(l=!!l),{filename:t,pattern:y,format:g,mime:v,pages:r,padding:A,quality:n,matte:a,density:o,outline:l,archive:f}}class Rr{static for(t){return new Rr().append(t).get()}constructor(){this.crc=-1}get(){return~this.crc}append(t){for(var e=this.crc|0,i=this.table,s=0,n=t.length|0;s<n;s++)e=e>>>8^i[(e^t[s])&255];return this.crc=e,this}}Rr.prototype.table=(()=>{var r,t,e,i=[];for(r=0;r<256;r++){for(e=r,t=0;t<8;t++)e=e&1?e>>>1^3988292384:e>>>1;i[r]=e}return i})();function wa(r){let t=new Uint8Array(r),e=new DataView(t.buffer),i={array:t,view:e,size:r,set8(s,n){return e.setUint8(s,n),i},set16(s,n){return e.setUint16(s,n,!0),i},set32(s,n){return e.setUint32(s,n,!0),i},bytes(s,n){return t.set(n,s),i}};return i}const _r=class _r{constructor(t){let e=new Date;Object.assign(this,{directory:t,offset:0,files:[],time:(e.getHours()<<6|e.getMinutes())<<5|e.getSeconds()/2,date:(e.getFullYear()-1980<<4|e.getMonth()+1)<<5|e.getDate()}),this.add(t)}async add(t,e){let i=!e,s=_r.encoder.encode(`${this.directory}/${i?"":t}`),n=new Uint8Array(i?0:await e.arrayBuffer()),a=30+s.length,o=a+n.length,l=16,{offset:h}=this,c=wa(26).set32(0,134742036).set16(6,this.time).set16(8,this.date).set32(10,Rr.for(n)).set32(14,n.length).set32(18,n.length).set16(22,s.length);h+=a;let d=wa(a+n.length+l).set32(0,67324752).bytes(4,c.array).bytes(30,s).bytes(a,n);h+=n.length,d.set32(o,134695760).bytes(o+4,c.array.slice(10,22)),h+=l,this.files.push({offset:h,folder:i,name:s,header:c,payload:d}),this.offset=h}toBuffer(){let t=this.files.reduce((d,{name:u})=>46+u.length+d,0),e=wa(t+22),i=0;for(var{offset:s,name:n,header:a,folder:o}of this.files)e.set32(i,33639248).set16(i+4,20).bytes(i+6,a.array).set8(i+38,o?16:0).set32(i+42,s).bytes(i+46,n),i+=46+n.length;e.set32(i,101010256).set16(i+8,this.files.length).set16(i+10,this.files.length).set32(i+12,t).set32(i+16,this.offset);let l=new Uint8Array(this.offset+e.size),h=0;for(var{payload:c}of this.files)l.set(c.array,h),h+=c.size;return l.set(e.array,h),l}get blob(){return new Blob([this.toBuffer()],{type:"application/zip"})}};Dc(_r,"encoder",new TextEncoder);let Sa=_r;const La=(r,t,e,i)=>{if(i){let{width:s,height:n}=r,a=Object.assign(document.createElement("canvas"),{width:s,height:n}),o=a.getContext("2d");o.fillStyle=i,o.fillRect(0,0,s,n),o.drawImage(r,0,0),r=a}return new Promise((s,n)=>r.toBlob(s,t,e))},L0=(...r)=>La(...r).then(t=>t.arrayBuffer()),R0=async(r,t,e,i,s)=>{Sc(s,await La(r,t,e,i))},_0=async(r,t,e,i,s,n,a)=>{let o=c=>n.replace("{}",String(c+1).padStart(a,"0")),l=wc(s,".zip")||"archive",h=new Sa(l);await Promise.all(r.map(async(c,d)=>{let u=o(d);await h.add(u,await La(c,t,e,i))})),Sc(`${l}.zip`,h.blob)},Sc=(r,t)=>{const e=window.URL.createObjectURL(t),i=document.createElement("a");i.style.display="none",i.href=e,i.setAttribute("download",r),typeof i.download>"u"&&i.setAttribute("target","_blank"),document.body.appendChild(i),i.click(),document.body.removeChild(i),setTimeout(()=>window.URL.revokeObjectURL(e),100)};var k0={asBuffer:L0,asDownload:R0,asZipDownload:_0,atScale:(r,t,e)=>r.map(i=>{if(t==1&&!e)return i.canvas;let s=document.createElement("canvas"),n=s.getContext("2d"),a=i.canvas?i.canvas:i;return s.width=a.width*t,s.height=a.height*t,e&&(n.fillStyle=e,n.fillRect(0,0,s.width,s.height)),n.scale(t,t),n.drawImage(a,0,0),s}),options:S0};const{asBuffer:Ra,asDownload:I0,asZipDownload:C0,atScale:_a,options:ka}=k0,Lc=Symbol.for("toDataURL"),D0=r=>{let t=Object.assign(new Rc,{crossOrigin:"Anonymous",src:r});return t.decode().then(()=>t)};class x0{constructor(t,e){let i=document.createElement("canvas"),s=[];Object.defineProperty(i,"async",{value:!0,writable:!1,enumerable:!0});for(var[n,a]of Object.entries({png:()=>Ra(i,"image/png"),jpg:()=>Ra(i,"image/jpeg"),pages:()=>s.concat(i).map(o=>o.getContext("2d"))}))Object.defineProperty(i,n,{get:a});return Object.assign(i,{width:t,height:e,newPage(...o){var{width:h,height:c}=i,l=Object.assign(document.createElement("canvas"),{width:h,height:c});l.getContext("2d").drawImage(i,0,0),s.push(l);var[h,c]=o.length?o:[h,c];return Object.assign(i,{width:h,height:c}).getContext("2d")},saveAs(o,l){l=typeof l=="number"?{quality:l}:l;let h=ka(this.pages,{filename:o,...l}),{pattern:c,padding:d,mime:u,quality:f,matte:p,density:g,archive:v}=h,E=_a(h.pages,g);return d==null?I0(E[0],u,f,p,o):C0(E,u,f,p,v,c,d)},toBuffer(o="png",l={}){l=typeof l=="number"?{quality:l}:l;let h=ka(this.pages,{extension:o,...l}),{mime:c,quality:d,matte:u,pages:f,density:p}=h,g=_a(f,p,u)[0];return Ra(g,c,d,u)},[Lc]:i.toDataURL.bind(i),toDataURL(o="png",l={}){l=typeof l=="number"?{quality:l}:l;let h=ka(this.pages,{extension:o,...l}),{mime:c,quality:d,matte:u,pages:f,density:p}=h,g=_a(f,p,u)[0],v=g[g===i?Lc:"toDataURL"](c,d);return Promise.resolve(v)}})}}const{CanvasRenderingContext2D:P0,CanvasGradient:O0,CanvasPattern:$0,Image:Rc,ImageData:M0,Path2D:F0,DOMMatrix:N0,DOMRect:U0,DOMPoint:B0}=window;var _c={Canvas:x0,loadImage:D0,CanvasRenderingContext2D:P0,CanvasGradient:O0,CanvasPattern:$0,Image:Rc,ImageData:M0,Path2D:F0,DOMMatrix:N0,DOMRect:U0,DOMPoint:B0};const kc=De({__proto__:null,default:Jr(_c)},[_c]);return Object.defineProperty(At,Symbol.toStringTag,{value:"Module"}),At}({});
1417
1405
  //# sourceMappingURL=embeds.iife.js.map