/**
 * Bundled by jsDelivr using Rollup v2.79.2 and Terser v5.39.0.
 * Original file: /npm/@maveio/components@0.0.150/dist/index.js
 *
 * Do NOT use SRI with dynamically generated files! More information: https://www.jsdelivr.com/using-sri-with-dynamic-files
 */
var e,t=window,i=t.ShadowRoot&&(void 0===t.ShadyCSS||t.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,r=Symbol(),s=new WeakMap,n=class{constructor(e,t,i){if(this._$cssResult$=!0,i!==r)throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");this.cssText=e,this.t=t}get styleSheet(){let e=this.o,t=this.t;if(i&&void 0===e){let i=void 0!==t&&1===t.length;i&&(e=s.get(t)),void 0===e&&((this.o=e=new CSSStyleSheet).replaceSync(this.cssText),i&&s.set(t,e))}return e}toString(){return this.cssText}},a=i?e=>e:e=>e instanceof CSSStyleSheet?(e=>{let t="";for(let i of e.cssRules)t+=i.cssText;return(e=>new n("string"==typeof e?e:e+"",void 0,r))(t)})(e):e,o=window,l=o.trustedTypes,h=l?l.emptyScript:"",d=o.reactiveElementPolyfillSupport,u={toAttribute(e,t){switch(t){case Boolean:e=e?h:null;break;case Object:case Array:e=null==e?e:JSON.stringify(e)}return e},fromAttribute(e,t){let i=e;switch(t){case Boolean:i=null!==e;break;case Number:i=null===e?null:Number(e);break;case Object:case Array:try{i=JSON.parse(e)}catch{i=null}}return i}},c=(e,t)=>t!==e&&(t==t||e==e),f={attribute:!0,type:String,converter:u,reflect:!1,hasChanged:c},p=class extends HTMLElement{constructor(){super(),this._$Ei=new Map,this.isUpdatePending=!1,this.hasUpdated=!1,this._$El=null,this.u()}static addInitializer(e){var t;this.finalize(),(null!==(t=this.h)&&void 0!==t?t:this.h=[]).push(e)}static get observedAttributes(){this.finalize();let e=[];return this.elementProperties.forEach(((t,i)=>{let r=this._$Ep(i,t);void 0!==r&&(this._$Ev.set(r,i),e.push(r))})),e}static createProperty(e,t=f){if(t.state&&(t.attribute=!1),this.finalize(),this.elementProperties.set(e,t),!t.noAccessor&&!this.prototype.hasOwnProperty(e)){let i="symbol"==typeof e?Symbol():"__"+e,r=this.getPropertyDescriptor(e,i,t);void 0!==r&&Object.defineProperty(this.prototype,e,r)}}static getPropertyDescriptor(e,t,i){return{get(){return this[t]},set(r){let s=this[e];this[t]=r,this.requestUpdate(e,s,i)},configurable:!0,enumerable:!0}}static getPropertyOptions(e){return this.elementProperties.get(e)||f}static finalize(){if(this.hasOwnProperty("finalized"))return!1;this.finalized=!0;let e=Object.getPrototypeOf(this);if(e.finalize(),void 0!==e.h&&(this.h=[...e.h]),this.elementProperties=new Map(e.elementProperties),this._$Ev=new Map,this.hasOwnProperty("properties")){let e=this.properties,t=[...Object.getOwnPropertyNames(e),...Object.getOwnPropertySymbols(e)];for(let i of t)this.createProperty(i,e[i])}return this.elementStyles=this.finalizeStyles(this.styles),!0}static finalizeStyles(e){let t=[];if(Array.isArray(e)){let i=new Set(e.flat(1/0).reverse());for(let e of i)t.unshift(a(e))}else void 0!==e&&t.push(a(e));return t}static _$Ep(e,t){let i=t.attribute;return!1===i?void 0:"string"==typeof i?i:"string"==typeof e?e.toLowerCase():void 0}u(){var e;this._$E_=new Promise((e=>this.enableUpdating=e)),this._$AL=new Map,this._$Eg(),this.requestUpdate(),null===(e=this.constructor.h)||void 0===e||e.forEach((e=>e(this)))}addController(e){var t,i;(null!==(t=this._$ES)&&void 0!==t?t:this._$ES=[]).push(e),void 0!==this.renderRoot&&this.isConnected&&(null===(i=e.hostConnected)||void 0===i||i.call(e))}removeController(e){var t;null===(t=this._$ES)||void 0===t||t.splice(this._$ES.indexOf(e)>>>0,1)}_$Eg(){this.constructor.elementProperties.forEach(((e,t)=>{this.hasOwnProperty(t)&&(this._$Ei.set(t,this[t]),delete this[t])}))}createRenderRoot(){var e;let r=null!==(e=this.shadowRoot)&&void 0!==e?e:this.attachShadow(this.constructor.shadowRootOptions);return((e,r)=>{i?e.adoptedStyleSheets=r.map((e=>e instanceof CSSStyleSheet?e:e.styleSheet)):r.forEach((i=>{let r=document.createElement("style"),s=t.litNonce;void 0!==s&&r.setAttribute("nonce",s),r.textContent=i.cssText,e.appendChild(r)}))})(r,this.constructor.elementStyles),r}connectedCallback(){var e;void 0===this.renderRoot&&(this.renderRoot=this.createRenderRoot()),this.enableUpdating(!0),null===(e=this._$ES)||void 0===e||e.forEach((e=>{var t;return null===(t=e.hostConnected)||void 0===t?void 0:t.call(e)}))}enableUpdating(e){}disconnectedCallback(){var e;null===(e=this._$ES)||void 0===e||e.forEach((e=>{var t;return null===(t=e.hostDisconnected)||void 0===t?void 0:t.call(e)}))}attributeChangedCallback(e,t,i){this._$AK(e,i)}_$EO(e,t,i=f){var r;let s=this.constructor._$Ep(e,i);if(void 0!==s&&!0===i.reflect){let n=(void 0!==(null===(r=i.converter)||void 0===r?void 0:r.toAttribute)?i.converter:u).toAttribute(t,i.type);this._$El=e,null==n?this.removeAttribute(s):this.setAttribute(s,n),this._$El=null}}_$AK(e,t){var i;let r=this.constructor,s=r._$Ev.get(e);if(void 0!==s&&this._$El!==s){let e=r.getPropertyOptions(s),n="function"==typeof e.converter?{fromAttribute:e.converter}:void 0!==(null===(i=e.converter)||void 0===i?void 0:i.fromAttribute)?e.converter:u;this._$El=s,this[s]=n.fromAttribute(t,e.type),this._$El=null}}requestUpdate(e,t,i){let r=!0;void 0!==e&&(((i=i||this.constructor.getPropertyOptions(e)).hasChanged||c)(this[e],t)?(this._$AL.has(e)||this._$AL.set(e,t),!0===i.reflect&&this._$El!==e&&(void 0===this._$EC&&(this._$EC=new Map),this._$EC.set(e,i))):r=!1),!this.isUpdatePending&&r&&(this._$E_=this._$Ej())}async _$Ej(){this.isUpdatePending=!0;try{await this._$E_}catch(e){Promise.reject(e)}let e=this.scheduleUpdate();return null!=e&&await e,!this.isUpdatePending}scheduleUpdate(){return this.performUpdate()}performUpdate(){var e;if(!this.isUpdatePending)return;this.hasUpdated,this._$Ei&&(this._$Ei.forEach(((e,t)=>this[t]=e)),this._$Ei=void 0);let t=!1,i=this._$AL;try{t=this.shouldUpdate(i),t?(this.willUpdate(i),null===(e=this._$ES)||void 0===e||e.forEach((e=>{var t;return null===(t=e.hostUpdate)||void 0===t?void 0:t.call(e)})),this.update(i)):this._$Ek()}catch(e){throw t=!1,this._$Ek(),e}t&&this._$AE(i)}willUpdate(e){}_$AE(e){var t;null===(t=this._$ES)||void 0===t||t.forEach((e=>{var t;return null===(t=e.hostUpdated)||void 0===t?void 0:t.call(e)})),this.hasUpdated||(this.hasUpdated=!0,this.firstUpdated(e)),this.updated(e)}_$Ek(){this._$AL=new Map,this.isUpdatePending=!1}get updateComplete(){return this.getUpdateComplete()}getUpdateComplete(){return this._$E_}shouldUpdate(e){return!0}update(e){void 0!==this._$EC&&(this._$EC.forEach(((e,t)=>this._$EO(t,this[t],e))),this._$EC=void 0),this._$Ek()}updated(e){}firstUpdated(e){}};p.finalized=!0,p.elementProperties=new Map,p.elementStyles=[],p.shadowRootOptions={mode:"open"},d?.({ReactiveElement:p}),(null!==(e=o.reactiveElementVersions)&&void 0!==e?e:o.reactiveElementVersions=[]).push("1.6.1");var m=Symbol(),g=class{get taskComplete(){return this.t||(1===this.status?this.t=new Promise(((e,t)=>{this.i=e,this.o=t})):3===this.status?this.t=Promise.reject(this.h):this.t=Promise.resolve(this.l)),this.t}constructor(e,t,i){this.u=0,this.status=0,(this.p=e).addController(this);let r="object"==typeof t?t:{task:t,args:i};this._=r.task,this.v=r.args,this.j=r.argsEqual??v,this.m=r.onComplete,this.g=r.onError,this.autoRun=r.autoRun??!0,"initialValue"in r&&(this.l=r.initialValue,this.status=2,this.k=this.A?.())}hostUpdate(){!0===this.autoRun&&this.O()}hostUpdated(){"afterUpdate"===this.autoRun&&this.O()}A(){if(void 0===this.v)return;let e=this.v();if(!Array.isArray(e))throw Error("The args function must return an array");return e}async O(){let e=this.A(),t=this.k;this.k=e,e===t||void 0===e||void 0!==t&&this.j(t,e)||await this.run(e)}async run(e){let t,i;e??(e=this.A()),this.k=e,1===this.status?this.T?.abort():(this.t=void 0,this.i=void 0,this.o=void 0),this.status=1,"afterUpdate"===this.autoRun?queueMicrotask((()=>this.p.requestUpdate())):this.p.requestUpdate();let r=++this.u;this.T=new AbortController;let s=!1;try{t=await this._(e,{signal:this.T.signal})}catch(e){s=!0,i=e}if(this.u===r){if(t===m)this.status=0;else{if(!1===s){try{this.m?.(t)}catch{}this.status=2,this.i?.(t)}else{try{this.g?.(i)}catch{}this.status=3,this.o?.(i)}this.l=t,this.h=i}this.p.requestUpdate()}}abort(e){1===this.status&&this.T?.abort(e)}get value(){return this.l}get error(){return this.h}render(e){switch(this.status){case 0:return e.initial?.();case 1:return e.pending?.();case 2:return e.complete?.(this.value);case 3:return e.error?.(this.error);default:throw Error("Unexpected status: "+this.status)}}},v=(e,t)=>e===t||e.length===t.length&&e.every(((e,i)=>!c(e,t[i]))),E={metrics:{enabled:!0,socket:"wss://metrics.video-dns.com/socket"},upload:{socket:"wss://app.mave.io/api/v1/socket",endpoint:"https://upload.mave.io/files"},api:{endpoint:"https://mave.io/api/v1"},cdn:{endpoint:"https://space-${this.spaceId}.video-dns.com"}};function y(e){Object.assign(E,e)}var b=class{constructor(e,t){this.host=e,this.embed=t,this.task=new g(this.host,(async()=>{try{let e=this.embedFile("subtitle.json"),t=await fetch(e);if(200!==t.status)throw new Error;let i=await t.json(),r=i.segments.flatMap((e=>e.words)).map((e=>({start:e.start,end:e.end,word:e.word.trim()}))),s=[],n={start:0,end:0,text:"",words:[]};r.forEach((e=>{let{start:t,end:i,word:r}=e;0===n.start&&(n.start=t),n.end=i,n.words.push(e),n.text+=(n.text?" ":"")+r,/[.!?]$/.test(r)&&(s.push({...n}),n={start:0,end:0,text:"",words:[]})})),n.words.length>0&&s.push({...n});let a=[],o=1,l=5;if(s.length>0){let e={start:s[0].start,end:s[0].end,text:s[0].text,words:s[0].words},t=1;for(let i=1;i<s.length;i++){let r=s[i],n=s[i-1];(r.start??0)-(n.end??0)<=o&&t<l?(e.end=r.end,e.text+=" "+r.text,e.words=[...e.words,...r.words],t++):(a.push({...e}),e={start:r.start,end:r.end,text:r.text,words:r.words},t=1)}e.words.length>0&&a.push(e)}return{text:i.text,segments:a}}catch{throw console.warn(`Failed to fetch language file for "${this.embed}"`),new Error}}),(()=>[this.embed]))}set embed(e){this._embed!=e&&(this._embed=e,this.host.requestUpdate())}get embed(){return this._embed}set token(e){this._token!=e&&(this._token=e,this.host.requestUpdate())}get token(){return this._token}get spaceId(){return this.embed.substring(0,5)}get embedId(){return this.embed.substring(5,this.embed.length)}get version(){return this._version?`/v${this._version}/`:"/"}set version(e){this._version!=e&&(this._version=e,this.host.requestUpdate())}get cdnRoot(){return E.cdn.endpoint.replace("${this.spaceId}",this.spaceId)}embedFile(e,t=new URLSearchParams){let i=new URL(`${this.cdnRoot}/${this.embedId}${"manifest"==e?"/":this.version}${e}`);return this.token&&t.append("token",this.token),i.search=t.toString(),i.toString()}render(e){return this.task?.render(e)}},T=globalThis,S=T.trustedTypes,A=S?S.createPolicy("lit-html",{createHTML:e=>e}):void 0,_="$lit$",w=`lit$${(Math.random()+"").slice(9)}$`,k="?"+w,L=`<${k}>`,R=document,I=()=>R.createComment(""),C=e=>null===e||"object"!=typeof e&&"function"!=typeof e,D=Array.isArray,x="[ \t\n\f\r]",M=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,P=/-->/g,O=/>/g,U=RegExp(`>|${x}(?:([^\\s"'>=/]+)(${x}*=${x}*(?:[^ \t\n\f\r"'\`<>=]|("|')|))|$)`,"g"),N=/'/g,$=/"/g,F=/^(?:script|style|textarea|title)$/i,B=(e=>(t,...i)=>({_$litType$:e,strings:t,values:i}))(1),H=Symbol.for("lit-noChange"),G=Symbol.for("lit-nothing"),j=new WeakMap,V=R.createTreeWalker(R,129);function K(e,t){if(!Array.isArray(e)||!e.hasOwnProperty("raw"))throw Error("invalid template strings array");return void 0!==A?A.createHTML(t):t}var W=class e{constructor({strings:t,_$litType$:i},r){let s;this.parts=[];let n=0,a=0,o=t.length-1,l=this.parts,[h,d]=((e,t)=>{let i,r=e.length-1,s=[],n=2===t?"<svg>":"",a=M;for(let t=0;t<r;t++){let r,o,l=e[t],h=-1,d=0;for(;d<l.length&&(a.lastIndex=d,o=a.exec(l),null!==o);)d=a.lastIndex,a===M?"!--"===o[1]?a=P:void 0!==o[1]?a=O:void 0!==o[2]?(F.test(o[2])&&(i=RegExp("</"+o[2],"g")),a=U):void 0!==o[3]&&(a=U):a===U?">"===o[0]?(a=i??M,h=-1):void 0===o[1]?h=-2:(h=a.lastIndex-o[2].length,r=o[1],a=void 0===o[3]?U:'"'===o[3]?$:N):a===$||a===N?a=U:a===P||a===O?a=M:(a=U,i=void 0);let u=a===U&&e[t+1].startsWith("/>")?" ":"";n+=a===M?l+L:h>=0?(s.push(r),l.slice(0,h)+_+l.slice(h)+w+u):l+w+(-2===h?t:u)}return[K(e,n+(e[r]||"<?>")+(2===t?"</svg>":"")),s]})(t,i);if(this.el=e.createElement(h,r),V.currentNode=this.el.content,2===i){let e=this.el.content.firstChild;e.replaceWith(...e.childNodes)}for(;null!==(s=V.nextNode())&&l.length<o;){if(1===s.nodeType){if(s.hasAttributes())for(let e of s.getAttributeNames())if(e.endsWith(_)){let t=d[a++],i=s.getAttribute(e).split(w),r=/([.?@])?(.*)/.exec(t);l.push({type:1,index:n,name:r[2],strings:i,ctor:"."===r[1]?Q:"?"===r[1]?Z:"@"===r[1]?J:X}),s.removeAttribute(e)}else e.startsWith(w)&&(l.push({type:6,index:n}),s.removeAttribute(e));if(F.test(s.tagName)){let e=s.textContent.split(w),t=e.length-1;if(t>0){s.textContent=S?S.emptyScript:"";for(let i=0;i<t;i++)s.append(e[i],I()),V.nextNode(),l.push({type:2,index:++n});s.append(e[t],I())}}}else if(8===s.nodeType)if(s.data===k)l.push({type:2,index:n});else{let e=-1;for(;-1!==(e=s.data.indexOf(w,e+1));)l.push({type:7,index:n}),e+=w.length-1}n++}}static createElement(e,t){let i=R.createElement("template");return i.innerHTML=e,i}};function q(e,t,i=e,r){if(t===H)return t;let s=void 0!==r?i._$Co?.[r]:i._$Cl,n=C(t)?void 0:t._$litDirective$;return s?.constructor!==n&&(s?._$AO?.(!1),void 0===n?s=void 0:(s=new n(e),s._$AT(e,i,r)),void 0!==r?(i._$Co??(i._$Co=[]))[r]=s:i._$Cl=s),void 0!==s&&(t=q(e,s._$AS(e,t.values),s,r)),t}var Y=class{constructor(e,t){this._$AV=[],this._$AN=void 0,this._$AD=e,this._$AM=t}get parentNode(){return this._$AM.parentNode}get _$AU(){return this._$AM._$AU}u(e){let{el:{content:t},parts:i}=this._$AD,r=(e?.creationScope??R).importNode(t,!0);V.currentNode=r;let s=V.nextNode(),n=0,a=0,o=i[0];for(;void 0!==o;){if(n===o.index){let t;2===o.type?t=new z(s,s.nextSibling,this,e):1===o.type?t=new o.ctor(s,o.name,o.strings,this,e):6===o.type&&(t=new ee(s,this,e)),this._$AV.push(t),o=i[++a]}n!==o?.index&&(s=V.nextNode(),n++)}return V.currentNode=R,r}p(e){let t=0;for(let i of this._$AV)void 0!==i&&(void 0!==i.strings?(i._$AI(e,i,t),t+=i.strings.length-2):i._$AI(e[t])),t++}},z=class e{get _$AU(){return this._$AM?._$AU??this._$Cv}constructor(e,t,i,r){this.type=2,this._$AH=G,this._$AN=void 0,this._$AA=e,this._$AB=t,this._$AM=i,this.options=r,this._$Cv=r?.isConnected??!0}get parentNode(){let e=this._$AA.parentNode,t=this._$AM;return void 0!==t&&11===e?.nodeType&&(e=t.parentNode),e}get startNode(){return this._$AA}get endNode(){return this._$AB}_$AI(e,t=this){e=q(this,e,t),C(e)?e===G||null==e||""===e?(this._$AH!==G&&this._$AR(),this._$AH=G):e!==this._$AH&&e!==H&&this._(e):void 0!==e._$litType$?this.$(e):void 0!==e.nodeType?this.T(e):(e=>D(e)||"function"==typeof e?.[Symbol.iterator])(e)?this.k(e):this._(e)}S(e){return this._$AA.parentNode.insertBefore(e,this._$AB)}T(e){this._$AH!==e&&(this._$AR(),this._$AH=this.S(e))}_(e){this._$AH!==G&&C(this._$AH)?this._$AA.nextSibling.data=e:this.T(R.createTextNode(e)),this._$AH=e}$(e){let{values:t,_$litType$:i}=e,r="number"==typeof i?this._$AC(e):(void 0===i.el&&(i.el=W.createElement(K(i.h,i.h[0]),this.options)),i);if(this._$AH?._$AD===r)this._$AH.p(t);else{let e=new Y(r,this),i=e.u(this.options);e.p(t),this.T(i),this._$AH=e}}_$AC(e){let t=j.get(e.strings);return void 0===t&&j.set(e.strings,t=new W(e)),t}k(t){D(this._$AH)||(this._$AH=[],this._$AR());let i,r=this._$AH,s=0;for(let n of t)s===r.length?r.push(i=new e(this.S(I()),this.S(I()),this,this.options)):i=r[s],i._$AI(n),s++;s<r.length&&(this._$AR(i&&i._$AB.nextSibling,s),r.length=s)}_$AR(e=this._$AA.nextSibling,t){for(this._$AP?.(!1,!0,t);e&&e!==this._$AB;){let t=e.nextSibling;e.remove(),e=t}}setConnected(e){void 0===this._$AM&&(this._$Cv=e,this._$AP?.(e))}},X=class{get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}constructor(e,t,i,r,s){this.type=1,this._$AH=G,this._$AN=void 0,this.element=e,this.name=t,this._$AM=r,this.options=s,i.length>2||""!==i[0]||""!==i[1]?(this._$AH=Array(i.length-1).fill(new String),this.strings=i):this._$AH=G}_$AI(e,t=this,i,r){let s=this.strings,n=!1;if(void 0===s)e=q(this,e,t,0),n=!C(e)||e!==this._$AH&&e!==H,n&&(this._$AH=e);else{let r,a,o=e;for(e=s[0],r=0;r<s.length-1;r++)a=q(this,o[i+r],t,r),a===H&&(a=this._$AH[r]),n||(n=!C(a)||a!==this._$AH[r]),a===G?e=G:e!==G&&(e+=(a??"")+s[r+1]),this._$AH[r]=a}n&&!r&&this.j(e)}j(e){e===G?this.element.removeAttribute(this.name):this.element.setAttribute(this.name,e??"")}},Q=class extends X{constructor(){super(...arguments),this.type=3}j(e){this.element[this.name]=e===G?void 0:e}},Z=class extends X{constructor(){super(...arguments),this.type=4}j(e){this.element.toggleAttribute(this.name,!!e&&e!==G)}},J=class extends X{constructor(e,t,i,r,s){super(e,t,i,r,s),this.type=5}_$AI(e,t=this){if((e=q(this,e,t,0)??G)===H)return;let i=this._$AH,r=e===G&&i!==G||e.capture!==i.capture||e.once!==i.once||e.passive!==i.passive,s=e!==G&&(i===G||r);r&&this.element.removeEventListener(this.name,this,i),s&&this.element.addEventListener(this.name,this,e),this._$AH=e}handleEvent(e){"function"==typeof this._$AH?this._$AH.call(this.options?.host??this.element,e):this._$AH.handleEvent(e)}},ee=class{constructor(e,t,i){this.element=e,this.type=6,this._$AN=void 0,this._$AM=t,this.options=i}get _$AU(){return this._$AM._$AU}_$AI(e){q(this,e)}},te=T.litHtmlPolyfillSupport;te?.(W,z),(T.litHtmlVersions??(T.litHtmlVersions=[])).push("3.1.2");var ie=globalThis,re=ie.ShadowRoot&&(void 0===ie.ShadyCSS||ie.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,se=Symbol(),ne=new WeakMap,ae=class{constructor(e,t,i){if(this._$cssResult$=!0,i!==se)throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");this.cssText=e,this.t=t}get styleSheet(){let e=this.o,t=this.t;if(re&&void 0===e){let i=void 0!==t&&1===t.length;i&&(e=ne.get(t)),void 0===e&&((this.o=e=new CSSStyleSheet).replaceSync(this.cssText),i&&ne.set(t,e))}return e}toString(){return this.cssText}},oe=(e,...t)=>{let i=1===e.length?e[0]:t.reduce(((t,i,r)=>t+(e=>{if(!0===e._$cssResult$)return e.cssText;if("number"==typeof e)return e;throw Error("Value passed to 'css' function must be a 'css' function result: "+e+". Use 'unsafeCSS' to pass non-literal values, but take care to ensure page security.")})(i)+e[r+1]),e[0]);return new ae(i,e,se)},le=re?e=>e:e=>e instanceof CSSStyleSheet?(e=>{let t="";for(let i of e.cssRules)t+=i.cssText;return(e=>new ae("string"==typeof e?e:e+"",void 0,se))(t)})(e):e,{is:he,defineProperty:de,getOwnPropertyDescriptor:ue,getOwnPropertyNames:ce,getOwnPropertySymbols:fe,getPrototypeOf:pe}=Object,me=globalThis,ge=me.trustedTypes,ve=ge?ge.emptyScript:"",Ee=me.reactiveElementPolyfillSupport,ye=(e,t)=>e,be={toAttribute(e,t){switch(t){case Boolean:e=e?ve:null;break;case Object:case Array:e=null==e?e:JSON.stringify(e)}return e},fromAttribute(e,t){let i=e;switch(t){case Boolean:i=null!==e;break;case Number:i=null===e?null:Number(e);break;case Object:case Array:try{i=JSON.parse(e)}catch{i=null}}return i}},Te=(e,t)=>!he(e,t),Se={attribute:!0,type:String,converter:be,reflect:!1,hasChanged:Te};Symbol.metadata??(Symbol.metadata=Symbol("metadata")),me.litPropertyMetadata??(me.litPropertyMetadata=new WeakMap);var Ae=class extends HTMLElement{static addInitializer(e){this._$Ei(),(this.l??(this.l=[])).push(e)}static get observedAttributes(){return this.finalize(),this._$Eh&&[...this._$Eh.keys()]}static createProperty(e,t=Se){if(t.state&&(t.attribute=!1),this._$Ei(),this.elementProperties.set(e,t),!t.noAccessor){let i=Symbol(),r=this.getPropertyDescriptor(e,i,t);void 0!==r&&de(this.prototype,e,r)}}static getPropertyDescriptor(e,t,i){let{get:r,set:s}=ue(this.prototype,e)??{get(){return this[t]},set(e){this[t]=e}};return{get(){return r?.call(this)},set(t){let n=r?.call(this);s.call(this,t),this.requestUpdate(e,n,i)},configurable:!0,enumerable:!0}}static getPropertyOptions(e){return this.elementProperties.get(e)??Se}static _$Ei(){if(this.hasOwnProperty(ye("elementProperties")))return;let e=pe(this);e.finalize(),void 0!==e.l&&(this.l=[...e.l]),this.elementProperties=new Map(e.elementProperties)}static finalize(){if(this.hasOwnProperty(ye("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(ye("properties"))){let e=this.properties,t=[...ce(e),...fe(e)];for(let i of t)this.createProperty(i,e[i])}let e=this[Symbol.metadata];if(null!==e){let t=litPropertyMetadata.get(e);if(void 0!==t)for(let[e,i]of t)this.elementProperties.set(e,i)}this._$Eh=new Map;for(let[e,t]of this.elementProperties){let i=this._$Eu(e,t);void 0!==i&&this._$Eh.set(i,e)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(e){let t=[];if(Array.isArray(e)){let i=new Set(e.flat(1/0).reverse());for(let e of i)t.unshift(le(e))}else void 0!==e&&t.push(le(e));return t}static _$Eu(e,t){let i=t.attribute;return!1===i?void 0:"string"==typeof i?i:"string"==typeof e?e.toLowerCase():void 0}constructor(){super(),this._$Ep=void 0,this.isUpdatePending=!1,this.hasUpdated=!1,this._$Em=null,this._$Ev()}_$Ev(){this._$ES=new Promise((e=>this.enableUpdating=e)),this._$AL=new Map,this._$E_(),this.requestUpdate(),this.constructor.l?.forEach((e=>e(this)))}addController(e){(this._$EO??(this._$EO=new Set)).add(e),void 0!==this.renderRoot&&this.isConnected&&e.hostConnected?.()}removeController(e){this._$EO?.delete(e)}_$E_(){let e=new Map,t=this.constructor.elementProperties;for(let i of t.keys())this.hasOwnProperty(i)&&(e.set(i,this[i]),delete this[i]);e.size>0&&(this._$Ep=e)}createRenderRoot(){let e=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return((e,t)=>{if(re)e.adoptedStyleSheets=t.map((e=>e instanceof CSSStyleSheet?e:e.styleSheet));else for(let i of t){let t=document.createElement("style"),r=ie.litNonce;void 0!==r&&t.setAttribute("nonce",r),t.textContent=i.cssText,e.appendChild(t)}})(e,this.constructor.elementStyles),e}connectedCallback(){this.renderRoot??(this.renderRoot=this.createRenderRoot()),this.enableUpdating(!0),this._$EO?.forEach((e=>e.hostConnected?.()))}enableUpdating(e){}disconnectedCallback(){this._$EO?.forEach((e=>e.hostDisconnected?.()))}attributeChangedCallback(e,t,i){this._$AK(e,i)}_$EC(e,t){let i=this.constructor.elementProperties.get(e),r=this.constructor._$Eu(e,i);if(void 0!==r&&!0===i.reflect){let s=(void 0!==i.converter?.toAttribute?i.converter:be).toAttribute(t,i.type);this._$Em=e,null==s?this.removeAttribute(r):this.setAttribute(r,s),this._$Em=null}}_$AK(e,t){let i=this.constructor,r=i._$Eh.get(e);if(void 0!==r&&this._$Em!==r){let e=i.getPropertyOptions(r),s="function"==typeof e.converter?{fromAttribute:e.converter}:void 0!==e.converter?.fromAttribute?e.converter:be;this._$Em=r,this[r]=s.fromAttribute(t,e.type),this._$Em=null}}requestUpdate(e,t,i){if(void 0!==e){if(i??(i=this.constructor.getPropertyOptions(e)),!(i.hasChanged??Te)(this[e],t))return;this.P(e,t,i)}!1===this.isUpdatePending&&(this._$ES=this._$ET())}P(e,t,i){this._$AL.has(e)||this._$AL.set(e,t),!0===i.reflect&&this._$Em!==e&&(this._$Ej??(this._$Ej=new Set)).add(e)}async _$ET(){this.isUpdatePending=!0;try{await this._$ES}catch(e){Promise.reject(e)}let e=this.scheduleUpdate();return null!=e&&await e,!this.isUpdatePending}scheduleUpdate(){return this.performUpdate()}performUpdate(){if(!this.isUpdatePending)return;if(!this.hasUpdated){if(this.renderRoot??(this.renderRoot=this.createRenderRoot()),this._$Ep){for(let[e,t]of this._$Ep)this[e]=t;this._$Ep=void 0}let e=this.constructor.elementProperties;if(e.size>0)for(let[t,i]of e)!0!==i.wrapped||this._$AL.has(t)||void 0===this[t]||this.P(t,this[t],i)}let e=!1,t=this._$AL;try{e=this.shouldUpdate(t),e?(this.willUpdate(t),this._$EO?.forEach((e=>e.hostUpdate?.())),this.update(t)):this._$EU()}catch(t){throw e=!1,this._$EU(),t}e&&this._$AE(t)}willUpdate(e){}_$AE(e){this._$EO?.forEach((e=>e.hostUpdated?.())),this.hasUpdated||(this.hasUpdated=!0,this.firstUpdated(e)),this.updated(e)}_$EU(){this._$AL=new Map,this.isUpdatePending=!1}get updateComplete(){return this.getUpdateComplete()}getUpdateComplete(){return this._$ES}shouldUpdate(e){return!0}update(e){this._$Ej&&(this._$Ej=this._$Ej.forEach((e=>this._$EC(e,this[e])))),this._$EU()}updated(e){}firstUpdated(e){}};Ae.elementStyles=[],Ae.shadowRootOptions={mode:"open"},Ae[ye("elementProperties")]=new Map,Ae[ye("finalized")]=new Map,Ee?.({ReactiveElement:Ae}),(me.reactiveElementVersions??(me.reactiveElementVersions=[])).push("2.0.4");var _e=class extends Ae{constructor(){super(...arguments),this.renderOptions={host:this},this._$Do=void 0}createRenderRoot(){var e;let t=super.createRenderRoot();return(e=this.renderOptions).renderBefore??(e.renderBefore=t.firstChild),t}update(e){let t=this.render();this.hasUpdated||(this.renderOptions.isConnected=this.isConnected),super.update(e),this._$Do=((e,t,i)=>{let r=i?.renderBefore??t,s=r._$litPart$;if(void 0===s){let e=i?.renderBefore??null;r._$litPart$=s=new z(t.insertBefore(I(),e),e,void 0,i??{})}return s._$AI(e),s})(t,this.renderRoot,this.renderOptions)}connectedCallback(){super.connectedCallback(),this._$Do?.setConnected(!0)}disconnectedCallback(){super.disconnectedCallback(),this._$Do?.setConnected(!1)}render(){return H}};_e._$litElement$=!0,_e.finalized=!0,globalThis.litElementHydrateSupport?.({LitElement:_e});var we=globalThis.litElementPolyfillSupport;we?.({LitElement:_e}),(globalThis.litElementVersions??(globalThis.litElementVersions=[])).push("4.0.4");var ke=globalThis,Le=ke.ShadowRoot&&(void 0===ke.ShadyCSS||ke.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,Re=Symbol(),Ie=new WeakMap,Ce=class{constructor(e,t,i){if(this._$cssResult$=!0,i!==Re)throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");this.cssText=e,this.t=t}get styleSheet(){let e=this.o,t=this.t;if(Le&&void 0===e){let i=void 0!==t&&1===t.length;i&&(e=Ie.get(t)),void 0===e&&((this.o=e=new CSSStyleSheet).replaceSync(this.cssText),i&&Ie.set(t,e))}return e}toString(){return this.cssText}},De=Le?e=>e:e=>e instanceof CSSStyleSheet?(e=>{let t="";for(let i of e.cssRules)t+=i.cssText;return(e=>new Ce("string"==typeof e?e:e+"",void 0,Re))(t)})(e):e,{is:xe,defineProperty:Me,getOwnPropertyDescriptor:Pe,getOwnPropertyNames:Oe,getOwnPropertySymbols:Ue,getPrototypeOf:Ne}=Object,$e=globalThis,Fe=$e.trustedTypes,Be=Fe?Fe.emptyScript:"",He=$e.reactiveElementPolyfillSupport,Ge=(e,t)=>e,je={toAttribute(e,t){switch(t){case Boolean:e=e?Be:null;break;case Object:case Array:e=null==e?e:JSON.stringify(e)}return e},fromAttribute(e,t){let i=e;switch(t){case Boolean:i=null!==e;break;case Number:i=null===e?null:Number(e);break;case Object:case Array:try{i=JSON.parse(e)}catch{i=null}}return i}},Ve=(e,t)=>!xe(e,t),Ke={attribute:!0,type:String,converter:je,reflect:!1,hasChanged:Ve};Symbol.metadata??(Symbol.metadata=Symbol("metadata")),$e.litPropertyMetadata??($e.litPropertyMetadata=new WeakMap);var We=class extends HTMLElement{static addInitializer(e){this._$Ei(),(this.l??(this.l=[])).push(e)}static get observedAttributes(){return this.finalize(),this._$Eh&&[...this._$Eh.keys()]}static createProperty(e,t=Ke){if(t.state&&(t.attribute=!1),this._$Ei(),this.elementProperties.set(e,t),!t.noAccessor){let i=Symbol(),r=this.getPropertyDescriptor(e,i,t);void 0!==r&&Me(this.prototype,e,r)}}static getPropertyDescriptor(e,t,i){let{get:r,set:s}=Pe(this.prototype,e)??{get(){return this[t]},set(e){this[t]=e}};return{get(){return r?.call(this)},set(t){let n=r?.call(this);s.call(this,t),this.requestUpdate(e,n,i)},configurable:!0,enumerable:!0}}static getPropertyOptions(e){return this.elementProperties.get(e)??Ke}static _$Ei(){if(this.hasOwnProperty(Ge("elementProperties")))return;let e=Ne(this);e.finalize(),void 0!==e.l&&(this.l=[...e.l]),this.elementProperties=new Map(e.elementProperties)}static finalize(){if(this.hasOwnProperty(Ge("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(Ge("properties"))){let e=this.properties,t=[...Oe(e),...Ue(e)];for(let i of t)this.createProperty(i,e[i])}let e=this[Symbol.metadata];if(null!==e){let t=litPropertyMetadata.get(e);if(void 0!==t)for(let[e,i]of t)this.elementProperties.set(e,i)}this._$Eh=new Map;for(let[e,t]of this.elementProperties){let i=this._$Eu(e,t);void 0!==i&&this._$Eh.set(i,e)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(e){let t=[];if(Array.isArray(e)){let i=new Set(e.flat(1/0).reverse());for(let e of i)t.unshift(De(e))}else void 0!==e&&t.push(De(e));return t}static _$Eu(e,t){let i=t.attribute;return!1===i?void 0:"string"==typeof i?i:"string"==typeof e?e.toLowerCase():void 0}constructor(){super(),this._$Ep=void 0,this.isUpdatePending=!1,this.hasUpdated=!1,this._$Em=null,this._$Ev()}_$Ev(){this._$ES=new Promise((e=>this.enableUpdating=e)),this._$AL=new Map,this._$E_(),this.requestUpdate(),this.constructor.l?.forEach((e=>e(this)))}addController(e){(this._$EO??(this._$EO=new Set)).add(e),void 0!==this.renderRoot&&this.isConnected&&e.hostConnected?.()}removeController(e){this._$EO?.delete(e)}_$E_(){let e=new Map,t=this.constructor.elementProperties;for(let i of t.keys())this.hasOwnProperty(i)&&(e.set(i,this[i]),delete this[i]);e.size>0&&(this._$Ep=e)}createRenderRoot(){let e=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return((e,t)=>{if(Le)e.adoptedStyleSheets=t.map((e=>e instanceof CSSStyleSheet?e:e.styleSheet));else for(let i of t){let t=document.createElement("style"),r=ke.litNonce;void 0!==r&&t.setAttribute("nonce",r),t.textContent=i.cssText,e.appendChild(t)}})(e,this.constructor.elementStyles),e}connectedCallback(){this.renderRoot??(this.renderRoot=this.createRenderRoot()),this.enableUpdating(!0),this._$EO?.forEach((e=>e.hostConnected?.()))}enableUpdating(e){}disconnectedCallback(){this._$EO?.forEach((e=>e.hostDisconnected?.()))}attributeChangedCallback(e,t,i){this._$AK(e,i)}_$EC(e,t){let i=this.constructor.elementProperties.get(e),r=this.constructor._$Eu(e,i);if(void 0!==r&&!0===i.reflect){let s=(void 0!==i.converter?.toAttribute?i.converter:je).toAttribute(t,i.type);this._$Em=e,null==s?this.removeAttribute(r):this.setAttribute(r,s),this._$Em=null}}_$AK(e,t){let i=this.constructor,r=i._$Eh.get(e);if(void 0!==r&&this._$Em!==r){let e=i.getPropertyOptions(r),s="function"==typeof e.converter?{fromAttribute:e.converter}:void 0!==e.converter?.fromAttribute?e.converter:je;this._$Em=r,this[r]=s.fromAttribute(t,e.type),this._$Em=null}}requestUpdate(e,t,i){if(void 0!==e){if(i??(i=this.constructor.getPropertyOptions(e)),!(i.hasChanged??Ve)(this[e],t))return;this.P(e,t,i)}!1===this.isUpdatePending&&(this._$ES=this._$ET())}P(e,t,i){this._$AL.has(e)||this._$AL.set(e,t),!0===i.reflect&&this._$Em!==e&&(this._$Ej??(this._$Ej=new Set)).add(e)}async _$ET(){this.isUpdatePending=!0;try{await this._$ES}catch(e){Promise.reject(e)}let e=this.scheduleUpdate();return null!=e&&await e,!this.isUpdatePending}scheduleUpdate(){return this.performUpdate()}performUpdate(){if(!this.isUpdatePending)return;if(!this.hasUpdated){if(this.renderRoot??(this.renderRoot=this.createRenderRoot()),this._$Ep){for(let[e,t]of this._$Ep)this[e]=t;this._$Ep=void 0}let e=this.constructor.elementProperties;if(e.size>0)for(let[t,i]of e)!0!==i.wrapped||this._$AL.has(t)||void 0===this[t]||this.P(t,this[t],i)}let e=!1,t=this._$AL;try{e=this.shouldUpdate(t),e?(this.willUpdate(t),this._$EO?.forEach((e=>e.hostUpdate?.())),this.update(t)):this._$EU()}catch(t){throw e=!1,this._$EU(),t}e&&this._$AE(t)}willUpdate(e){}_$AE(e){this._$EO?.forEach((e=>e.hostUpdated?.())),this.hasUpdated||(this.hasUpdated=!0,this.firstUpdated(e)),this.updated(e)}_$EU(){this._$AL=new Map,this.isUpdatePending=!1}get updateComplete(){return this.getUpdateComplete()}getUpdateComplete(){return this._$ES}shouldUpdate(e){return!0}update(e){this._$Ej&&(this._$Ej=this._$Ej.forEach((e=>this._$EC(e,this[e])))),this._$EU()}updated(e){}firstUpdated(e){}};We.elementStyles=[],We.shadowRootOptions={mode:"open"},We[Ge("elementProperties")]=new Map,We[Ge("finalized")]=new Map,He?.({ReactiveElement:We}),($e.reactiveElementVersions??($e.reactiveElementVersions=[])).push("2.0.4");var qe=e=>e??G,Ye=1,ze=2,Xe=e=>(...t)=>({_$litDirective$:e,values:t}),Qe=class{constructor(e){}get _$AU(){return this._$AM._$AU}_$AT(e,t,i){this._$Ct=e,this._$AM=t,this._$Ci=i}_$AS(e,t){return this.update(e,t)}update(e,t){return this.render(...t)}},Ze="important",Je=" !"+Ze,et=Xe(class extends Qe{constructor(e){if(super(e),e.type!==Ye||"style"!==e.name||e.strings?.length>2)throw Error("The `styleMap` directive must be used in the `style` attribute and must be the only part in the attribute.")}render(e){return Object.keys(e).reduce(((t,i)=>{let r=e[i];return null==r?t:t+`${i=i.includes("-")?i:i.replace(/(?:^(webkit|moz|ms|o)|)(?=[A-Z])/g,"-$&").toLowerCase()}:${r};`}),"")}update(e,[t]){let{style:i}=e.element;if(void 0===this.ft)return this.ft=new Set(Object.keys(t)),this.render(t);for(let e of this.ft)null==t[e]&&(this.ft.delete(e),e.includes("-")?i.removeProperty(e):i[e]=null);for(let e in t){let r=t[e];if(null!=r){this.ft.add(e);let t="string"==typeof r&&r.endsWith(Je);e.includes("-")||t?i.setProperty(e,t?r.slice(0,-11):r,t?Ze:""):i[e]=r}}return H}}),tt={attribute:!0,type:String,converter:je,reflect:!1,hasChanged:Ve},it=(e=tt,t,i)=>{let{kind:r,metadata:s}=i,n=globalThis.litPropertyMetadata.get(s);if(void 0===n&&globalThis.litPropertyMetadata.set(s,n=new Map),n.set(i.name,e),"accessor"===r){let{name:r}=i;return{set(i){let s=t.get.call(this);t.set.call(this,i),this.requestUpdate(r,s,e)},init(t){return void 0!==t&&this.P(r,void 0,e),t}}}if("setter"===r){let{name:r}=i;return function(i){let s=this[r];t.call(this,i),this.requestUpdate(r,s,e)}}throw Error("Unsupported decorator location: "+r)};function rt(e){return(t,i)=>"object"==typeof i?it(e,t,i):((e,t,i)=>{let r=t.hasOwnProperty(i);return t.constructor.createProperty(i,r?{...e,wrapped:!0}:e),r?Object.getOwnPropertyDescriptor(t,i):void 0})(e,t,i)}function st(e){return rt({...e,state:!0,attribute:!1})}var nt=(e,t,i)=>(i.configurable=!0,i.enumerable=!0,Reflect.decorate&&"object"!=typeof t&&Object.defineProperty(e,t,i),i);function at(e,t){return(i,r,s)=>{let n=t=>t.renderRoot?.querySelector(e)??null;if(t){let{get:e,set:t}="object"==typeof r?i:s??(()=>{let e=Symbol();return{get(){return this[e]},set(t){this[e]=t}}})();return nt(i,r,{get(){let i=e.call(this);return void 0===i&&(i=n(this),(null!==i||this.hasUpdated)&&t.call(this,i)),i}})}return nt(i,r,{get(){return n(this)}})}}var ot,lt,ht,dt,ut=Object.create,ct=Object.defineProperty,ft=Object.getOwnPropertyDescriptor,pt=Object.getOwnPropertyNames,mt=Object.getPrototypeOf,gt=Object.prototype.hasOwnProperty,vt=e=>{throw TypeError(e)},Et=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),yt=(e,t,i)=>(i=null!=e?ut(mt(e)):{},((e,t,i,r)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let s of pt(t))!gt.call(e,s)&&s!==i&&ct(e,s,{get:()=>t[s],enumerable:!(r=ft(t,s))||r.enumerable});return e})(!t&&e&&e.__esModule?i:ct(i,"default",{value:e,enumerable:!0}),e)),bt=(e,t,i,r)=>{for(var s,n=r>1?void 0:r?ft(t,i):t,a=e.length-1;a>=0;a--)(s=e[a])&&(n=(r?s(t,i,n):s(n))||n);return r&&n&&ct(t,i,n),n},Tt=(e,t,i)=>t.has(e)||vt("Cannot "+i),St=(e,t,i)=>(Tt(e,t,"read from private field"),i?i.call(e):t.get(e)),At=(e,t,i)=>t.has(e)?vt("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,i),_t=(e,t,i)=>(Tt(e,t,"access private method"),i),wt=class extends _e{constructor(){super(...arguments),At(this,ot),this._clickable=!0,this._autoscroll=!0,this._lastScrollTime=0,this.currentTime=0}get embed(){return this._embedId}set embed(e){this._embedId!=e&&(this._embedId=e,this.captionController=new b(this,this.embed),this.reset(),this.requestUpdate("embed"))}get clickable(){return this._clickable}set clickable(e){this._clickable!=e&&(this._clickable="string"==typeof e?"true"===e||""===e:e,this.requestUpdate("clickable"))}get autoscroll(){return this._autoscroll}set autoscroll(e){this._autoscroll!=e&&(this._autoscroll="string"==typeof e?"true"===e||""===e:e,this.requestUpdate("autoscroll"))}get wordIndex(){return this._wordIndex}set wordIndex(e){if(this._wordIndex!=e&&(this._wordIndex=e,this.autoscroll)){let e=this.shadowRoot?.querySelector(`[data-word-id="word-${this.segmentIndex}-${this.wordIndex}"]`);if(e&&this._lastScrollTime+2500<Date.now()){let t=this.getBoundingClientRect(),i=e.getBoundingClientRect(),r=i.top-t.top;if(r>0){let e=this.scrollTop+r;_t(this,ot,lt).call(this,this,e-i.height/2)}}}}get segmentIndex(){return this._segmentIndex}set segmentIndex(e){this._segmentIndex!=e&&(this._segmentIndex=e)}connectedCallback(){super.connectedCallback(),this.addEventListener("scroll",_t(this,ot,ht).bind(this)),this.reset()}reset(){this.loop=!1,this.currentTime=0,this.wordIndex=0,this.segmentIndex=0;let e=document.querySelector(`mave-player[embed="${this.embed}"]`);e&&(this.player=e,e.addEventListener("play",(()=>{this.loop=!0,this.loopUpdateTime()})),e.addEventListener("pause",(()=>{this.loop=!1})))}updateTime(){this.currentTime=this.player.currentTime}loopUpdateTime(){this.updateTime(),setTimeout((()=>{this.loop&&requestAnimationFrame(this.loopUpdateTime.bind(this))}),10)}inRange({start:e,end:t},i,r,s){if(this.currentTime>=e&&this.currentTime<=t)return s&&(this.wordIndex=s),r&&(this.segmentIndex=r),i||!0}segmentStyle(){return this.clickable?{cursor:"pointer"}:{}}wordStyle(e){return e?{"background-color":this.highlight}:{}}render(){return this.captionController?this.captionController.render({complete:e=>(this.captions=e,B`
          <div>
            ${this.captions.segments.map(((e,t)=>B`
                <p
                  data-segment-id="segment-${t}"
                  style=${et(this.segmentStyle())}
                  @click=${this.clickable?_t(this,ot,dt):G}
                  part=${qe(this.inRange(e,"segment"))}
                  x-caption-segment-start="${e.start}"
                  x-caption-segment-end="${e.end}"
                >
                  ${e.words.map(((e,i)=>B`
                      <span
                        data-word-id="word-${t}-${i}"
                        style=${et(this.wordStyle(this.inRange(e)))}
                        part=${qe(this.inRange(e,"word",t,i))}
                        x-caption-word-start="${e.start}"
                        x-caption-word-end="${e.end}"
                        >${e.word.trim()}</span
                      >
                    `))}
                </p>
              `))}
          </div>
        `)}):G}};ot=new WeakSet,lt=function(e,t,i=500){let r=this.scrollTop,s=t-r,n=null,a=!1;a=!0,requestAnimationFrame((function t(o){n||(n=o);let l=o-n,h=Math.min(l/i,1);e.scrollTop=r+s*function(e){return e<.5?2*e*e:1-Math.pow(-2*e+2,2)/2}(h),l<i&&a?requestAnimationFrame(t):a=!1}))},ht=function(){this._lastScrollTime=Date.now()},dt=function(e){if(this.clickable){let t=e.target.closest("p");if(t&&this.player){let e=t.getAttribute("x-caption-segment-start");this.player.currentTime=Number(e),this.player.paused&&this.player.play()}}},wt.styles=oe`
    :host {
      display: block;
      width: 100%;
      height: 100%;
    }

    [part='word'] {
      background-color: rgba(255, 210, 42, 0.5);
    }
  `,bt([rt()],wt.prototype,"embed",1),bt([rt()],wt.prototype,"highlight",2),bt([rt()],wt.prototype,"clickable",1),bt([rt()],wt.prototype,"autoscroll",1),bt([st()],wt.prototype,"currentTime",2),bt([st()],wt.prototype,"captions",2),window&&window.customElements&&(window.customElements.get("mave-text")||window.customElements.define("mave-text",wt));var kt="undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},Lt=[],Rt=[],It="undefined"!=typeof Uint8Array?Uint8Array:Array,Ct=!1;function Dt(){Ct=!0;for(var e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",t=0;t<64;++t)Lt[t]=e[t],Rt[e.charCodeAt(t)]=t;Rt["-".charCodeAt(0)]=62,Rt["_".charCodeAt(0)]=63}function xt(e,t,i){for(var r,s,n=[],a=t;a<i;a+=3)r=(e[a]<<16)+(e[a+1]<<8)+e[a+2],n.push(Lt[(s=r)>>18&63]+Lt[s>>12&63]+Lt[s>>6&63]+Lt[63&s]);return n.join("")}function Mt(e){var t;Ct||Dt();for(var i=e.length,r=i%3,s="",n=[],a=16383,o=0,l=i-r;o<l;o+=a)n.push(xt(e,o,o+a>l?l:o+a));return 1===r?(t=e[i-1],s+=Lt[t>>2],s+=Lt[t<<4&63],s+="=="):2===r&&(t=(e[i-2]<<8)+e[i-1],s+=Lt[t>>10],s+=Lt[t>>4&63],s+=Lt[t<<2&63],s+="="),n.push(s),n.join("")}function Pt(e,t,i,r,s){var n,a,o=8*s-r-1,l=(1<<o)-1,h=l>>1,d=-7,u=i?s-1:0,c=i?-1:1,f=e[t+u];for(u+=c,n=f&(1<<-d)-1,f>>=-d,d+=o;d>0;n=256*n+e[t+u],u+=c,d-=8);for(a=n&(1<<-d)-1,n>>=-d,d+=r;d>0;a=256*a+e[t+u],u+=c,d-=8);if(0===n)n=1-h;else{if(n===l)return a?NaN:1/0*(f?-1:1);a+=Math.pow(2,r),n-=h}return(f?-1:1)*a*Math.pow(2,n-r)}function Ot(e,t,i,r,s,n){var a,o,l,h=8*n-s-1,d=(1<<h)-1,u=d>>1,c=23===s?Math.pow(2,-24)-Math.pow(2,-77):0,f=r?0:n-1,p=r?1:-1,m=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(o=isNaN(t)?1:0,a=d):(a=Math.floor(Math.log(t)/Math.LN2),t*(l=Math.pow(2,-a))<1&&(a--,l*=2),(t+=a+u>=1?c/l:c*Math.pow(2,1-u))*l>=2&&(a++,l/=2),a+u>=d?(o=0,a=d):a+u>=1?(o=(t*l-1)*Math.pow(2,s),a+=u):(o=t*Math.pow(2,u-1)*Math.pow(2,s),a=0));s>=8;e[i+f]=255&o,f+=p,o/=256,s-=8);for(a=a<<s|o,h+=s;h>0;e[i+f]=255&a,f+=p,a/=256,h-=8);e[i+f-p]|=128*m}var Ut={}.toString,Nt=Array.isArray||function(e){return"[object Array]"==Ut.call(e)};function $t(){return Bt.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function Ft(e,t){if($t()<t)throw new RangeError("Invalid typed array length");return Bt.TYPED_ARRAY_SUPPORT?(e=new Uint8Array(t)).__proto__=Bt.prototype:(null===e&&(e=new Bt(t)),e.length=t),e}function Bt(e,t,i){if(!(Bt.TYPED_ARRAY_SUPPORT||this instanceof Bt))return new Bt(e,t,i);if("number"==typeof e){if("string"==typeof t)throw new Error("If encoding is specified then the first argument must be a string");return jt(this,e)}return Ht(this,e,t,i)}function Ht(e,t,i,r){if("number"==typeof t)throw new TypeError('"value" argument must not be a number');return"undefined"!=typeof ArrayBuffer&&t instanceof ArrayBuffer?function(e,t,i,r){if(t.byteLength,i<0||t.byteLength<i)throw new RangeError("'offset' is out of bounds");if(t.byteLength<i+(r||0))throw new RangeError("'length' is out of bounds");t=void 0===i&&void 0===r?new Uint8Array(t):void 0===r?new Uint8Array(t,i):new Uint8Array(t,i,r);Bt.TYPED_ARRAY_SUPPORT?(e=t).__proto__=Bt.prototype:e=Vt(e,t);return e}(e,t,i,r):"string"==typeof t?function(e,t,i){"string"==typeof i&&""!==i||(i="utf8");if(!Bt.isEncoding(i))throw new TypeError('"encoding" must be a valid string encoding');var r=0|qt(t,i);e=Ft(e,r);var s=e.write(t,i);s!==r&&(e=e.slice(0,s));return e}(e,t,i):function(e,t){if(Wt(t)){var i=0|Kt(t.length);return 0===(e=Ft(e,i)).length||t.copy(e,0,0,i),e}if(t){if("undefined"!=typeof ArrayBuffer&&t.buffer instanceof ArrayBuffer||"length"in t)return"number"!=typeof t.length||(r=t.length)!=r?Ft(e,0):Vt(e,t);if("Buffer"===t.type&&Nt(t.data))return Vt(e,t.data)}var r;throw new TypeError("First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.")}(e,t)}function Gt(e){if("number"!=typeof e)throw new TypeError('"size" argument must be a number');if(e<0)throw new RangeError('"size" argument must not be negative')}function jt(e,t){if(Gt(t),e=Ft(e,t<0?0:0|Kt(t)),!Bt.TYPED_ARRAY_SUPPORT)for(var i=0;i<t;++i)e[i]=0;return e}function Vt(e,t){var i=t.length<0?0:0|Kt(t.length);e=Ft(e,i);for(var r=0;r<i;r+=1)e[r]=255&t[r];return e}function Kt(e){if(e>=$t())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+$t().toString(16)+" bytes");return 0|e}function Wt(e){return!(null==e||!e._isBuffer)}function qt(e,t){if(Wt(e))return e.length;if("undefined"!=typeof ArrayBuffer&&"function"==typeof ArrayBuffer.isView&&(ArrayBuffer.isView(e)||e instanceof ArrayBuffer))return e.byteLength;"string"!=typeof e&&(e=""+e);var i=e.length;if(0===i)return 0;for(var r=!1;;)switch(t){case"ascii":case"latin1":case"binary":return i;case"utf8":case"utf-8":case void 0:return bi(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*i;case"hex":return i>>>1;case"base64":return Ti(e).length;default:if(r)return bi(e).length;t=(""+t).toLowerCase(),r=!0}}function Yt(e,t,i){var r=!1;if((void 0===t||t<0)&&(t=0),t>this.length)return"";if((void 0===i||i>this.length)&&(i=this.length),i<=0)return"";if((i>>>=0)<=(t>>>=0))return"";for(e||(e="utf8");;)switch(e){case"hex":return hi(this,t,i);case"utf8":case"utf-8":return ni(this,t,i);case"ascii":return oi(this,t,i);case"latin1":case"binary":return li(this,t,i);case"base64":return si(this,t,i);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return di(this,t,i);default:if(r)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),r=!0}}function zt(e,t,i){var r=e[t];e[t]=e[i],e[i]=r}function Xt(e,t,i,r,s){if(0===e.length)return-1;if("string"==typeof i?(r=i,i=0):i>2147483647?i=2147483647:i<-2147483648&&(i=-2147483648),i=+i,isNaN(i)&&(i=s?0:e.length-1),i<0&&(i=e.length+i),i>=e.length){if(s)return-1;i=e.length-1}else if(i<0){if(!s)return-1;i=0}if("string"==typeof t&&(t=Bt.from(t,r)),Wt(t))return 0===t.length?-1:Qt(e,t,i,r,s);if("number"==typeof t)return t&=255,Bt.TYPED_ARRAY_SUPPORT&&"function"==typeof Uint8Array.prototype.indexOf?s?Uint8Array.prototype.indexOf.call(e,t,i):Uint8Array.prototype.lastIndexOf.call(e,t,i):Qt(e,[t],i,r,s);throw new TypeError("val must be string, number or Buffer")}function Qt(e,t,i,r,s){var n,a=1,o=e.length,l=t.length;if(void 0!==r&&("ucs2"===(r=String(r).toLowerCase())||"ucs-2"===r||"utf16le"===r||"utf-16le"===r)){if(e.length<2||t.length<2)return-1;a=2,o/=2,l/=2,i/=2}function h(e,t){return 1===a?e[t]:e.readUInt16BE(t*a)}if(s){var d=-1;for(n=i;n<o;n++)if(h(e,n)===h(t,-1===d?0:n-d)){if(-1===d&&(d=n),n-d+1===l)return d*a}else-1!==d&&(n-=n-d),d=-1}else for(i+l>o&&(i=o-l),n=i;n>=0;n--){for(var u=!0,c=0;c<l;c++)if(h(e,n+c)!==h(t,c)){u=!1;break}if(u)return n}return-1}function Zt(e,t,i,r){i=Number(i)||0;var s=e.length-i;r?(r=Number(r))>s&&(r=s):r=s;var n=t.length;if(n%2!=0)throw new TypeError("Invalid hex string");r>n/2&&(r=n/2);for(var a=0;a<r;++a){var o=parseInt(t.substr(2*a,2),16);if(isNaN(o))return a;e[i+a]=o}return a}function Jt(e,t,i,r){return Si(bi(t,e.length-i),e,i,r)}function ei(e,t,i,r){return Si(function(e){for(var t=[],i=0;i<e.length;++i)t.push(255&e.charCodeAt(i));return t}(t),e,i,r)}function ti(e,t,i,r){return ei(e,t,i,r)}function ii(e,t,i,r){return Si(Ti(t),e,i,r)}function ri(e,t,i,r){return Si(function(e,t){for(var i,r,s,n=[],a=0;a<e.length&&!((t-=2)<0);++a)r=(i=e.charCodeAt(a))>>8,s=i%256,n.push(s),n.push(r);return n}(t,e.length-i),e,i,r)}function si(e,t,i){return 0===t&&i===e.length?Mt(e):Mt(e.slice(t,i))}function ni(e,t,i){i=Math.min(e.length,i);for(var r=[],s=t;s<i;){var n,a,o,l,h=e[s],d=null,u=h>239?4:h>223?3:h>191?2:1;if(s+u<=i)switch(u){case 1:h<128&&(d=h);break;case 2:128==(192&(n=e[s+1]))&&(l=(31&h)<<6|63&n)>127&&(d=l);break;case 3:n=e[s+1],a=e[s+2],128==(192&n)&&128==(192&a)&&(l=(15&h)<<12|(63&n)<<6|63&a)>2047&&(l<55296||l>57343)&&(d=l);break;case 4:n=e[s+1],a=e[s+2],o=e[s+3],128==(192&n)&&128==(192&a)&&128==(192&o)&&(l=(15&h)<<18|(63&n)<<12|(63&a)<<6|63&o)>65535&&l<1114112&&(d=l)}null===d?(d=65533,u=1):d>65535&&(d-=65536,r.push(d>>>10&1023|55296),d=56320|1023&d),r.push(d),s+=u}return function(e){var t=e.length;if(t<=ai)return String.fromCharCode.apply(String,e);var i="",r=0;for(;r<t;)i+=String.fromCharCode.apply(String,e.slice(r,r+=ai));return i}(r)}Bt.TYPED_ARRAY_SUPPORT=void 0===kt.TYPED_ARRAY_SUPPORT||kt.TYPED_ARRAY_SUPPORT,$t(),Bt.poolSize=8192,Bt._augment=function(e){return e.__proto__=Bt.prototype,e},Bt.from=function(e,t,i){return Ht(null,e,t,i)},Bt.TYPED_ARRAY_SUPPORT&&(Bt.prototype.__proto__=Uint8Array.prototype,Bt.__proto__=Uint8Array,"undefined"!=typeof Symbol&&Symbol.species&&Bt[Symbol.species]),Bt.alloc=function(e,t,i){return function(e,t,i,r){return Gt(t),t<=0?Ft(e,t):void 0!==i?"string"==typeof r?Ft(e,t).fill(i,r):Ft(e,t).fill(i):Ft(e,t)}(null,e,t,i)},Bt.allocUnsafe=function(e){return jt(null,e)},Bt.allocUnsafeSlow=function(e){return jt(null,e)},Bt.isBuffer=function(e){return null!=e&&(!!e._isBuffer||Ai(e)||function(e){return"function"==typeof e.readFloatLE&&"function"==typeof e.slice&&Ai(e.slice(0,0))}(e))},Bt.compare=function(e,t){if(!Wt(e)||!Wt(t))throw new TypeError("Arguments must be Buffers");if(e===t)return 0;for(var i=e.length,r=t.length,s=0,n=Math.min(i,r);s<n;++s)if(e[s]!==t[s]){i=e[s],r=t[s];break}return i<r?-1:r<i?1:0},Bt.isEncoding=function(e){switch(String(e).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},Bt.concat=function(e,t){if(!Nt(e))throw new TypeError('"list" argument must be an Array of Buffers');if(0===e.length)return Bt.alloc(0);var i;if(void 0===t)for(t=0,i=0;i<e.length;++i)t+=e[i].length;var r=Bt.allocUnsafe(t),s=0;for(i=0;i<e.length;++i){var n=e[i];if(!Wt(n))throw new TypeError('"list" argument must be an Array of Buffers');n.copy(r,s),s+=n.length}return r},Bt.byteLength=qt,Bt.prototype._isBuffer=!0,Bt.prototype.swap16=function(){var e=this.length;if(e%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(var t=0;t<e;t+=2)zt(this,t,t+1);return this},Bt.prototype.swap32=function(){var e=this.length;if(e%4!=0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(var t=0;t<e;t+=4)zt(this,t,t+3),zt(this,t+1,t+2);return this},Bt.prototype.swap64=function(){var e=this.length;if(e%8!=0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(var t=0;t<e;t+=8)zt(this,t,t+7),zt(this,t+1,t+6),zt(this,t+2,t+5),zt(this,t+3,t+4);return this},Bt.prototype.toString=function(){var e=0|this.length;return 0===e?"":0===arguments.length?ni(this,0,e):Yt.apply(this,arguments)},Bt.prototype.equals=function(e){if(!Wt(e))throw new TypeError("Argument must be a Buffer");return this===e||0===Bt.compare(this,e)},Bt.prototype.inspect=function(){var e="";return this.length>0&&(e=this.toString("hex",0,50).match(/.{2}/g).join(" "),this.length>50&&(e+=" ... ")),"<Buffer "+e+">"},Bt.prototype.compare=function(e,t,i,r,s){if(!Wt(e))throw new TypeError("Argument must be a Buffer");if(void 0===t&&(t=0),void 0===i&&(i=e?e.length:0),void 0===r&&(r=0),void 0===s&&(s=this.length),t<0||i>e.length||r<0||s>this.length)throw new RangeError("out of range index");if(r>=s&&t>=i)return 0;if(r>=s)return-1;if(t>=i)return 1;if(this===e)return 0;for(var n=(s>>>=0)-(r>>>=0),a=(i>>>=0)-(t>>>=0),o=Math.min(n,a),l=this.slice(r,s),h=e.slice(t,i),d=0;d<o;++d)if(l[d]!==h[d]){n=l[d],a=h[d];break}return n<a?-1:a<n?1:0},Bt.prototype.includes=function(e,t,i){return-1!==this.indexOf(e,t,i)},Bt.prototype.indexOf=function(e,t,i){return Xt(this,e,t,i,!0)},Bt.prototype.lastIndexOf=function(e,t,i){return Xt(this,e,t,i,!1)},Bt.prototype.write=function(e,t,i,r){if(void 0===t)r="utf8",i=this.length,t=0;else if(void 0===i&&"string"==typeof t)r=t,i=this.length,t=0;else{if(!isFinite(t))throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");t|=0,isFinite(i)?(i|=0,void 0===r&&(r="utf8")):(r=i,i=void 0)}var s=this.length-t;if((void 0===i||i>s)&&(i=s),e.length>0&&(i<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");r||(r="utf8");for(var n=!1;;)switch(r){case"hex":return Zt(this,e,t,i);case"utf8":case"utf-8":return Jt(this,e,t,i);case"ascii":return ei(this,e,t,i);case"latin1":case"binary":return ti(this,e,t,i);case"base64":return ii(this,e,t,i);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return ri(this,e,t,i);default:if(n)throw new TypeError("Unknown encoding: "+r);r=(""+r).toLowerCase(),n=!0}},Bt.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var ai=4096;function oi(e,t,i){var r="";i=Math.min(e.length,i);for(var s=t;s<i;++s)r+=String.fromCharCode(127&e[s]);return r}function li(e,t,i){var r="";i=Math.min(e.length,i);for(var s=t;s<i;++s)r+=String.fromCharCode(e[s]);return r}function hi(e,t,i){var r=e.length;(!t||t<0)&&(t=0),(!i||i<0||i>r)&&(i=r);for(var s="",n=t;n<i;++n)s+=yi(e[n]);return s}function di(e,t,i){for(var r=e.slice(t,i),s="",n=0;n<r.length;n+=2)s+=String.fromCharCode(r[n]+256*r[n+1]);return s}function ui(e,t,i){if(e%1!=0||e<0)throw new RangeError("offset is not uint");if(e+t>i)throw new RangeError("Trying to access beyond buffer length")}function ci(e,t,i,r,s,n){if(!Wt(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>s||t<n)throw new RangeError('"value" argument is out of bounds');if(i+r>e.length)throw new RangeError("Index out of range")}function fi(e,t,i,r){t<0&&(t=65535+t+1);for(var s=0,n=Math.min(e.length-i,2);s<n;++s)e[i+s]=(t&255<<8*(r?s:1-s))>>>8*(r?s:1-s)}function pi(e,t,i,r){t<0&&(t=4294967295+t+1);for(var s=0,n=Math.min(e.length-i,4);s<n;++s)e[i+s]=t>>>8*(r?s:3-s)&255}function mi(e,t,i,r,s,n){if(i+r>e.length)throw new RangeError("Index out of range");if(i<0)throw new RangeError("Index out of range")}function gi(e,t,i,r,s){return s||mi(e,0,i,4),Ot(e,t,i,r,23,4),i+4}function vi(e,t,i,r,s){return s||mi(e,0,i,8),Ot(e,t,i,r,52,8),i+8}Bt.prototype.slice=function(e,t){var i,r=this.length;if((e=~~e)<0?(e+=r)<0&&(e=0):e>r&&(e=r),(t=void 0===t?r:~~t)<0?(t+=r)<0&&(t=0):t>r&&(t=r),t<e&&(t=e),Bt.TYPED_ARRAY_SUPPORT)(i=this.subarray(e,t)).__proto__=Bt.prototype;else{var s=t-e;i=new Bt(s,void 0);for(var n=0;n<s;++n)i[n]=this[n+e]}return i},Bt.prototype.readUIntLE=function(e,t,i){e|=0,t|=0,i||ui(e,t,this.length);for(var r=this[e],s=1,n=0;++n<t&&(s*=256);)r+=this[e+n]*s;return r},Bt.prototype.readUIntBE=function(e,t,i){e|=0,t|=0,i||ui(e,t,this.length);for(var r=this[e+--t],s=1;t>0&&(s*=256);)r+=this[e+--t]*s;return r},Bt.prototype.readUInt8=function(e,t){return t||ui(e,1,this.length),this[e]},Bt.prototype.readUInt16LE=function(e,t){return t||ui(e,2,this.length),this[e]|this[e+1]<<8},Bt.prototype.readUInt16BE=function(e,t){return t||ui(e,2,this.length),this[e]<<8|this[e+1]},Bt.prototype.readUInt32LE=function(e,t){return t||ui(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},Bt.prototype.readUInt32BE=function(e,t){return t||ui(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},Bt.prototype.readIntLE=function(e,t,i){e|=0,t|=0,i||ui(e,t,this.length);for(var r=this[e],s=1,n=0;++n<t&&(s*=256);)r+=this[e+n]*s;return r>=(s*=128)&&(r-=Math.pow(2,8*t)),r},Bt.prototype.readIntBE=function(e,t,i){e|=0,t|=0,i||ui(e,t,this.length);for(var r=t,s=1,n=this[e+--r];r>0&&(s*=256);)n+=this[e+--r]*s;return n>=(s*=128)&&(n-=Math.pow(2,8*t)),n},Bt.prototype.readInt8=function(e,t){return t||ui(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},Bt.prototype.readInt16LE=function(e,t){t||ui(e,2,this.length);var i=this[e]|this[e+1]<<8;return 32768&i?4294901760|i:i},Bt.prototype.readInt16BE=function(e,t){t||ui(e,2,this.length);var i=this[e+1]|this[e]<<8;return 32768&i?4294901760|i:i},Bt.prototype.readInt32LE=function(e,t){return t||ui(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},Bt.prototype.readInt32BE=function(e,t){return t||ui(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},Bt.prototype.readFloatLE=function(e,t){return t||ui(e,4,this.length),Pt(this,e,!0,23,4)},Bt.prototype.readFloatBE=function(e,t){return t||ui(e,4,this.length),Pt(this,e,!1,23,4)},Bt.prototype.readDoubleLE=function(e,t){return t||ui(e,8,this.length),Pt(this,e,!0,52,8)},Bt.prototype.readDoubleBE=function(e,t){return t||ui(e,8,this.length),Pt(this,e,!1,52,8)},Bt.prototype.writeUIntLE=function(e,t,i,r){(e=+e,t|=0,i|=0,r)||ci(this,e,t,i,Math.pow(2,8*i)-1,0);var s=1,n=0;for(this[t]=255&e;++n<i&&(s*=256);)this[t+n]=e/s&255;return t+i},Bt.prototype.writeUIntBE=function(e,t,i,r){(e=+e,t|=0,i|=0,r)||ci(this,e,t,i,Math.pow(2,8*i)-1,0);var s=i-1,n=1;for(this[t+s]=255&e;--s>=0&&(n*=256);)this[t+s]=e/n&255;return t+i},Bt.prototype.writeUInt8=function(e,t,i){return e=+e,t|=0,i||ci(this,e,t,1,255,0),Bt.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),this[t]=255&e,t+1},Bt.prototype.writeUInt16LE=function(e,t,i){return e=+e,t|=0,i||ci(this,e,t,2,65535,0),Bt.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):fi(this,e,t,!0),t+2},Bt.prototype.writeUInt16BE=function(e,t,i){return e=+e,t|=0,i||ci(this,e,t,2,65535,0),Bt.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):fi(this,e,t,!1),t+2},Bt.prototype.writeUInt32LE=function(e,t,i){return e=+e,t|=0,i||ci(this,e,t,4,4294967295,0),Bt.TYPED_ARRAY_SUPPORT?(this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e):pi(this,e,t,!0),t+4},Bt.prototype.writeUInt32BE=function(e,t,i){return e=+e,t|=0,i||ci(this,e,t,4,4294967295,0),Bt.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):pi(this,e,t,!1),t+4},Bt.prototype.writeIntLE=function(e,t,i,r){if(e=+e,t|=0,!r){var s=Math.pow(2,8*i-1);ci(this,e,t,i,s-1,-s)}var n=0,a=1,o=0;for(this[t]=255&e;++n<i&&(a*=256);)e<0&&0===o&&0!==this[t+n-1]&&(o=1),this[t+n]=(e/a|0)-o&255;return t+i},Bt.prototype.writeIntBE=function(e,t,i,r){if(e=+e,t|=0,!r){var s=Math.pow(2,8*i-1);ci(this,e,t,i,s-1,-s)}var n=i-1,a=1,o=0;for(this[t+n]=255&e;--n>=0&&(a*=256);)e<0&&0===o&&0!==this[t+n+1]&&(o=1),this[t+n]=(e/a|0)-o&255;return t+i},Bt.prototype.writeInt8=function(e,t,i){return e=+e,t|=0,i||ci(this,e,t,1,127,-128),Bt.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),e<0&&(e=255+e+1),this[t]=255&e,t+1},Bt.prototype.writeInt16LE=function(e,t,i){return e=+e,t|=0,i||ci(this,e,t,2,32767,-32768),Bt.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):fi(this,e,t,!0),t+2},Bt.prototype.writeInt16BE=function(e,t,i){return e=+e,t|=0,i||ci(this,e,t,2,32767,-32768),Bt.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):fi(this,e,t,!1),t+2},Bt.prototype.writeInt32LE=function(e,t,i){return e=+e,t|=0,i||ci(this,e,t,4,2147483647,-2147483648),Bt.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24):pi(this,e,t,!0),t+4},Bt.prototype.writeInt32BE=function(e,t,i){return e=+e,t|=0,i||ci(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),Bt.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):pi(this,e,t,!1),t+4},Bt.prototype.writeFloatLE=function(e,t,i){return gi(this,e,t,!0,i)},Bt.prototype.writeFloatBE=function(e,t,i){return gi(this,e,t,!1,i)},Bt.prototype.writeDoubleLE=function(e,t,i){return vi(this,e,t,!0,i)},Bt.prototype.writeDoubleBE=function(e,t,i){return vi(this,e,t,!1,i)},Bt.prototype.copy=function(e,t,i,r){if(i||(i=0),r||0===r||(r=this.length),t>=e.length&&(t=e.length),t||(t=0),r>0&&r<i&&(r=i),r===i)return 0;if(0===e.length||0===this.length)return 0;if(t<0)throw new RangeError("targetStart out of bounds");if(i<0||i>=this.length)throw new RangeError("sourceStart out of bounds");if(r<0)throw new RangeError("sourceEnd out of bounds");r>this.length&&(r=this.length),e.length-t<r-i&&(r=e.length-t+i);var s,n=r-i;if(this===e&&i<t&&t<r)for(s=n-1;s>=0;--s)e[s+t]=this[s+i];else if(n<1e3||!Bt.TYPED_ARRAY_SUPPORT)for(s=0;s<n;++s)e[s+t]=this[s+i];else Uint8Array.prototype.set.call(e,this.subarray(i,i+n),t);return n},Bt.prototype.fill=function(e,t,i,r){if("string"==typeof e){if("string"==typeof t?(r=t,t=0,i=this.length):"string"==typeof i&&(r=i,i=this.length),1===e.length){var s=e.charCodeAt(0);s<256&&(e=s)}if(void 0!==r&&"string"!=typeof r)throw new TypeError("encoding must be a string");if("string"==typeof r&&!Bt.isEncoding(r))throw new TypeError("Unknown encoding: "+r)}else"number"==typeof e&&(e&=255);if(t<0||this.length<t||this.length<i)throw new RangeError("Out of range index");if(i<=t)return this;var n;if(t>>>=0,i=void 0===i?this.length:i>>>0,e||(e=0),"number"==typeof e)for(n=t;n<i;++n)this[n]=e;else{var a=Wt(e)?e:bi(new Bt(e,r).toString()),o=a.length;for(n=0;n<i-t;++n)this[n+t]=a[n%o]}return this};var Ei=/[^+\/0-9A-Za-z-_]/g;function yi(e){return e<16?"0"+e.toString(16):e.toString(16)}function bi(e,t){var i;t=t||1/0;for(var r=e.length,s=null,n=[],a=0;a<r;++a){if((i=e.charCodeAt(a))>55295&&i<57344){if(!s){if(i>56319){(t-=3)>-1&&n.push(239,191,189);continue}if(a+1===r){(t-=3)>-1&&n.push(239,191,189);continue}s=i;continue}if(i<56320){(t-=3)>-1&&n.push(239,191,189),s=i;continue}i=65536+(s-55296<<10|i-56320)}else s&&(t-=3)>-1&&n.push(239,191,189);if(s=null,i<128){if((t-=1)<0)break;n.push(i)}else if(i<2048){if((t-=2)<0)break;n.push(i>>6|192,63&i|128)}else if(i<65536){if((t-=3)<0)break;n.push(i>>12|224,i>>6&63|128,63&i|128)}else{if(!(i<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;n.push(i>>18|240,i>>12&63|128,i>>6&63|128,63&i|128)}}return n}function Ti(e){return function(e){var t,i,r,s,n,a;Ct||Dt();var o=e.length;if(o%4>0)throw new Error("Invalid string. Length must be a multiple of 4");n="="===e[o-2]?2:"="===e[o-1]?1:0,a=new It(3*o/4-n),r=n>0?o-4:o;var l=0;for(t=0,i=0;t<r;t+=4,i+=3)s=Rt[e.charCodeAt(t)]<<18|Rt[e.charCodeAt(t+1)]<<12|Rt[e.charCodeAt(t+2)]<<6|Rt[e.charCodeAt(t+3)],a[l++]=s>>16&255,a[l++]=s>>8&255,a[l++]=255&s;return 2===n?(s=Rt[e.charCodeAt(t)]<<2|Rt[e.charCodeAt(t+1)]>>4,a[l++]=255&s):1===n&&(s=Rt[e.charCodeAt(t)]<<10|Rt[e.charCodeAt(t+1)]<<4|Rt[e.charCodeAt(t+2)]>>2,a[l++]=s>>8&255,a[l++]=255&s),a}(function(e){if((e=function(e){return e.trim?e.trim():e.replace(/^\s+|\s+$/g,"")}(e).replace(Ei,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function Si(e,t,i,r){for(var s=0;s<r&&!(s+i>=t.length||s>=e.length);++s)t[s+i]=e[s];return s}function Ai(e){return!!e.constructor&&"function"==typeof e.constructor.isBuffer&&e.constructor.isBuffer(e)}function _i(){return document&&new URL(import.meta.url).pathname.includes("+esm")?"dist/":""}var wi=(e,t,i)=>{let r=e[0];for(let s=1;s<e.length;s++)r+=t[i?i[s-1]:s-1],r+=e[s];return r},ki=e=>(e=>"string"!=typeof e&&"strTag"in e)(e)?wi(e.strings,e.values):e,Li="lit-localize-status",Ri=class{constructor(e){this.__litLocalizeEventHandler=e=>{"ready"===e.detail.status&&this.host.requestUpdate()},this.host=e}hostConnected(){window.addEventListener(Li,this.__litLocalizeEventHandler)}hostDisconnected(){window.removeEventListener(Li,this.__litLocalizeEventHandler)}},Ii=e=>e.addController(new Ri(e)),Ci=class{constructor(){this.settled=!1,this.promise=new Promise(((e,t)=>{this._resolve=e,this._reject=t}))}resolve(e){this.settled=!0,this._resolve(e)}reject(e){this.settled=!0,this._reject(e)}},Di=[];for(let e=0;e<256;e++)Di[e]=(e>>4&15).toString(16)+(15&e).toString(16);function xi(e,t){return(t?"h":"s")+function(e){let t=0,i=8997,r=0,s=33826,n=0,a=40164,o=0,l=52210;for(let h=0;h<e.length;h++)i^=e.charCodeAt(h),t=435*i,r=435*s,n=435*a,o=435*l,n+=i<<8,o+=s<<8,r+=t>>>16,i=65535&t,n+=r>>>16,s=65535&r,l=o+(n>>>16)&65535,a=65535&n;return Di[l>>8]+Di[255&l]+Di[a>>8]+Di[255&a]+Di[s>>8]+Di[255&s]+Di[i>>8]+Di[255&i]}("string"==typeof e?e:e.join(""))}var Mi=new WeakMap,Pi=new Map;function Oi(e,t,i){if(e){let r=i?.id??function(e){let t="string"==typeof e?e:e.strings,i=Pi.get(t);return void 0===i&&(i=xi(t,"string"!=typeof e&&!("strTag"in e)),Pi.set(t,i)),i}(t),s=e[r];if(s){if("string"==typeof s)return s;if("strTag"in s)return wi(s.strings,t.values,s.values);{let e=Mi.get(s);return void 0===e&&(e=s.values,Mi.set(s,e)),{...s,values:e.map((e=>t.values[e]))}}}}return ki(t)}function Ui(e){window.dispatchEvent(new CustomEvent(Li,{detail:e}))}var Ni,$i,Fi,Bi,Hi,Gi="",ji=new Ci;ji.resolve();var Vi=0,Ki=()=>Gi,Wi=e=>{if(e===(Ni??Gi))return ji.promise;if(!Fi||!Bi)throw new Error("Internal error");if(!Fi.has(e))throw new Error("Invalid locale code");let t=++Vi;return Ni=e,ji.settled&&(ji=new Ci),Ui({status:"loading",loadingLocale:e}),(e===$i?Promise.resolve({templates:void 0}):Bi(e)).then((i=>{Vi===t&&(Gi=e,Ni=void 0,Hi=i.templates,Ui({status:"ready",readyLocale:e}),ji.resolve())}),(i=>{Vi===t&&(Ui({status:"error",errorLocale:e,errorMessage:i.toString()}),ji.reject(i))})),ji.promise},qi=ki,Yi=!1;var zi=(e=>(function(e){if(Yi)throw new Error("lit-localize can only be configured once");qi=e,Yi=!0}(((e,t)=>Oi(Hi,e,t))),Gi=$i=e.sourceLocale,(Fi=new Set(e.targetLocales)).add(e.sourceLocale),Bi=e.loadLocale,{getLocale:Ki,setLocale:Wi}))({sourceLocale:"default",targetLocales:["en","nl","de","fr"],loadLocale:async e=>{try{return await import(`./${_i()}generated/locales/${e}.js`)}catch(e){return console.log("[mave-player]: locale not loaded",e),null}}}),Xi=!1,Qi=class{constructor(e){this._onLoad=e=>{"loading"===e.detail.status?Xi=!1:"ready"===e.detail.status&&(Xi=!0),this.host.requestUpdate()},this.host=e,e.addController(this)}get loaded(){return Xi}set locale(e){this._locale!==e&&(zi.setLocale(e),this.host.requestUpdate())}get locale(){return this._locale}hostConnected(){window.addEventListener("lit-localize-status",this._onLoad)}hostDisconnected(){window.removeEventListener("lit-localize-status",this._onLoad)}},Zi=e=>"function"==typeof e?e:function(){return e},Ji=typeof self<"u"?self:null,er=typeof window<"u"?window:null,tr=Ji||er||tr,ir=0,rr=1,sr=2,nr=3,ar="closed",or="errored",lr="joined",hr="joining",dr="leaving",ur="phx_close",cr="phx_error",fr="phx_join",pr="phx_reply",mr="phx_leave",gr="longpoll",vr="websocket",Er=4,yr=class{constructor(e,t,i,r){this.channel=e,this.event=t,this.payload=i||function(){return{}},this.receivedResp=null,this.timeout=r,this.timeoutTimer=null,this.recHooks=[],this.sent=!1}resend(e){this.timeout=e,this.reset(),this.send()}send(){this.hasReceived("timeout")||(this.startTimeout(),this.sent=!0,this.channel.socket.push({topic:this.channel.topic,event:this.event,payload:this.payload(),ref:this.ref,join_ref:this.channel.joinRef()}))}receive(e,t){return this.hasReceived(e)&&t(this.receivedResp.response),this.recHooks.push({status:e,callback:t}),this}reset(){this.cancelRefEvent(),this.ref=null,this.refEvent=null,this.receivedResp=null,this.sent=!1}matchReceive({status:e,response:t,_ref:i}){this.recHooks.filter((t=>t.status===e)).forEach((e=>e.callback(t)))}cancelRefEvent(){this.refEvent&&this.channel.off(this.refEvent)}cancelTimeout(){clearTimeout(this.timeoutTimer),this.timeoutTimer=null}startTimeout(){this.timeoutTimer&&this.cancelTimeout(),this.ref=this.channel.socket.makeRef(),this.refEvent=this.channel.replyEventName(this.ref),this.channel.on(this.refEvent,(e=>{this.cancelRefEvent(),this.cancelTimeout(),this.receivedResp=e,this.matchReceive(e)})),this.timeoutTimer=setTimeout((()=>{this.trigger("timeout",{})}),this.timeout)}hasReceived(e){return this.receivedResp&&this.receivedResp.status===e}trigger(e,t){this.channel.trigger(this.refEvent,{status:e,response:t})}},br=class{constructor(e,t){this.callback=e,this.timerCalc=t,this.timer=null,this.tries=0}reset(){this.tries=0,clearTimeout(this.timer)}scheduleTimeout(){clearTimeout(this.timer),this.timer=setTimeout((()=>{this.tries=this.tries+1,this.callback()}),this.timerCalc(this.tries+1))}},Tr=class{constructor(e,t,i){this.state=ar,this.topic=e,this.params=Zi(t||{}),this.socket=i,this.bindings=[],this.bindingRef=0,this.timeout=this.socket.timeout,this.joinedOnce=!1,this.joinPush=new yr(this,fr,this.params,this.timeout),this.pushBuffer=[],this.stateChangeRefs=[],this.rejoinTimer=new br((()=>{this.socket.isConnected()&&this.rejoin()}),this.socket.rejoinAfterMs),this.stateChangeRefs.push(this.socket.onError((()=>this.rejoinTimer.reset()))),this.stateChangeRefs.push(this.socket.onOpen((()=>{this.rejoinTimer.reset(),this.isErrored()&&this.rejoin()}))),this.joinPush.receive("ok",(()=>{this.state=lr,this.rejoinTimer.reset(),this.pushBuffer.forEach((e=>e.send())),this.pushBuffer=[]})),this.joinPush.receive("error",(()=>{this.state=or,this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()})),this.onClose((()=>{this.rejoinTimer.reset(),this.socket.hasLogger()&&this.socket.log("channel",`close ${this.topic} ${this.joinRef()}`),this.state=ar,this.socket.remove(this)})),this.onError((e=>{this.socket.hasLogger()&&this.socket.log("channel",`error ${this.topic}`,e),this.isJoining()&&this.joinPush.reset(),this.state=or,this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()})),this.joinPush.receive("timeout",(()=>{this.socket.hasLogger()&&this.socket.log("channel",`timeout ${this.topic} (${this.joinRef()})`,this.joinPush.timeout),new yr(this,mr,Zi({}),this.timeout).send(),this.state=or,this.joinPush.reset(),this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()})),this.on(pr,((e,t)=>{this.trigger(this.replyEventName(t),e)}))}join(e=this.timeout){if(this.joinedOnce)throw new Error("tried to join multiple times. 'join' can only be called a single time per channel instance");return this.timeout=e,this.joinedOnce=!0,this.rejoin(),this.joinPush}onClose(e){this.on(ur,e)}onError(e){return this.on(cr,(t=>e(t)))}on(e,t){let i=this.bindingRef++;return this.bindings.push({event:e,ref:i,callback:t}),i}off(e,t){this.bindings=this.bindings.filter((i=>!(i.event===e&&(typeof t>"u"||t===i.ref))))}canPush(){return this.socket.isConnected()&&this.isJoined()}push(e,t,i=this.timeout){if(t=t||{},!this.joinedOnce)throw new Error(`tried to push '${e}' to '${this.topic}' before joining. Use channel.join() before pushing events`);let r=new yr(this,e,(function(){return t}),i);return this.canPush()?r.send():(r.startTimeout(),this.pushBuffer.push(r)),r}leave(e=this.timeout){this.rejoinTimer.reset(),this.joinPush.cancelTimeout(),this.state=dr;let t=()=>{this.socket.hasLogger()&&this.socket.log("channel",`leave ${this.topic}`),this.trigger(ur,"leave")},i=new yr(this,mr,Zi({}),e);return i.receive("ok",(()=>t())).receive("timeout",(()=>t())),i.send(),this.canPush()||i.trigger("ok",{}),i}onMessage(e,t,i){return t}isMember(e,t,i,r){return this.topic===e&&(!r||r===this.joinRef()||(this.socket.hasLogger()&&this.socket.log("channel","dropping outdated message",{topic:e,event:t,payload:i,joinRef:r}),!1))}joinRef(){return this.joinPush.ref}rejoin(e=this.timeout){this.isLeaving()||(this.socket.leaveOpenTopic(this.topic),this.state=hr,this.joinPush.resend(e))}trigger(e,t,i,r){let s=this.onMessage(e,t,i,r);if(t&&!s)throw new Error("channel onMessage callbacks must return the payload, modified or unmodified");let n=this.bindings.filter((t=>t.event===e));for(let e=0;e<n.length;e++)n[e].callback(s,i,r||this.joinRef())}replyEventName(e){return`chan_reply_${e}`}isClosed(){return this.state===ar}isErrored(){return this.state===or}isJoined(){return this.state===lr}isJoining(){return this.state===hr}isLeaving(){return this.state===dr}},Sr=class{static request(e,t,i,r,s,n,a){if(tr.XDomainRequest){let i=new tr.XDomainRequest;return this.xdomainRequest(i,e,t,r,s,n,a)}{let o=new tr.XMLHttpRequest;return this.xhrRequest(o,e,t,i,r,s,n,a)}}static xdomainRequest(e,t,i,r,s,n,a){return e.timeout=s,e.open(t,i),e.onload=()=>{let t=this.parseJSON(e.responseText);a&&a(t)},n&&(e.ontimeout=n),e.onprogress=()=>{},e.send(r),e}static xhrRequest(e,t,i,r,s,n,a,o){return e.open(t,i,!0),e.timeout=n,e.setRequestHeader("Content-Type",r),e.onerror=()=>o&&o(null),e.onreadystatechange=()=>{if(e.readyState===Er&&o){let t=this.parseJSON(e.responseText);o(t)}},a&&(e.ontimeout=a),e.send(s),e}static parseJSON(e){if(!e||""===e)return null;try{return JSON.parse(e)}catch{return console&&console.log("failed to parse JSON response",e),null}}static serialize(e,t){let i=[];for(var r in e){if(!Object.prototype.hasOwnProperty.call(e,r))continue;let s=t?`${t}[${r}]`:r,n=e[r];"object"==typeof n?i.push(this.serialize(n,s)):i.push(encodeURIComponent(s)+"="+encodeURIComponent(n))}return i.join("&")}static appendParams(e,t){if(0===Object.keys(t).length)return e;let i=e.match(/\?/)?"&":"?";return`${e}${i}${this.serialize(t)}`}},Ar=class{constructor(e){this.endPoint=null,this.token=null,this.skipHeartbeat=!0,this.reqs=new Set,this.awaitingBatchAck=!1,this.currentBatch=null,this.currentBatchTimer=null,this.batchBuffer=[],this.onopen=function(){},this.onerror=function(){},this.onmessage=function(){},this.onclose=function(){},this.pollEndpoint=this.normalizeEndpoint(e),this.readyState=ir,setTimeout((()=>this.poll()),0)}normalizeEndpoint(e){return e.replace("ws://","http://").replace("wss://","https://").replace(new RegExp("(.*)/"+vr),"$1/"+gr)}endpointURL(){return Sr.appendParams(this.pollEndpoint,{token:this.token})}closeAndRetry(e,t,i){this.close(e,t,i),this.readyState=ir}ontimeout(){this.onerror("timeout"),this.closeAndRetry(1005,"timeout",!1)}isActive(){return this.readyState===rr||this.readyState===ir}poll(){this.ajax("GET","application/json",null,(()=>this.ontimeout()),(e=>{if(e){var{status:t,token:i,messages:r}=e;this.token=i}else t=0;switch(t){case 200:r.forEach((e=>{setTimeout((()=>this.onmessage({data:e})),0)})),this.poll();break;case 204:this.poll();break;case 410:this.readyState=rr,this.onopen({}),this.poll();break;case 403:this.onerror(403),this.close(1008,"forbidden",!1);break;case 0:case 500:this.onerror(500),this.closeAndRetry(1011,"internal server error",500);break;default:throw new Error(`unhandled poll status ${t}`)}}))}send(e){"string"!=typeof e&&(e=(e=>{let t="",i=new Uint8Array(e),r=i.byteLength;for(let e=0;e<r;e++)t+=String.fromCharCode(i[e]);return btoa(t)})(e)),this.currentBatch?this.currentBatch.push(e):this.awaitingBatchAck?this.batchBuffer.push(e):(this.currentBatch=[e],this.currentBatchTimer=setTimeout((()=>{this.batchSend(this.currentBatch),this.currentBatch=null}),0))}batchSend(e){this.awaitingBatchAck=!0,this.ajax("POST","application/x-ndjson",e.join("\n"),(()=>this.onerror("timeout")),(e=>{this.awaitingBatchAck=!1,e&&200===e.status?this.batchBuffer.length>0&&(this.batchSend(this.batchBuffer),this.batchBuffer=[]):(this.onerror(e&&e.status),this.closeAndRetry(1011,"internal server error",!1))}))}close(e,t,i){for(let e of this.reqs)e.abort();this.readyState=nr;let r=Object.assign({code:1e3,reason:void 0,wasClean:!0},{code:e,reason:t,wasClean:i});this.batchBuffer=[],clearTimeout(this.currentBatchTimer),this.currentBatchTimer=null,typeof CloseEvent<"u"?this.onclose(new CloseEvent("close",r)):this.onclose(r)}ajax(e,t,i,r,s){let n;n=Sr.request(e,this.endpointURL(),t,i,this.timeout,(()=>{this.reqs.delete(n),r()}),(e=>{this.reqs.delete(n),this.isActive()&&s(e)})),this.reqs.add(n)}},_r={HEADER_LENGTH:1,META_LENGTH:4,KINDS:{push:0,reply:1,broadcast:2},encode(e,t){if(e.payload.constructor===ArrayBuffer)return t(this.binaryEncode(e));{let i=[e.join_ref,e.ref,e.topic,e.event,e.payload];return t(JSON.stringify(i))}},decode(e,t){if(e.constructor===ArrayBuffer)return t(this.binaryDecode(e));{let[i,r,s,n,a]=JSON.parse(e);return t({join_ref:i,ref:r,topic:s,event:n,payload:a})}},binaryEncode(e){let{join_ref:t,ref:i,event:r,topic:s,payload:n}=e,a=this.META_LENGTH+t.length+i.length+s.length+r.length,o=new ArrayBuffer(this.HEADER_LENGTH+a),l=new DataView(o),h=0;l.setUint8(h++,this.KINDS.push),l.setUint8(h++,t.length),l.setUint8(h++,i.length),l.setUint8(h++,s.length),l.setUint8(h++,r.length),Array.from(t,(e=>l.setUint8(h++,e.charCodeAt(0)))),Array.from(i,(e=>l.setUint8(h++,e.charCodeAt(0)))),Array.from(s,(e=>l.setUint8(h++,e.charCodeAt(0)))),Array.from(r,(e=>l.setUint8(h++,e.charCodeAt(0))));var d=new Uint8Array(o.byteLength+n.byteLength);return d.set(new Uint8Array(o),0),d.set(new Uint8Array(n),o.byteLength),d.buffer},binaryDecode(e){let t=new DataView(e),i=t.getUint8(0),r=new TextDecoder;switch(i){case this.KINDS.push:return this.decodePush(e,t,r);case this.KINDS.reply:return this.decodeReply(e,t,r);case this.KINDS.broadcast:return this.decodeBroadcast(e,t,r)}},decodePush(e,t,i){let r=t.getUint8(1),s=t.getUint8(2),n=t.getUint8(3),a=this.HEADER_LENGTH+this.META_LENGTH-1,o=i.decode(e.slice(a,a+r));a+=r;let l=i.decode(e.slice(a,a+s));a+=s;let h=i.decode(e.slice(a,a+n));return a+=n,{join_ref:o,ref:null,topic:l,event:h,payload:e.slice(a,e.byteLength)}},decodeReply(e,t,i){let r=t.getUint8(1),s=t.getUint8(2),n=t.getUint8(3),a=t.getUint8(4),o=this.HEADER_LENGTH+this.META_LENGTH,l=i.decode(e.slice(o,o+r));o+=r;let h=i.decode(e.slice(o,o+s));o+=s;let d=i.decode(e.slice(o,o+n));o+=n;let u=i.decode(e.slice(o,o+a));o+=a;let c=e.slice(o,e.byteLength);return{join_ref:l,ref:h,topic:d,event:pr,payload:{status:u,response:c}}},decodeBroadcast(e,t,i){let r=t.getUint8(1),s=t.getUint8(2),n=this.HEADER_LENGTH+2,a=i.decode(e.slice(n,n+r));n+=r;let o=i.decode(e.slice(n,n+s));return n+=s,{join_ref:null,ref:null,topic:a,event:o,payload:e.slice(n,e.byteLength)}}},wr=class{constructor(e,t={}){this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.channels=[],this.sendBuffer=[],this.ref=0,this.timeout=t.timeout||1e4,this.transport=t.transport||tr.WebSocket||Ar,this.longPollFallbackMs=t.longPollFallbackMs,this.fallbackTimer=null,this.sessionStore=t.sessionStorage||tr.sessionStorage,this.establishedConnections=0,this.defaultEncoder=_r.encode.bind(_r),this.defaultDecoder=_r.decode.bind(_r),this.closeWasClean=!1,this.binaryType=t.binaryType||"arraybuffer",this.connectClock=1,this.transport!==Ar?(this.encode=t.encode||this.defaultEncoder,this.decode=t.decode||this.defaultDecoder):(this.encode=this.defaultEncoder,this.decode=this.defaultDecoder);let i=null;er&&er.addEventListener&&(er.addEventListener("pagehide",(e=>{this.conn&&(this.disconnect(),i=this.connectClock)})),er.addEventListener("pageshow",(e=>{i===this.connectClock&&(i=null,this.connect())}))),this.heartbeatIntervalMs=t.heartbeatIntervalMs||3e4,this.rejoinAfterMs=e=>t.rejoinAfterMs?t.rejoinAfterMs(e):[1e3,2e3,5e3][e-1]||1e4,this.reconnectAfterMs=e=>t.reconnectAfterMs?t.reconnectAfterMs(e):[10,50,100,150,200,250,500,1e3,2e3][e-1]||5e3,this.logger=t.logger||null,!this.logger&&t.debug&&(this.logger=(e,t,i)=>{console.log(`${e}: ${t}`,i)}),this.longpollerTimeout=t.longpollerTimeout||2e4,this.params=Zi(t.params||{}),this.endPoint=`${e}/${vr}`,this.vsn=t.vsn||"2.0.0",this.heartbeatTimeoutTimer=null,this.heartbeatTimer=null,this.pendingHeartbeatRef=null,this.reconnectTimer=new br((()=>{this.teardown((()=>this.connect()))}),this.reconnectAfterMs)}getLongPollTransport(){return Ar}replaceTransport(e){this.connectClock++,this.closeWasClean=!0,clearTimeout(this.fallbackTimer),this.reconnectTimer.reset(),this.conn&&(this.conn.close(),this.conn=null),this.transport=e}protocol(){return location.protocol.match(/^https/)?"wss":"ws"}endPointURL(){let e=Sr.appendParams(Sr.appendParams(this.endPoint,this.params()),{vsn:this.vsn});return"/"!==e.charAt(0)?e:"/"===e.charAt(1)?`${this.protocol()}:${e}`:`${this.protocol()}://${location.host}${e}`}disconnect(e,t,i){this.connectClock++,this.closeWasClean=!0,clearTimeout(this.fallbackTimer),this.reconnectTimer.reset(),this.teardown(e,t,i)}connect(e){e&&(console&&console.log("passing params to connect is deprecated. Instead pass :params to the Socket constructor"),this.params=Zi(e)),!this.conn&&(this.longPollFallbackMs&&this.transport!==Ar?this.connectWithFallback(Ar,this.longPollFallbackMs):this.transportConnect())}log(e,t,i){this.logger&&this.logger(e,t,i)}hasLogger(){return null!==this.logger}onOpen(e){let t=this.makeRef();return this.stateChangeCallbacks.open.push([t,e]),t}onClose(e){let t=this.makeRef();return this.stateChangeCallbacks.close.push([t,e]),t}onError(e){let t=this.makeRef();return this.stateChangeCallbacks.error.push([t,e]),t}onMessage(e){let t=this.makeRef();return this.stateChangeCallbacks.message.push([t,e]),t}ping(e){if(!this.isConnected())return!1;let t=this.makeRef(),i=Date.now();this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:t});let r=this.onMessage((s=>{s.ref===t&&(this.off([r]),e(Date.now()-i))}));return!0}transportConnect(){this.connectClock++,this.closeWasClean=!1,this.conn=new this.transport(this.endPointURL()),this.conn.binaryType=this.binaryType,this.conn.timeout=this.longpollerTimeout,this.conn.onopen=()=>this.onConnOpen(),this.conn.onerror=e=>this.onConnError(e),this.conn.onmessage=e=>this.onConnMessage(e),this.conn.onclose=e=>this.onConnClose(e)}getSession(e){return this.sessionStore&&this.sessionStore.getItem(e)}storeSession(e,t){this.sessionStore&&this.sessionStore.setItem(e,t)}connectWithFallback(e,t=2500){clearTimeout(this.fallbackTimer);let i,r=!1,s=!0,n=t=>{this.log("transport",`falling back to ${e.name}...`,t),this.off([undefined,i]),s=!1,this.storeSession("phx:longpoll","true"),this.replaceTransport(e),this.transportConnect()};if(this.getSession("phx:longpoll"))return n("memorized");this.fallbackTimer=setTimeout(n,t),i=this.onError((e=>{this.log("transport","error",e),s&&!r&&(clearTimeout(this.fallbackTimer),n(e))})),this.onOpen((()=>{if(r=!0,!s)return console.log("transport",`established ${e.name} fallback`);clearTimeout(this.fallbackTimer),this.fallbackTimer=setTimeout(n,t),this.ping((e=>{this.log("transport","connected to primary after",e),clearTimeout(this.fallbackTimer)}))})),this.transportConnect()}clearHeartbeats(){clearTimeout(this.heartbeatTimer),clearTimeout(this.heartbeatTimeoutTimer)}onConnOpen(){this.hasLogger()&&this.log("transport",`${this.transport.name} connected to ${this.endPointURL()}`),this.closeWasClean=!1,this.establishedConnections++,this.flushSendBuffer(),this.reconnectTimer.reset(),this.resetHeartbeat(),this.stateChangeCallbacks.open.forEach((([,e])=>e()))}heartbeatTimeout(){this.pendingHeartbeatRef&&(this.pendingHeartbeatRef=null,this.hasLogger()&&this.log("transport","heartbeat timeout. Attempting to re-establish connection"),this.triggerChanError(),this.closeWasClean=!1,this.teardown((()=>this.reconnectTimer.scheduleTimeout()),1e3,"heartbeat timeout"))}resetHeartbeat(){this.conn&&this.conn.skipHeartbeat||(this.pendingHeartbeatRef=null,this.clearHeartbeats(),this.heartbeatTimer=setTimeout((()=>this.sendHeartbeat()),this.heartbeatIntervalMs))}teardown(e,t,i){if(!this.conn)return e&&e();this.waitForBufferDone((()=>{this.conn&&(t?this.conn.close(t,i||""):this.conn.close()),this.waitForSocketClosed((()=>{this.conn&&(this.conn.onopen=function(){},this.conn.onerror=function(){},this.conn.onmessage=function(){},this.conn.onclose=function(){},this.conn=null),e&&e()}))}))}waitForBufferDone(e,t=1){5!==t&&this.conn&&this.conn.bufferedAmount?setTimeout((()=>{this.waitForBufferDone(e,t+1)}),150*t):e()}waitForSocketClosed(e,t=1){5!==t&&this.conn&&this.conn.readyState!==nr?setTimeout((()=>{this.waitForSocketClosed(e,t+1)}),150*t):e()}onConnClose(e){let t=e&&e.code;this.hasLogger()&&this.log("transport","close",e),this.triggerChanError(),this.clearHeartbeats(),!this.closeWasClean&&1e3!==t&&this.reconnectTimer.scheduleTimeout(),this.stateChangeCallbacks.close.forEach((([,t])=>t(e)))}onConnError(e){this.hasLogger()&&this.log("transport",e);let t=this.transport,i=this.establishedConnections;this.stateChangeCallbacks.error.forEach((([,r])=>{r(e,t,i)})),(t===this.transport||i>0)&&this.triggerChanError()}triggerChanError(){this.channels.forEach((e=>{e.isErrored()||e.isLeaving()||e.isClosed()||e.trigger(cr)}))}connectionState(){switch(this.conn&&this.conn.readyState){case ir:return"connecting";case rr:return"open";case sr:return"closing";default:return"closed"}}isConnected(){return"open"===this.connectionState()}remove(e){this.off(e.stateChangeRefs),this.channels=this.channels.filter((t=>t.joinRef()!==e.joinRef()))}off(e){for(let t in this.stateChangeCallbacks)this.stateChangeCallbacks[t]=this.stateChangeCallbacks[t].filter((([t])=>-1===e.indexOf(t)))}channel(e,t={}){let i=new Tr(e,t,this);return this.channels.push(i),i}push(e){if(this.hasLogger()){let{topic:t,event:i,payload:r,ref:s,join_ref:n}=e;this.log("push",`${t} ${i} (${n}, ${s})`,r)}this.isConnected()?this.encode(e,(e=>this.conn.send(e))):this.sendBuffer.push((()=>this.encode(e,(e=>this.conn.send(e)))))}makeRef(){let e=this.ref+1;return e===this.ref?this.ref=0:this.ref=e,this.ref.toString()}sendHeartbeat(){this.pendingHeartbeatRef&&!this.isConnected()||(this.pendingHeartbeatRef=this.makeRef(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef}),this.heartbeatTimeoutTimer=setTimeout((()=>this.heartbeatTimeout()),this.heartbeatIntervalMs))}flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>0&&(this.sendBuffer.forEach((e=>e())),this.sendBuffer=[])}onConnMessage(e){this.decode(e.data,(e=>{let{topic:t,event:i,payload:r,ref:s,join_ref:n}=e;s&&s===this.pendingHeartbeatRef&&(this.clearHeartbeats(),this.pendingHeartbeatRef=null,this.heartbeatTimer=setTimeout((()=>this.sendHeartbeat()),this.heartbeatIntervalMs)),this.hasLogger()&&this.log("receive",`${r.status||""} ${t} ${i} ${s&&"("+s+")"||""}`,r);for(let e=0;e<this.channels.length;e++){let a=this.channels[e];a.isMember(t,i,r,n)&&a.trigger(i,r,s,n)}for(let t=0;t<this.stateChangeCallbacks.message.length;t++){let[,i]=this.stateChangeCallbacks.message[t];i(e)}}))}leaveOpenTopic(e){let t=this.channels.find((t=>t.topic===e&&(t.isJoined()||t.isJoining())));t&&(this.hasLogger()&&this.log("transport",`leaving duplicate topic "${e}"`),t.leave())}},kr=class e{constructor(){this.channels=[]}static connect(t){e.instance||(e.instance=new e,window&&(e.instance.socket=new wr(E.upload.socket,{params:{token:t},reconnectAfterMs:e=>[1e3,3e3,5e3,1e4][e-1]||1e4}),e.instance.socket.connect()));let i=e.instance.channels.find((e=>e.token===t));if(i)return i;{let i=e.instance.socket.channel(`embed:${t}`);i.join();let r={token:t,channel:i};return i.on("initiate",(({upload_id:t})=>{e.instance.channels.push({...r,upload_id:t})})),r}}},Lr=Et(((e,t)=>{t.exports=function(e,t){if(t=t.split(":")[0],!(e=+e))return!1;switch(t){case"http":case"ws":return 80!==e;case"https":case"wss":return 443!==e;case"ftp":return 21!==e;case"gopher":return 70!==e;case"file":return!1}return 0!==e}})),Rr=Et((e=>{var t=Object.prototype.hasOwnProperty;function i(e){try{return decodeURIComponent(e.replace(/\+/g," "))}catch{return null}}function r(e){try{return encodeURIComponent(e)}catch{return null}}e.stringify=function(e,i){i=i||"";var s,n,a=[];for(n in"string"!=typeof i&&(i="?"),e)if(t.call(e,n)){if(!(s=e[n])&&(null==s||isNaN(s))&&(s=""),n=r(n),s=r(s),null===n||null===s)continue;a.push(n+"="+s)}return a.length?i+a.join("&"):""},e.parse=function(e){for(var t,r=/([^=?#&]+)=?([^&]*)/g,s={};t=r.exec(e);){var n=i(t[1]),a=i(t[2]);null===n||null===a||n in s||(s[n]=a)}return s}})),Ir=Et(((e,t)=>{var i=Lr(),r=Rr(),s=/^[\x00-\x20\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]+/,n=/[\n\r\t]/g,a=/^[A-Za-z][A-Za-z0-9+-.]*:\/\//,o=/:\d+$/,l=/^([a-z][a-z0-9.+-]*:)?(\/\/)?([\\/]+)?([\S\s]*)/i,h=/^[a-zA-Z]:/;function d(e){return(e||"").toString().replace(s,"")}var u=[["#","hash"],["?","query"],function(e,t){return p(t.protocol)?e.replace(/\\/g,"/"):e},["/","pathname"],["@","auth",1],[NaN,"host",void 0,1,1],[/:(\d*)$/,"port",void 0,1],[NaN,"hostname",void 0,1,1]],c={hash:1,query:1};function f(e){var t,i=(typeof window<"u"?window:typeof kt<"u"?kt:typeof self<"u"?self:{}).location||{},r={},s=typeof(e=e||i);if("blob:"===e.protocol)r=new g(unescape(e.pathname),{});else if("string"===s)for(t in r=new g(e,{}),c)delete r[t];else if("object"===s){for(t in e)t in c||(r[t]=e[t]);void 0===r.slashes&&(r.slashes=a.test(e.href))}return r}function p(e){return"file:"===e||"ftp:"===e||"http:"===e||"https:"===e||"ws:"===e||"wss:"===e}function m(e,t){e=(e=d(e)).replace(n,""),t=t||{};var i,r=l.exec(e),s=r[1]?r[1].toLowerCase():"",a=!!r[2],o=!!r[3],h=0;return a?o?(i=r[2]+r[3]+r[4],h=r[2].length+r[3].length):(i=r[2]+r[4],h=r[2].length):o?(i=r[3]+r[4],h=r[3].length):i=r[4],"file:"===s?h>=2&&(i=i.slice(2)):p(s)?i=r[4]:s?a&&(i=i.slice(2)):h>=2&&p(t.protocol)&&(i=r[4]),{protocol:s,slashes:a||p(s),slashesCount:h,rest:i}}function g(e,t,s){if(e=(e=d(e)).replace(n,""),!(this instanceof g))return new g(e,t,s);var a,o,l,c,v,E,y=u.slice(),b=typeof t,T=this,S=0;for("object"!==b&&"string"!==b&&(s=t,t=null),s&&"function"!=typeof s&&(s=r.parse),a=!(o=m(e||"",t=f(t))).protocol&&!o.slashes,T.slashes=o.slashes||a&&t.slashes,T.protocol=o.protocol||t.protocol||"",e=o.rest,("file:"===o.protocol&&(2!==o.slashesCount||h.test(e))||!o.slashes&&(o.protocol||o.slashesCount<2||!p(T.protocol)))&&(y[3]=[/(.*)/,"pathname"]);S<y.length;S++)"function"!=typeof(c=y[S])?(l=c[0],E=c[1],l!=l?T[E]=e:"string"==typeof l?~(v="@"===l?e.lastIndexOf(l):e.indexOf(l))&&("number"==typeof c[2]?(T[E]=e.slice(0,v),e=e.slice(v+c[2])):(T[E]=e.slice(v),e=e.slice(0,v))):(v=l.exec(e))&&(T[E]=v[1],e=e.slice(0,v.index)),T[E]=T[E]||a&&c[3]&&t[E]||"",c[4]&&(T[E]=T[E].toLowerCase())):e=c(e,T);s&&(T.query=s(T.query)),a&&t.slashes&&"/"!==T.pathname.charAt(0)&&(""!==T.pathname||""!==t.pathname)&&(T.pathname=function(e,t){if(""===e)return t;for(var i=(t||"/").split("/").slice(0,-1).concat(e.split("/")),r=i.length,s=i[r-1],n=!1,a=0;r--;)"."===i[r]?i.splice(r,1):".."===i[r]?(i.splice(r,1),a++):a&&(0===r&&(n=!0),i.splice(r,1),a--);return n&&i.unshift(""),("."===s||".."===s)&&i.push(""),i.join("/")}(T.pathname,t.pathname)),"/"!==T.pathname.charAt(0)&&p(T.protocol)&&(T.pathname="/"+T.pathname),i(T.port,T.protocol)||(T.host=T.hostname,T.port=""),T.username=T.password="",T.auth&&(~(v=T.auth.indexOf(":"))?(T.username=T.auth.slice(0,v),T.username=encodeURIComponent(decodeURIComponent(T.username)),T.password=T.auth.slice(v+1),T.password=encodeURIComponent(decodeURIComponent(T.password))):T.username=encodeURIComponent(decodeURIComponent(T.auth)),T.auth=T.password?T.username+":"+T.password:T.username),T.origin="file:"!==T.protocol&&p(T.protocol)&&T.host?T.protocol+"//"+T.host:"null",T.href=T.toString()}g.prototype={set:function(e,t,s){var n=this;switch(e){case"query":"string"==typeof t&&t.length&&(t=(s||r.parse)(t)),n[e]=t;break;case"port":n[e]=t,i(t,n.protocol)?t&&(n.host=n.hostname+":"+t):(n.host=n.hostname,n[e]="");break;case"hostname":n[e]=t,n.port&&(t+=":"+n.port),n.host=t;break;case"host":n[e]=t,o.test(t)?(t=t.split(":"),n.port=t.pop(),n.hostname=t.join(":")):(n.hostname=t,n.port="");break;case"protocol":n.protocol=t.toLowerCase(),n.slashes=!s;break;case"pathname":case"hash":if(t){var a="pathname"===e?"/":"#";n[e]=t.charAt(0)!==a?a+t:t}else n[e]=t;break;case"username":case"password":n[e]=encodeURIComponent(t);break;case"auth":var l=t.indexOf(":");~l?(n.username=t.slice(0,l),n.username=encodeURIComponent(decodeURIComponent(n.username)),n.password=t.slice(l+1),n.password=encodeURIComponent(decodeURIComponent(n.password))):n.username=encodeURIComponent(decodeURIComponent(t))}for(var h=0;h<u.length;h++){var d=u[h];d[4]&&(n[d[1]]=n[d[1]].toLowerCase())}return n.auth=n.password?n.username+":"+n.password:n.username,n.origin="file:"!==n.protocol&&p(n.protocol)&&n.host?n.protocol+"//"+n.host:"null",n.href=n.toString(),n},toString:function(e){(!e||"function"!=typeof e)&&(e=r.stringify);var t,i=this,s=i.host,n=i.protocol;n&&":"!==n.charAt(n.length-1)&&(n+=":");var a=n+(i.protocol&&i.slashes||p(i.protocol)?"//":"");return i.username?(a+=i.username,i.password&&(a+=":"+i.password),a+="@"):i.password?(a+=":"+i.password,a+="@"):"file:"!==i.protocol&&p(i.protocol)&&!s&&"/"!==i.pathname&&(a+="@"),(":"===s[s.length-1]||o.test(i.hostname)&&!i.port)&&(s+=":"),a+=s+i.pathname,(t="object"==typeof i.query?e(i.query):i.query)&&(a+="?"!==t.charAt(0)?"?"+t:t),i.hash&&(a+=i.hash),a}},g.extractProtocol=m,g.location=f,g.trimLeft=d,g.qs=r,t.exports=g}));function Cr(e){return Cr="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Cr(e)}function Dr(e,t,i){return t=Or(t),function(e,t){if(t&&("object"===Cr(t)||"function"==typeof t))return t;if(void 0!==t)throw new TypeError("Derived constructors may only return object or undefined");return function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(e)}(e,Mr()?Reflect.construct(t,i||[],Or(e).constructor):t.apply(e,i))}function xr(e){var t="function"==typeof Map?new Map:void 0;return xr=function(e){if(null===e||!function(e){try{return-1!==Function.toString.call(e).indexOf("[native code]")}catch{return"function"==typeof e}}(e))return e;if("function"!=typeof e)throw new TypeError("Super expression must either be null or a function");if(typeof t<"u"){if(t.has(e))return t.get(e);t.set(e,i)}function i(){return function(e,t,i){if(Mr())return Reflect.construct.apply(null,arguments);var r=[null];r.push.apply(r,t);var s=new(e.bind.apply(e,r));return i&&Pr(s,i.prototype),s}(e,arguments,Or(this).constructor)}return i.prototype=Object.create(e.prototype,{constructor:{value:i,enumerable:!1,writable:!0,configurable:!0}}),Pr(i,e)},xr(e)}function Mr(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch{}return(Mr=function(){return!!e})()}function Pr(e,t){return Pr=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},Pr(e,t)}function Or(e){return Or=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},Or(e)}var Ur=function(){function e(t){var i,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null,s=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null,n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:null;if(function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),(i=Dr(this,e,[t])).originalRequest=s,i.originalResponse=n,i.causingError=r,null!=r&&(t+=", caused by ".concat(r.toString())),null!=s){var a=s.getHeader("X-Request-ID")||"n/a",o=s.getMethod(),l=s.getURL(),h=n?n.getStatus():"n/a",d=n?n.getBody()||"":"n/a";t+=", originated from request (method: ".concat(o,", url: ").concat(l,", response code: ").concat(h,", response text: ").concat(d,", request id: ").concat(a,")")}return i.message=t,i}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&Pr(e,t)}(e,xr(Error)),function(e){return Object.defineProperty(e,"prototype",{writable:!1}),e}(e)}(),Nr=Ur;function $r(e){return $r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},$r(e)}function Fr(e,t,i){return t&&function(e,t){for(var i=0;i<t.length;i++){var r=t[i];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,Br(r.key),r)}}(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e}function Br(e){var t=function(e,t){if("object"!=$r(e)||!e)return e;var i=e[Symbol.toPrimitive];if(void 0!==i){var r=i.call(e,t);if("object"!=$r(r))return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e,"string");return"symbol"==$r(t)?t:t+""}var Hr=Fr((function e(){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e)}),[{key:"listAllUploads",value:function(){return Promise.resolve([])}},{key:"findUploadsByFingerprint",value:function(e){return Promise.resolve([])}},{key:"removeUpload",value:function(e){return Promise.resolve()}},{key:"addUpload",value:function(e,t){return Promise.resolve(null)}}]),Gr=("function"==typeof TextDecoder&&new TextDecoder,"function"==typeof TextEncoder&&new TextEncoder,Array.prototype.slice.call("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=")),jr=((()=>{let e={};Gr.forEach(((t,i)=>e[t]=i))})(),String.fromCharCode.bind(String),"function"==typeof Uint8Array.from&&Uint8Array.from.bind(Uint8Array),e=>e.replace(/=/g,"").replace(/[+\/]/g,(e=>"+"==e?"-":"_"))),Vr=e=>Bt.from(e,"utf8").toString("base64"),Kr=(e,t=!1)=>t?jr(Vr(e)):Vr(e),Wr=Kr,qr=yt(Ir());function Yr(){Yr=function(){return t};var e,t={},i=Object.prototype,r=i.hasOwnProperty,s=Object.defineProperty||function(e,t,i){e[t]=i.value},n="function"==typeof Symbol?Symbol:{},a=n.iterator||"@@iterator",o=n.asyncIterator||"@@asyncIterator",l=n.toStringTag||"@@toStringTag";function h(e,t,i){return Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}),e[t]}try{h({},"")}catch{h=function(e,t,i){return e[t]=i}}function d(e,t,i,r){var n=t&&t.prototype instanceof v?t:v,a=Object.create(n.prototype),o=new C(r||[]);return s(a,"_invoke",{value:k(e,i,o)}),a}function u(e,t,i){try{return{type:"normal",arg:e.call(t,i)}}catch(e){return{type:"throw",arg:e}}}t.wrap=d;var c="suspendedStart",f="suspendedYield",p="executing",m="completed",g={};function v(){}function E(){}function y(){}var b={};h(b,a,(function(){return this}));var T=Object.getPrototypeOf,S=T&&T(T(D([])));S&&S!==i&&r.call(S,a)&&(b=S);var A=y.prototype=v.prototype=Object.create(b);function _(e){["next","throw","return"].forEach((function(t){h(e,t,(function(e){return this._invoke(t,e)}))}))}function w(e,t){function i(s,n,a,o){var l=u(e[s],e,n);if("throw"!==l.type){var h=l.arg,d=h.value;return d&&"object"==Qr(d)&&r.call(d,"__await")?t.resolve(d.__await).then((function(e){i("next",e,a,o)}),(function(e){i("throw",e,a,o)})):t.resolve(d).then((function(e){h.value=e,a(h)}),(function(e){return i("throw",e,a,o)}))}o(l.arg)}var n;s(this,"_invoke",{value:function(e,r){function s(){return new t((function(t,s){i(e,r,t,s)}))}return n=n?n.then(s,s):s()}})}function k(t,i,r){var s=c;return function(n,a){if(s===p)throw Error("Generator is already running");if(s===m){if("throw"===n)throw a;return{value:e,done:!0}}for(r.method=n,r.arg=a;;){var o=r.delegate;if(o){var l=L(o,r);if(l){if(l===g)continue;return l}}if("next"===r.method)r.sent=r._sent=r.arg;else if("throw"===r.method){if(s===c)throw s=m,r.arg;r.dispatchException(r.arg)}else"return"===r.method&&r.abrupt("return",r.arg);s=p;var h=u(t,i,r);if("normal"===h.type){if(s=r.done?m:f,h.arg===g)continue;return{value:h.arg,done:r.done}}"throw"===h.type&&(s=m,r.method="throw",r.arg=h.arg)}}}function L(t,i){var r=i.method,s=t.iterator[r];if(s===e)return i.delegate=null,"throw"===r&&t.iterator.return&&(i.method="return",i.arg=e,L(t,i),"throw"===i.method)||"return"!==r&&(i.method="throw",i.arg=new TypeError("The iterator does not provide a '"+r+"' method")),g;var n=u(s,t.iterator,i.arg);if("throw"===n.type)return i.method="throw",i.arg=n.arg,i.delegate=null,g;var a=n.arg;return a?a.done?(i[t.resultName]=a.value,i.next=t.nextLoc,"return"!==i.method&&(i.method="next",i.arg=e),i.delegate=null,g):a:(i.method="throw",i.arg=new TypeError("iterator result is not an object"),i.delegate=null,g)}function R(e){var t={tryLoc:e[0]};1 in e&&(t.catchLoc=e[1]),2 in e&&(t.finallyLoc=e[2],t.afterLoc=e[3]),this.tryEntries.push(t)}function I(e){var t=e.completion||{};t.type="normal",delete t.arg,e.completion=t}function C(e){this.tryEntries=[{tryLoc:"root"}],e.forEach(R,this),this.reset(!0)}function D(t){if(t||""===t){var i=t[a];if(i)return i.call(t);if("function"==typeof t.next)return t;if(!isNaN(t.length)){var s=-1,n=function i(){for(;++s<t.length;)if(r.call(t,s))return i.value=t[s],i.done=!1,i;return i.value=e,i.done=!0,i};return n.next=n}}throw new TypeError(Qr(t)+" is not iterable")}return E.prototype=y,s(A,"constructor",{value:y,configurable:!0}),s(y,"constructor",{value:E,configurable:!0}),E.displayName=h(y,l,"GeneratorFunction"),t.isGeneratorFunction=function(e){var t="function"==typeof e&&e.constructor;return!!t&&(t===E||"GeneratorFunction"===(t.displayName||t.name))},t.mark=function(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,y):(e.__proto__=y,h(e,l,"GeneratorFunction")),e.prototype=Object.create(A),e},t.awrap=function(e){return{__await:e}},_(w.prototype),h(w.prototype,o,(function(){return this})),t.AsyncIterator=w,t.async=function(e,i,r,s,n){void 0===n&&(n=Promise);var a=new w(d(e,i,r,s),n);return t.isGeneratorFunction(i)?a:a.next().then((function(e){return e.done?e.value:a.next()}))},_(A),h(A,l,"Generator"),h(A,a,(function(){return this})),h(A,"toString",(function(){return"[object Generator]"})),t.keys=function(e){var t=Object(e),i=[];for(var r in t)i.push(r);return i.reverse(),function e(){for(;i.length;){var r=i.pop();if(r in t)return e.value=r,e.done=!1,e}return e.done=!0,e}},t.values=D,C.prototype={constructor:C,reset:function(t){if(this.prev=0,this.next=0,this.sent=this._sent=e,this.done=!1,this.delegate=null,this.method="next",this.arg=e,this.tryEntries.forEach(I),!t)for(var i in this)"t"===i.charAt(0)&&r.call(this,i)&&!isNaN(+i.slice(1))&&(this[i]=e)},stop:function(){this.done=!0;var e=this.tryEntries[0].completion;if("throw"===e.type)throw e.arg;return this.rval},dispatchException:function(t){if(this.done)throw t;var i=this;function s(r,s){return o.type="throw",o.arg=t,i.next=r,s&&(i.method="next",i.arg=e),!!s}for(var n=this.tryEntries.length-1;n>=0;--n){var a=this.tryEntries[n],o=a.completion;if("root"===a.tryLoc)return s("end");if(a.tryLoc<=this.prev){var l=r.call(a,"catchLoc"),h=r.call(a,"finallyLoc");if(l&&h){if(this.prev<a.catchLoc)return s(a.catchLoc,!0);if(this.prev<a.finallyLoc)return s(a.finallyLoc)}else if(l){if(this.prev<a.catchLoc)return s(a.catchLoc,!0)}else{if(!h)throw Error("try statement without catch or finally");if(this.prev<a.finallyLoc)return s(a.finallyLoc)}}}},abrupt:function(e,t){for(var i=this.tryEntries.length-1;i>=0;--i){var s=this.tryEntries[i];if(s.tryLoc<=this.prev&&r.call(s,"finallyLoc")&&this.prev<s.finallyLoc){var n=s;break}}n&&("break"===e||"continue"===e)&&n.tryLoc<=t&&t<=n.finallyLoc&&(n=null);var a=n?n.completion:{};return a.type=e,a.arg=t,n?(this.method="next",this.next=n.finallyLoc,g):this.complete(a)},complete:function(e,t){if("throw"===e.type)throw e.arg;return"break"===e.type||"continue"===e.type?this.next=e.arg:"return"===e.type?(this.rval=this.arg=e.arg,this.method="return",this.next="end"):"normal"===e.type&&t&&(this.next=t),g},finish:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var i=this.tryEntries[t];if(i.finallyLoc===e)return this.complete(i.completion,i.afterLoc),I(i),g}},catch:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var i=this.tryEntries[t];if(i.tryLoc===e){var r=i.completion;if("throw"===r.type){var s=r.arg;I(i)}return s}}throw Error("illegal catch attempt")},delegateYield:function(t,i,r){return this.delegate={iterator:D(t),resultName:i,nextLoc:r},"next"===this.method&&(this.arg=e),g}},t}function zr(e,t,i,r,s,n,a){try{var o=e[n](a),l=o.value}catch(e){return void i(e)}o.done?t(l):Promise.resolve(l).then(r,s)}function Xr(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var i=null==e?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(null!=i){var r,s,n,a,o=[],l=!0,h=!1;try{if(n=(i=i.call(e)).next,0===t);else for(;!(l=(r=n.call(i)).done)&&(o.push(r.value),o.length!==t);l=!0);}catch(e){h=!0,s=e}finally{try{if(!l&&null!=i.return&&(a=i.return(),Object(a)!==a))return}finally{if(h)throw s}}return o}}(e,t)||Zr(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function Qr(e){return Qr="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Qr(e)}function Zr(e,t){if(e){if("string"==typeof e)return Jr(e,t);var i=Object.prototype.toString.call(e).slice(8,-1);if("Object"===i&&e.constructor&&(i=e.constructor.name),"Map"===i||"Set"===i)return Array.from(e);if("Arguments"===i||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(i))return Jr(e,t)}}function Jr(e,t){(null==t||t>e.length)&&(t=e.length);for(var i=0,r=new Array(t);i<t;i++)r[i]=e[i];return r}function es(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,r)}return i}function ts(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?es(Object(i),!0).forEach((function(t){is(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):es(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}function is(e,t,i){return(t=ss(t))in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}function rs(e,t){for(var i=0;i<t.length;i++){var r=t[i];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,ss(r.key),r)}}function ss(e){var t=function(e,t){if("object"!=Qr(e)||!e)return e;var i=e[Symbol.toPrimitive];if(void 0!==i){var r=i.call(e,t);if("object"!=Qr(r))return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e,"string");return"symbol"==Qr(t)?t:t+""}var ns="tus-v1",as="ietf-draft-03",os={endpoint:null,uploadUrl:null,metadata:{},metadataForPartialUploads:{},fingerprint:null,uploadSize:null,onProgress:null,onChunkComplete:null,onSuccess:null,onError:null,onUploadUrlAvailable:null,overridePatchMethod:!1,headers:{},addRequestId:!1,onBeforeRequest:null,onAfterResponse:null,onShouldRetry:ms,chunkSize:Number.POSITIVE_INFINITY,retryDelays:[0,1e3,3e3,5e3],parallelUploads:1,parallelUploadBoundaries:null,storeFingerprintForResuming:!0,removeFingerprintOnSuccess:!1,uploadLengthDeferred:!1,uploadDataDuringCreation:!1,urlStorage:null,fileReader:null,httpStack:null,protocol:ns},ls=function(){function e(t,i){(function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")})(this,e),"resume"in i&&console.log("tus: The `resume` option has been removed in tus-js-client v2. Please use the URL storage API instead."),this.options=i,this.options.chunkSize=Number(this.options.chunkSize),this._urlStorage=this.options.urlStorage,this.file=t,this.url=null,this._req=null,this._fingerprint=null,this._urlStorageKey=null,this._offset=null,this._aborted=!1,this._size=null,this._source=null,this._retryAttempt=0,this._retryTimeout=null,this._offsetBeforeRetry=0,this._parallelUploads=null,this._parallelUploadUrls=null}return function(e,t,i){return t&&rs(e.prototype,t),i&&rs(e,i),Object.defineProperty(e,"prototype",{writable:!1}),e}(e,[{key:"findPreviousUploads",value:function(){var e=this;return this.options.fingerprint(this.file,this.options).then((function(t){return e._urlStorage.findUploadsByFingerprint(t)}))}},{key:"resumeFromPreviousUpload",value:function(e){this.url=e.uploadUrl||null,this._parallelUploadUrls=e.parallelUploadUrls||null,this._urlStorageKey=e.urlStorageKey}},{key:"start",value:function(){var e=this,t=this.file;if(t)if([ns,as].includes(this.options.protocol))if(this.options.endpoint||this.options.uploadUrl||this.url){var i=this.options.retryDelays;if(null==i||"[object Array]"===Object.prototype.toString.call(i)){if(this.options.parallelUploads>1)for(var r=0,s=["uploadUrl","uploadSize","uploadLengthDeferred"];r<s.length;r++){var n=s[r];if(this.options[n])return void this._emitError(new Error("tus: cannot use the ".concat(n," option when parallelUploads is enabled")))}if(this.options.parallelUploadBoundaries){if(this.options.parallelUploads<=1)return void this._emitError(new Error("tus: cannot use the `parallelUploadBoundaries` option when `parallelUploads` is disabled"));if(this.options.parallelUploads!==this.options.parallelUploadBoundaries.length)return void this._emitError(new Error("tus: the `parallelUploadBoundaries` must have the same length as the value of `parallelUploads`"))}this.options.fingerprint(t,this.options).then((function(i){return e._fingerprint=i,e._source?e._source:e.options.fileReader.openFile(t,e.options.chunkSize)})).then((function(t){if(e._source=t,e.options.uploadLengthDeferred)e._size=null;else if(null!=e.options.uploadSize){if(e._size=Number(e.options.uploadSize),Number.isNaN(e._size))return void e._emitError(new Error("tus: cannot convert `uploadSize` option into a number"))}else if(e._size=e._source.size,null==e._size)return void e._emitError(new Error("tus: cannot automatically derive upload's size from input. Specify it manually using the `uploadSize` option or use the `uploadLengthDeferred` option"));e.options.parallelUploads>1||null!=e._parallelUploadUrls?e._startParallelUpload():e._startSingleUpload()})).catch((function(t){e._emitError(t)}))}else this._emitError(new Error("tus: the `retryDelays` option must either be an array or null"))}else this._emitError(new Error("tus: neither an endpoint or an upload URL is provided"));else this._emitError(new Error("tus: unsupported protocol ".concat(this.options.protocol)));else this._emitError(new Error("tus: no file or stream to upload provided"))}},{key:"_startParallelUpload",value:function(){var t,i=this,r=this._size,s=0;this._parallelUploads=[];var n=null!=this._parallelUploadUrls?this._parallelUploadUrls.length:this.options.parallelUploads,a=null!==(t=this.options.parallelUploadBoundaries)&&void 0!==t?t:function(e,t){for(var i=Math.floor(e/t),r=[],s=0;s<t;s++)r.push({start:i*s,end:i*(s+1)});return r[t-1].end=e,r}(this._source.size,n);this._parallelUploadUrls&&a.forEach((function(e,t){e.uploadUrl=i._parallelUploadUrls[t]||null})),this._parallelUploadUrls=new Array(a.length);var o,l=a.map((function(t,n){var o=0;return i._source.slice(t.start,t.end).then((function(l){var h=l.value;return new Promise((function(l,d){var u=ts(ts({},i.options),{},{uploadUrl:t.uploadUrl||null,storeFingerprintForResuming:!1,removeFingerprintOnSuccess:!1,parallelUploads:1,parallelUploadBoundaries:null,metadata:i.options.metadataForPartialUploads,headers:ts(ts({},i.options.headers),{},{"Upload-Concat":"partial"}),onSuccess:l,onError:d,onProgress:function(e){s=s-o+e,o=e,i._emitProgress(s,r)},onUploadUrlAvailable:function(){i._parallelUploadUrls[n]=c.url,i._parallelUploadUrls.filter((function(e){return!!e})).length===a.length&&i._saveUploadInUrlStorage()}}),c=new e(h,u);c.start(),i._parallelUploads.push(c)}))}))}));Promise.all(l).then((function(){(o=i._openRequest("POST",i.options.endpoint)).setHeader("Upload-Concat","final;".concat(i._parallelUploadUrls.join(" ")));var e=hs(i.options.metadata);return""!==e&&o.setHeader("Upload-Metadata",e),i._sendRequest(o,null)})).then((function(e){if(ds(e.getStatus(),200)){var t=e.getHeader("Location");null!=t?(i.url=gs(i.options.endpoint,t),"Created upload at ".concat(i.url),i._emitSuccess(e)):i._emitHttpError(o,e,"tus: invalid or missing Location header")}else i._emitHttpError(o,e,"tus: unexpected response while creating upload")})).catch((function(e){i._emitError(e)}))}},{key:"_startSingleUpload",value:function(){return this._aborted=!1,null!=this.url?("Resuming upload from previous URL: ".concat(this.url),void this._resumeUpload()):null!=this.options.uploadUrl?("Resuming upload from provided URL: ".concat(this.options.uploadUrl),this.url=this.options.uploadUrl,void this._resumeUpload()):void this._createUpload()}},{key:"abort",value:function(t){var i=this;if(null!=this._parallelUploads){var r,s=function(e,t){var i=typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(!i){if(Array.isArray(e)||(i=Zr(e))||t){i&&(e=i);var r=0,s=function(){};return{s:s,n:function(){return r>=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(e){throw e},f:s}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var n,a=!0,o=!1;return{s:function(){i=i.call(e)},n:function(){var e=i.next();return a=e.done,e},e:function(e){o=!0,n=e},f:function(){try{!a&&null!=i.return&&i.return()}finally{if(o)throw n}}}}(this._parallelUploads);try{for(s.s();!(r=s.n()).done;){r.value.abort(t)}}catch(e){s.e(e)}finally{s.f()}}return null!==this._req&&this._req.abort(),this._aborted=!0,null!=this._retryTimeout&&(clearTimeout(this._retryTimeout),this._retryTimeout=null),t&&null!=this.url?e.terminate(this.url,this.options).then((function(){return i._removeFromUrlStorage()})):Promise.resolve()}},{key:"_emitHttpError",value:function(e,t,i,r){this._emitError(new Nr(i,r,e,t))}},{key:"_emitError",value:function(e){var t=this;if(!this._aborted){if(null!=this.options.retryDelays)if(null!=this._offset&&this._offset>this._offsetBeforeRetry&&(this._retryAttempt=0),ps(e,this._retryAttempt,this.options)){var i=this.options.retryDelays[this._retryAttempt++];return this._offsetBeforeRetry=this._offset,void(this._retryTimeout=setTimeout((function(){t.start()}),i))}if("function"!=typeof this.options.onError)throw e;this.options.onError(e)}}},{key:"_emitSuccess",value:function(e){this.options.removeFingerprintOnSuccess&&this._removeFromUrlStorage(),"function"==typeof this.options.onSuccess&&this.options.onSuccess({lastResponse:e})}},{key:"_emitProgress",value:function(e,t){"function"==typeof this.options.onProgress&&this.options.onProgress(e,t)}},{key:"_emitChunkComplete",value:function(e,t,i){"function"==typeof this.options.onChunkComplete&&this.options.onChunkComplete(e,t,i)}},{key:"_createUpload",value:function(){var e=this;if(this.options.endpoint){var t=this._openRequest("POST",this.options.endpoint);this.options.uploadLengthDeferred?t.setHeader("Upload-Defer-Length","1"):t.setHeader("Upload-Length","".concat(this._size));var i,r=hs(this.options.metadata);""!==r&&t.setHeader("Upload-Metadata",r),this.options.uploadDataDuringCreation&&!this.options.uploadLengthDeferred?(this._offset=0,i=this._addChunkToRequest(t)):(this.options.protocol===as&&t.setHeader("Upload-Complete","?0"),i=this._sendRequest(t,null)),i.then((function(i){if(ds(i.getStatus(),200)){var r=i.getHeader("Location");if(null!=r)return e.url=gs(e.options.endpoint,r),"Created upload at ".concat(e.url),"function"==typeof e.options.onUploadUrlAvailable&&e.options.onUploadUrlAvailable(),0===e._size?(e._emitSuccess(i),void e._source.close()):void e._saveUploadInUrlStorage().then((function(){e.options.uploadDataDuringCreation?e._handleUploadResponse(t,i):(e._offset=0,e._performUpload())}));e._emitHttpError(t,i,"tus: invalid or missing Location header")}else e._emitHttpError(t,i,"tus: unexpected response while creating upload")})).catch((function(i){e._emitHttpError(t,null,"tus: failed to create upload",i)}))}else this._emitError(new Error("tus: unable to create upload because no endpoint is provided"))}},{key:"_resumeUpload",value:function(){var e=this,t=this._openRequest("HEAD",this.url);this._sendRequest(t,null).then((function(i){var r=i.getStatus();if(!ds(r,200))return 423===r?void e._emitHttpError(t,i,"tus: upload is currently locked; retry later"):(ds(r,400)&&e._removeFromUrlStorage(),e.options.endpoint?(e.url=null,void e._createUpload()):void e._emitHttpError(t,i,"tus: unable to resume upload (new upload cannot be created without an endpoint)"));var s=Number.parseInt(i.getHeader("Upload-Offset"),10);if(Number.isNaN(s))e._emitHttpError(t,i,"tus: invalid or missing offset value");else{var n=Number.parseInt(i.getHeader("Upload-Length"),10);!Number.isNaN(n)||e.options.uploadLengthDeferred||e.options.protocol!==ns?("function"==typeof e.options.onUploadUrlAvailable&&e.options.onUploadUrlAvailable(),e._saveUploadInUrlStorage().then((function(){if(s===n)return e._emitProgress(n,n),void e._emitSuccess(i);e._offset=s,e._performUpload()}))):e._emitHttpError(t,i,"tus: invalid or missing length value")}})).catch((function(i){e._emitHttpError(t,null,"tus: failed to resume upload",i)}))}},{key:"_performUpload",value:function(){var e,t=this;this._aborted||(this.options.overridePatchMethod?(e=this._openRequest("POST",this.url)).setHeader("X-HTTP-Method-Override","PATCH"):e=this._openRequest("PATCH",this.url),e.setHeader("Upload-Offset","".concat(this._offset)),this._addChunkToRequest(e).then((function(i){ds(i.getStatus(),200)?t._handleUploadResponse(e,i):t._emitHttpError(e,i,"tus: unexpected response while uploading chunk")})).catch((function(i){t._aborted||t._emitHttpError(e,null,"tus: failed to upload chunk at offset ".concat(t._offset),i)})))}},{key:"_addChunkToRequest",value:function(e){var t=this,i=this._offset,r=this._offset+this.options.chunkSize;return e.setProgressHandler((function(e){t._emitProgress(i+e,t._size)})),e.setHeader("Content-Type","application/offset+octet-stream"),(r===Number.POSITIVE_INFINITY||r>this._size)&&!this.options.uploadLengthDeferred&&(r=this._size),this._source.slice(i,r).then((function(i){var r=i.value,s=i.done,n=null!=r&&r.size?r.size:0;t.options.uploadLengthDeferred&&s&&(t._size=t._offset+n,e.setHeader("Upload-Length","".concat(t._size)));var a=t._offset+n;return!t.options.uploadLengthDeferred&&s&&a!==t._size?Promise.reject(new Error("upload was configured with a size of ".concat(t._size," bytes, but the source is done after ").concat(a," bytes"))):null===r?t._sendRequest(e):(t.options.protocol===as&&e.setHeader("Upload-Complete",s?"?1":"?0"),t._emitProgress(t._offset,t._size),t._sendRequest(e,r))}))}},{key:"_handleUploadResponse",value:function(e,t){var i=Number.parseInt(t.getHeader("Upload-Offset"),10);if(!Number.isNaN(i))return this._emitProgress(i,this._size),this._emitChunkComplete(i-this._offset,i,this._size),this._offset=i,i===this._size?(this._emitSuccess(t),void this._source.close()):void this._performUpload();this._emitHttpError(e,t,"tus: invalid or missing offset value")}},{key:"_openRequest",value:function(e,t){var i=us(e,t,this.options);return this._req=i,i}},{key:"_removeFromUrlStorage",value:function(){var e=this;this._urlStorageKey&&(this._urlStorage.removeUpload(this._urlStorageKey).catch((function(t){e._emitError(t)})),this._urlStorageKey=null)}},{key:"_saveUploadInUrlStorage",value:function(){var e=this;if(!this.options.storeFingerprintForResuming||!this._fingerprint||null!==this._urlStorageKey)return Promise.resolve();var t={size:this._size,metadata:this.options.metadata,creationTime:(new Date).toString()};return this._parallelUploads?t.parallelUploadUrls=this._parallelUploadUrls:t.uploadUrl=this.url,this._urlStorage.addUpload(this._fingerprint,t).then((function(t){e._urlStorageKey=t}))}},{key:"_sendRequest",value:function(e){return cs(e,arguments.length>1&&void 0!==arguments[1]?arguments[1]:null,this.options)}}],[{key:"terminate",value:function(t){var i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=us("DELETE",t,i);return cs(r,null,i).then((function(e){if(204!==e.getStatus())throw new Nr("tus: unexpected response while terminating upload",null,r,e)})).catch((function(s){if(s instanceof Nr||(s=new Nr("tus: failed to terminate upload",s,r,null)),!ps(s,0,i))throw s;var n=i.retryDelays[0],a=i.retryDelays.slice(1),o=ts(ts({},i),{},{retryDelays:a});return new Promise((function(e){return setTimeout(e,n)})).then((function(){return e.terminate(t,o)}))}))}}])}();function hs(e){return Object.entries(e).map((function(e){var t=Xr(e,2),i=t[0],r=t[1];return"".concat(i," ").concat(Wr(String(r)))})).join(",")}function ds(e,t){return e>=t&&e<t+100}function us(e,t,i){var r=i.httpStack.createRequest(e,t);i.protocol===as?r.setHeader("Upload-Draft-Interop-Version","5"):r.setHeader("Tus-Resumable","1.0.0");for(var s=i.headers||{},n=0,a=Object.entries(s);n<a.length;n++){var o=Xr(a[n],2),l=o[0],h=o[1];r.setHeader(l,h)}if(i.addRequestId){var d="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(function(e){var t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)}));r.setHeader("X-Request-ID",d)}return r}function cs(e,t,i){return fs.apply(this,arguments)}function fs(){return fs=function(e){return function(){var t=this,i=arguments;return new Promise((function(r,s){var n=e.apply(t,i);function a(e){zr(n,r,s,a,o,"next",e)}function o(e){zr(n,r,s,a,o,"throw",e)}a(void 0)}))}}(Yr().mark((function e(t,i,r){var s;return Yr().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if("function"!=typeof r.onBeforeRequest){e.next=3;break}return e.next=3,r.onBeforeRequest(t);case 3:return e.next=5,t.send(i);case 5:if(s=e.sent,"function"!=typeof r.onAfterResponse){e.next=9;break}return e.next=9,r.onAfterResponse(t,s);case 9:return e.abrupt("return",s);case 10:case"end":return e.stop()}}),e)}))),fs.apply(this,arguments)}function ps(e,t,i){return!(null==i.retryDelays||t>=i.retryDelays.length||null==e.originalRequest)&&(i&&"function"==typeof i.onShouldRetry?i.onShouldRetry(e,t,i):ms(e))}function ms(e){var t=e.originalResponse?e.originalResponse.getStatus():0;return(!ds(t,400)||409===t||423===t)&&function(){var e=!0;return typeof navigator<"u"&&!1===navigator.onLine&&(e=!1),e}()}function gs(e,t){return new qr.default(t,e).toString()}ls.defaultOptions=os;var vs=ls,Es=function(){return typeof navigator<"u"&&"string"==typeof navigator.product&&"reactnative"===navigator.product.toLowerCase()};function ys(e){return new Promise((function(t,i){var r=new XMLHttpRequest;r.responseType="blob",r.onload=function(){var e=r.response;t(e)},r.onerror=function(e){i(e)},r.open("GET",e),r.send()}))}var bs=function(){return typeof window<"u"&&(typeof window.PhoneGap<"u"||typeof window.Cordova<"u"||typeof window.cordova<"u")};function Ts(e){return Ts="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Ts(e)}function Ss(e,t,i){return t&&function(e,t){for(var i=0;i<t.length;i++){var r=t[i];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,As(r.key),r)}}(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e}function As(e){var t=function(e,t){if("object"!=Ts(e)||!e)return e;var i=e[Symbol.toPrimitive];if(void 0!==i){var r=i.call(e,t);if("object"!=Ts(r))return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e,"string");return"symbol"==Ts(t)?t:t+""}var _s=Ss((function e(t){(function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")})(this,e),this._file=t,this.size=t.size}),[{key:"slice",value:function(e,t){if(bs())return function(e){return new Promise((function(t,i){var r=new FileReader;r.onload=function(){var e=new Uint8Array(r.result);t({value:e})},r.onerror=function(e){i(e)},r.readAsArrayBuffer(e)}))}(this._file.slice(e,t));var i=this._file.slice(e,t),r=t>=this.size;return Promise.resolve({value:i,done:r})}},{key:"close",value:function(){}}]);function ws(e){return ws="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},ws(e)}function ks(e,t,i){return t&&function(e,t){for(var i=0;i<t.length;i++){var r=t[i];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,Ls(r.key),r)}}(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e}function Ls(e){var t=function(e,t){if("object"!=ws(e)||!e)return e;var i=e[Symbol.toPrimitive];if(void 0!==i){var r=i.call(e,t);if("object"!=ws(r))return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e,"string");return"symbol"==ws(t)?t:t+""}function Rs(e){return void 0===e?0:void 0!==e.size?e.size:e.length}var Is=ks((function e(t){(function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")})(this,e),this._buffer=void 0,this._bufferOffset=0,this._reader=t,this._done=!1}),[{key:"slice",value:function(e,t){return e<this._bufferOffset?Promise.reject(new Error("Requested data is before the reader's current offset")):this._readUntilEnoughDataOrDone(e,t)}},{key:"_readUntilEnoughDataOrDone",value:function(e,t){var i=this,r=t<=this._bufferOffset+Rs(this._buffer);if(this._done||r){var s=this._getDataFromBuffer(e,t),n=null==s&&this._done;return Promise.resolve({value:s,done:n})}return this._reader.read().then((function(r){var s=r.value;return r.done?i._done=!0:void 0===i._buffer?i._buffer=s:i._buffer=function(e,t){if(e.concat)return e.concat(t);if(e instanceof Blob)return new Blob([e,t],{type:e.type});if(e.set){var i=new e.constructor(e.length+t.length);return i.set(e),i.set(t,e.length),i}throw new Error("Unknown data type")}(i._buffer,s),i._readUntilEnoughDataOrDone(e,t)}))}},{key:"_getDataFromBuffer",value:function(e,t){e>this._bufferOffset&&(this._buffer=this._buffer.slice(e-this._bufferOffset),this._bufferOffset=e);var i=0===Rs(this._buffer);return this._done&&i?null:this._buffer.slice(0,t-e)}},{key:"close",value:function(){this._reader.cancel&&this._reader.cancel()}}]);function Cs(e){return Cs="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Cs(e)}function Ds(){Ds=function(){return t};var e,t={},i=Object.prototype,r=i.hasOwnProperty,s=Object.defineProperty||function(e,t,i){e[t]=i.value},n="function"==typeof Symbol?Symbol:{},a=n.iterator||"@@iterator",o=n.asyncIterator||"@@asyncIterator",l=n.toStringTag||"@@toStringTag";function h(e,t,i){return Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}),e[t]}try{h({},"")}catch{h=function(e,t,i){return e[t]=i}}function d(e,t,i,r){var n=t&&t.prototype instanceof v?t:v,a=Object.create(n.prototype),o=new C(r||[]);return s(a,"_invoke",{value:k(e,i,o)}),a}function u(e,t,i){try{return{type:"normal",arg:e.call(t,i)}}catch(e){return{type:"throw",arg:e}}}t.wrap=d;var c="suspendedStart",f="suspendedYield",p="executing",m="completed",g={};function v(){}function E(){}function y(){}var b={};h(b,a,(function(){return this}));var T=Object.getPrototypeOf,S=T&&T(T(D([])));S&&S!==i&&r.call(S,a)&&(b=S);var A=y.prototype=v.prototype=Object.create(b);function _(e){["next","throw","return"].forEach((function(t){h(e,t,(function(e){return this._invoke(t,e)}))}))}function w(e,t){function i(s,n,a,o){var l=u(e[s],e,n);if("throw"!==l.type){var h=l.arg,d=h.value;return d&&"object"==Cs(d)&&r.call(d,"__await")?t.resolve(d.__await).then((function(e){i("next",e,a,o)}),(function(e){i("throw",e,a,o)})):t.resolve(d).then((function(e){h.value=e,a(h)}),(function(e){return i("throw",e,a,o)}))}o(l.arg)}var n;s(this,"_invoke",{value:function(e,r){function s(){return new t((function(t,s){i(e,r,t,s)}))}return n=n?n.then(s,s):s()}})}function k(t,i,r){var s=c;return function(n,a){if(s===p)throw Error("Generator is already running");if(s===m){if("throw"===n)throw a;return{value:e,done:!0}}for(r.method=n,r.arg=a;;){var o=r.delegate;if(o){var l=L(o,r);if(l){if(l===g)continue;return l}}if("next"===r.method)r.sent=r._sent=r.arg;else if("throw"===r.method){if(s===c)throw s=m,r.arg;r.dispatchException(r.arg)}else"return"===r.method&&r.abrupt("return",r.arg);s=p;var h=u(t,i,r);if("normal"===h.type){if(s=r.done?m:f,h.arg===g)continue;return{value:h.arg,done:r.done}}"throw"===h.type&&(s=m,r.method="throw",r.arg=h.arg)}}}function L(t,i){var r=i.method,s=t.iterator[r];if(s===e)return i.delegate=null,"throw"===r&&t.iterator.return&&(i.method="return",i.arg=e,L(t,i),"throw"===i.method)||"return"!==r&&(i.method="throw",i.arg=new TypeError("The iterator does not provide a '"+r+"' method")),g;var n=u(s,t.iterator,i.arg);if("throw"===n.type)return i.method="throw",i.arg=n.arg,i.delegate=null,g;var a=n.arg;return a?a.done?(i[t.resultName]=a.value,i.next=t.nextLoc,"return"!==i.method&&(i.method="next",i.arg=e),i.delegate=null,g):a:(i.method="throw",i.arg=new TypeError("iterator result is not an object"),i.delegate=null,g)}function R(e){var t={tryLoc:e[0]};1 in e&&(t.catchLoc=e[1]),2 in e&&(t.finallyLoc=e[2],t.afterLoc=e[3]),this.tryEntries.push(t)}function I(e){var t=e.completion||{};t.type="normal",delete t.arg,e.completion=t}function C(e){this.tryEntries=[{tryLoc:"root"}],e.forEach(R,this),this.reset(!0)}function D(t){if(t||""===t){var i=t[a];if(i)return i.call(t);if("function"==typeof t.next)return t;if(!isNaN(t.length)){var s=-1,n=function i(){for(;++s<t.length;)if(r.call(t,s))return i.value=t[s],i.done=!1,i;return i.value=e,i.done=!0,i};return n.next=n}}throw new TypeError(Cs(t)+" is not iterable")}return E.prototype=y,s(A,"constructor",{value:y,configurable:!0}),s(y,"constructor",{value:E,configurable:!0}),E.displayName=h(y,l,"GeneratorFunction"),t.isGeneratorFunction=function(e){var t="function"==typeof e&&e.constructor;return!!t&&(t===E||"GeneratorFunction"===(t.displayName||t.name))},t.mark=function(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,y):(e.__proto__=y,h(e,l,"GeneratorFunction")),e.prototype=Object.create(A),e},t.awrap=function(e){return{__await:e}},_(w.prototype),h(w.prototype,o,(function(){return this})),t.AsyncIterator=w,t.async=function(e,i,r,s,n){void 0===n&&(n=Promise);var a=new w(d(e,i,r,s),n);return t.isGeneratorFunction(i)?a:a.next().then((function(e){return e.done?e.value:a.next()}))},_(A),h(A,l,"Generator"),h(A,a,(function(){return this})),h(A,"toString",(function(){return"[object Generator]"})),t.keys=function(e){var t=Object(e),i=[];for(var r in t)i.push(r);return i.reverse(),function e(){for(;i.length;){var r=i.pop();if(r in t)return e.value=r,e.done=!1,e}return e.done=!0,e}},t.values=D,C.prototype={constructor:C,reset:function(t){if(this.prev=0,this.next=0,this.sent=this._sent=e,this.done=!1,this.delegate=null,this.method="next",this.arg=e,this.tryEntries.forEach(I),!t)for(var i in this)"t"===i.charAt(0)&&r.call(this,i)&&!isNaN(+i.slice(1))&&(this[i]=e)},stop:function(){this.done=!0;var e=this.tryEntries[0].completion;if("throw"===e.type)throw e.arg;return this.rval},dispatchException:function(t){if(this.done)throw t;var i=this;function s(r,s){return o.type="throw",o.arg=t,i.next=r,s&&(i.method="next",i.arg=e),!!s}for(var n=this.tryEntries.length-1;n>=0;--n){var a=this.tryEntries[n],o=a.completion;if("root"===a.tryLoc)return s("end");if(a.tryLoc<=this.prev){var l=r.call(a,"catchLoc"),h=r.call(a,"finallyLoc");if(l&&h){if(this.prev<a.catchLoc)return s(a.catchLoc,!0);if(this.prev<a.finallyLoc)return s(a.finallyLoc)}else if(l){if(this.prev<a.catchLoc)return s(a.catchLoc,!0)}else{if(!h)throw Error("try statement without catch or finally");if(this.prev<a.finallyLoc)return s(a.finallyLoc)}}}},abrupt:function(e,t){for(var i=this.tryEntries.length-1;i>=0;--i){var s=this.tryEntries[i];if(s.tryLoc<=this.prev&&r.call(s,"finallyLoc")&&this.prev<s.finallyLoc){var n=s;break}}n&&("break"===e||"continue"===e)&&n.tryLoc<=t&&t<=n.finallyLoc&&(n=null);var a=n?n.completion:{};return a.type=e,a.arg=t,n?(this.method="next",this.next=n.finallyLoc,g):this.complete(a)},complete:function(e,t){if("throw"===e.type)throw e.arg;return"break"===e.type||"continue"===e.type?this.next=e.arg:"return"===e.type?(this.rval=this.arg=e.arg,this.method="return",this.next="end"):"normal"===e.type&&t&&(this.next=t),g},finish:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var i=this.tryEntries[t];if(i.finallyLoc===e)return this.complete(i.completion,i.afterLoc),I(i),g}},catch:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var i=this.tryEntries[t];if(i.tryLoc===e){var r=i.completion;if("throw"===r.type){var s=r.arg;I(i)}return s}}throw Error("illegal catch attempt")},delegateYield:function(t,i,r){return this.delegate={iterator:D(t),resultName:i,nextLoc:r},"next"===this.method&&(this.arg=e),g}},t}function xs(e,t,i,r,s,n,a){try{var o=e[n](a),l=o.value}catch(e){return void i(e)}o.done?t(l):Promise.resolve(l).then(r,s)}function Ms(e,t,i){return t&&function(e,t){for(var i=0;i<t.length;i++){var r=t[i];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,Ps(r.key),r)}}(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e}function Ps(e){var t=function(e,t){if("object"!=Cs(e)||!e)return e;var i=e[Symbol.toPrimitive];if(void 0!==i){var r=i.call(e,t);if("object"!=Cs(r))return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e,"string");return"symbol"==Cs(t)?t:t+""}var Os=Ms((function e(){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e)}),[{key:"openFile",value:function(){var e=function(e){return function(){var t=this,i=arguments;return new Promise((function(r,s){var n=e.apply(t,i);function a(e){xs(n,r,s,a,o,"next",e)}function o(e){xs(n,r,s,a,o,"throw",e)}a(void 0)}))}}(Ds().mark((function e(t,i){var r;return Ds().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!(Es()&&t&&typeof t.uri<"u")){e.next=11;break}return e.prev=1,e.next=4,ys(t.uri);case 4:return r=e.sent,e.abrupt("return",new _s(r));case 8:throw e.prev=8,e.t0=e.catch(1),new Error("tus: cannot fetch `file.uri` as Blob, make sure the uri is correct and accessible. ".concat(e.t0));case 11:if(!("function"==typeof t.slice&&typeof t.size<"u")){e.next=13;break}return e.abrupt("return",Promise.resolve(new _s(t)));case 13:if("function"!=typeof t.read){e.next=18;break}if(i=Number(i),Number.isFinite(i)){e.next=17;break}return e.abrupt("return",Promise.reject(new Error("cannot create source for stream without a finite value for the `chunkSize` option")));case 17:return e.abrupt("return",Promise.resolve(new Is(t,i)));case 18:return e.abrupt("return",Promise.reject(new Error("source object may only be an instance of File, Blob, or Reader in this environment")));case 19:case"end":return e.stop()}}),e,null,[[1,8]])})));return function(t,i){return e.apply(this,arguments)}}()}]);function Us(e){return Us="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Us(e)}function Ns(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function $s(e,t,i){return t&&function(e,t){for(var i=0;i<t.length;i++){var r=t[i];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,Fs(r.key),r)}}(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e}function Fs(e){var t=function(e,t){if("object"!=Us(e)||!e)return e;var i=e[Symbol.toPrimitive];if(void 0!==i){var r=i.call(e,t);if("object"!=Us(r))return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e,"string");return"symbol"==Us(t)?t:t+""}var Bs=$s((function e(){Ns(this,e)}),[{key:"createRequest",value:function(e,t){return new Hs(e,t)}},{key:"getName",value:function(){return"XHRHttpStack"}}]),Hs=$s((function e(t,i){Ns(this,e),this._xhr=new XMLHttpRequest,this._xhr.open(t,i,!0),this._method=t,this._url=i,this._headers={}}),[{key:"getMethod",value:function(){return this._method}},{key:"getURL",value:function(){return this._url}},{key:"setHeader",value:function(e,t){this._xhr.setRequestHeader(e,t),this._headers[e]=t}},{key:"getHeader",value:function(e){return this._headers[e]}},{key:"setProgressHandler",value:function(e){"upload"in this._xhr&&(this._xhr.upload.onprogress=function(t){t.lengthComputable&&e(t.loaded)})}},{key:"send",value:function(){var e=this,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:null;return new Promise((function(i,r){e._xhr.onload=function(){i(new Gs(e._xhr))},e._xhr.onerror=function(e){r(e)},e._xhr.send(t)}))}},{key:"abort",value:function(){return this._xhr.abort(),Promise.resolve()}},{key:"getUnderlyingObject",value:function(){return this._xhr}}]),Gs=$s((function e(t){Ns(this,e),this._xhr=t}),[{key:"getStatus",value:function(){return this._xhr.status}},{key:"getHeader",value:function(e){return this._xhr.getResponseHeader(e)}},{key:"getBody",value:function(){return this._xhr.responseText}},{key:"getUnderlyingObject",value:function(){return this._xhr}}]);function js(e){return js="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},js(e)}function Vs(e,t,i){return t&&function(e,t){for(var i=0;i<t.length;i++){var r=t[i];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,Ks(r.key),r)}}(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e}function Ks(e){var t=function(e,t){if("object"!=js(e)||!e)return e;var i=e[Symbol.toPrimitive];if(void 0!==i){var r=i.call(e,t);if("object"!=js(r))return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e,"string");return"symbol"==js(t)?t:t+""}var Ws=!1;try{Ws="localStorage"in window,qs="tusSupport",Ys=localStorage.getItem(qs),localStorage.setItem(qs,Ys),null===Ys&&localStorage.removeItem(qs)}catch(Kn){if(Kn.code!==Kn.SECURITY_ERR&&Kn.code!==Kn.QUOTA_EXCEEDED_ERR)throw Kn;Ws=!1}var qs,Ys,zs=Ws,Xs=Vs((function e(){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e)}),[{key:"findAllUploads",value:function(){var e=this._findEntries("tus::");return Promise.resolve(e)}},{key:"findUploadsByFingerprint",value:function(e){var t=this._findEntries("tus::".concat(e,"::"));return Promise.resolve(t)}},{key:"removeUpload",value:function(e){return localStorage.removeItem(e),Promise.resolve()}},{key:"addUpload",value:function(e,t){var i=Math.round(1e12*Math.random()),r="tus::".concat(e,"::").concat(i);return localStorage.setItem(r,JSON.stringify(t)),Promise.resolve(r)}},{key:"_findEntries",value:function(e){for(var t=[],i=0;i<localStorage.length;i++){var r=localStorage.key(i);if(0===r.indexOf(e))try{var s=JSON.parse(localStorage.getItem(r));s.urlStorageKey=r,t.push(s)}catch{}}return t}}]);function Qs(e){return Qs="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Qs(e)}function Zs(e,t,i){return i&&function(e,t){for(var i=0;i<t.length;i++){var r=t[i];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,on(r.key),r)}}(e,i),Object.defineProperty(e,"prototype",{writable:!1}),e}function Js(e,t,i){return t=tn(t),function(e,t){if(t&&("object"===Qs(t)||"function"==typeof t))return t;if(void 0!==t)throw new TypeError("Derived constructors may only return object or undefined");return function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(e)}(e,en()?Reflect.construct(t,i||[],tn(e).constructor):t.apply(e,i))}function en(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch{}return(en=function(){return!!e})()}function tn(e){return tn=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},tn(e)}function rn(e,t){return rn=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},rn(e,t)}function sn(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,r)}return i}function nn(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?sn(Object(i),!0).forEach((function(t){an(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):sn(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}function an(e,t,i){return(t=on(t))in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}function on(e){var t=function(e,t){if("object"!=Qs(e)||!e)return e;var i=e[Symbol.toPrimitive];if(void 0!==i){var r=i.call(e,t);if("object"!=Qs(r))return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==Qs(t)?t:t+""}var ln=nn(nn({},vs.defaultOptions),{},{httpStack:new Bs,fileReader:new Os,urlStorage:zs?new Xs:new Hr,fingerprint:function(e,t){return Es()?Promise.resolve(function(e,t){var i=e.exif?function(e){var t=0;if(0===e.length)return t;for(var i=0;i<e.length;i++){t=(t<<5)-t+e.charCodeAt(i),t&=t}return t}(JSON.stringify(e.exif)):"noexif";return["tus-rn",e.name||"noname",e.size||"nosize",i,t.endpoint].join("/")}(e,t)):Promise.resolve(["tus-br",e.name,e.type,e.size,e.lastModified,t.endpoint].join("-"))}}),hn=function(){function e(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:null,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),Js(this,e,[t,i=nn(nn({},ln),i)])}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&rn(e,t)}(e,vs),Zs(e,0,[{key:"terminate",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return t=nn(nn({},ln),t),vs.terminate(e,t)}}])}(),dn=class extends _e{constructor(){super(...arguments),this.disableCompletion=!1,this._completed=!1,this.languageController=new Qi(this)}connectedCallback(){super.connectedCallback(),window.customElements.get("lottie-player")||import("/npm/@maveio/components@0.0.150/dist/lottie-player.esm-BBAKIFYQ.js/+esm"),this.languageController.locale=this.locale||"en",this.embedChannel=kr.connect(this.token),this.embedChannel.upload_id&&(this._upload_id=this.embedChannel.upload_id),this.embedChannel.channel.on("initiate",(({upload_id:e})=>{this._upload_id=e,this.embedChannel.upload_id=e})),this.embedChannel.channel.on("completed",this.completed.bind(this)),this.embedChannel.channel.on("rendition",this.rendition.bind(this)),this.embedChannel.channel.on("error",this.error.bind(this))}requestUpdate(e,t){super.requestUpdate(e,t),"locale"===e&&(this.languageController.locale=this.locale)}reset(){this._progress=0,this._completed=!1,this.embedChannel.channel.push("reset",{})}disconnectedCallback(){super.disconnectedCallback()}handleDrop(e){if(e.preventDefault(),e.dataTransfer&&e.dataTransfer.items){for(let t of e.dataTransfer.items)if("file"===t.kind){let e=t.getAsFile();e&&(e.type.startsWith("video/")||e.type.startsWith("audio/"))&&(this._progress=1,this.upload(e))}}else if(e.dataTransfer&&e.dataTransfer.files)for(let t of e.dataTransfer.files)(t.type.startsWith("video/")||t.type.startsWith("audio/"))&&(this._progress=1,this.upload(t))}handleForm(e){this._progress=1;let t=e.target;if(t.files)for(let e of t.files)(e.type.startsWith("video/")||e.type.startsWith("audio/"))&&this.upload(e)}upload(e){this.dispatchEvent(new CustomEvent("upload",{bubbles:!0,composed:!0,detail:{file:e}}));let t=new hn(e,{endpoint:E.upload.endpoint,retryDelays:[0,3e3,5e3,1e4,2e4,6e4,6e4],metadata:{title:e.name,filetype:e.type,token:this.token,upload_id:this._upload_id},onError:e=>{console.log(e),this.dispatchEvent(new CustomEvent("failed",{bubbles:!0,composed:!0,detail:e}))},onProgress:(e,t)=>{let i=Math.round(e/t*100);i>this._progress&&(this._progress=i),this.dispatchEvent(new CustomEvent("progress",{bubbles:!0,composed:!0,detail:{progress:i}}))},onSuccess:()=>{this._progress=100,this.dispatchEvent(new CustomEvent("processing",{bubbles:!0,composed:!0}))},removeFingerprintOnSuccess:!0});t.findPreviousUploads().then((e=>{e.length&&t.resumeFromPreviousUpload(e[0]),t.start()}))}completed(e){this.disableCompletion||(this._completed=!0),this.dispatchEvent(new CustomEvent("completed",{bubbles:!0,composed:!0,detail:e}))}rendition(e){this.dispatchEvent(new CustomEvent("rendition",{bubbles:!0,composed:!0,detail:e}))}error(e){console.warn(`[mave-upload] ${e.message}`),this.dispatchEvent(new CustomEvent("error",{bubbles:!0,detail:e}))}render(){return B` ${this._progress?this.renderProgress():this.renderUpload()} `}styleOpacity(){return this.languageController.loaded?this._upload_id?{}:{pointerEvents:"none",opacity:"0.5"}:{pointerEvents:"none",opacity:"0"}}styleFont(){return this.font?{fontFamily:this.font}:{fontFamily:"system-ui"}}renderUpload(){return B`<form
      class="state"
      style=${et({...this.styleOpacity(),...this.styleFont()})}
      @dragover=${e=>e.preventDefault()}
      @drop=${this.handleDrop}
      onDragOver="this.style.boxShadow='inset 0 0 0 2px blue'"
      onDragLeave="this.style.boxShadow='inset 0 0 0 2px transparent'"
    >
      <div style="font-size: 32px; padding-bottom: 14px; font-weight: 300; opacity: 0.9;">
        ${qi("drop video here")}
      </div>
      <div style="padding-bottom: 40px; opacity: 0.5;">
        ${qi("or browse your files")}
      </div>
      <div
        style="position: relative; background: ${this.color?this.color:"#1997FF"}; width: 150px; height: 40px; overflow: hidden; border-radius: ${this.radius?this.radius:"16px"}; color: white;"
        onMouseOver="this.style.opacity='0.9'"
        onMouseOut="this.style.opacity='1'"
      >
        <input
          .disabled=${!this._upload_id}
          type="file"
          accept="video/*, audio/*"
          @change=${this.handleForm}
          style="position: absolute; top: 0; left: -150px; display: block; width: 500px; height: 100%; opacity: 0; cursor: pointer;"
        />
        <div
          style="width: 100%; height: 100%; display: flex; justify-content: center; align-items: center; text-align: center;"
        >
          <div style="padding-bottom: 2px;">${qi("select file")}</div>
        </div>
      </div>
    </form>`}renderProgress(){return B`
      ${100==this._progress?this.renderProcessing():B`
            <div class="state">
              <lottie-player
                src="https://assets1.lottiefiles.com/packages/lf20_z7DhMX.json"
                background="transparent"
                speed="1"
                style="width: 200px; height: 200px; padding-bottom: 20px;"
                loop
                autoplay
              ></lottie-player>
              <div
                style="width: 40%; height: 3px; border-radius: 3px; background: #ccc; overflow: hidden;"
              >
                <div
                  style="width: ${this._progress}%; height: 3px; background: #1997FF; transition-property: width; transition-duration: 200ms; transition-timing-function: cubic-bezier(0, 0, 0.2, 1);"
                ></div>
              </div>
              <div style="margin-top: 16px; opacity: 0.6; padding-bottom: 24px;">
                ${qi("uploading...")}
              </div>
            </div>
          `}
    `}renderProcessing(){return B`<div class="state">
      ${this._completed?B` <lottie-player
            src="https://assets1.lottiefiles.com/packages/lf20_tnlxlkom.json"
            background="transparent"
            style="width: 200px; height: 200px; padding-bottom: 20px;"
            autoplay
          ></lottie-player>`:B` <lottie-player
            src="https://assets10.lottiefiles.com/private_files/lf30_4kmk2efh.json"
            background="transparent"
            speed="2"
            style="width: 200px; height: 200px; padding-bottom: 20px;"
            loop
            autoplay
          ></lottie-player>`}
      <div style="width: 100%; height: 3px;"></div>
      <div style="margin-top: 16px; opacity: 0.6; padding-bottom: 24px;">
        ${this._completed?qi("done"):qi("just a minute...")}
      </div>
    </div>`}};dn.styles=oe`
    :host {
      all: initial;
      display: block;
      width: 100%;
      aspect-ratio: 16 / 9;
      overflow: hidden;
      position: relative;
      background: white;
      box-shadow: inset 0 0 0 1px #eee;
    }

    .state {
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      background: white;
      width: 100%;
      height: 100%;
    }
  `,bt([rt()],dn.prototype,"token",2),bt([rt()],dn.prototype,"locale",2),bt([rt()],dn.prototype,"color",2),bt([rt()],dn.prototype,"font",2),bt([rt()],dn.prototype,"radius",2),bt([rt({type:Boolean})],dn.prototype,"disableCompletion",2),bt([st()],dn.prototype,"_progress",2),bt([st()],dn.prototype,"_upload_id",2),bt([st()],dn.prototype,"_completed",2),dn=bt([(e,t)=>(e.addInitializer(Ii),e)],dn),window&&window.customElements&&(window.customElements.get("mave-upload")||window.customElements.define("mave-upload",dn));var un=Et(((e,t)=>{var i=Object.defineProperty,r=Object.getOwnPropertyDescriptor,s=Object.getOwnPropertyNames,n=Object.prototype.hasOwnProperty,a=(e,t,i)=>{if(!t.has(e))throw TypeError("Cannot "+i)},o=(e,t,i)=>(a(e,t,"read from private field"),i?i.call(e):t.get(e)),l=(e,t,i)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,i)},h=(e,t,i,r)=>(a(e,t,"write to private field"),t.set(e,i),i),d=(e,t,i)=>(a(e,t,"access private method"),i),u={};((e,t)=>{for(var r in t)i(e,r,{get:t[r],enumerable:!0})})(u,{Metrics:()=>ce}),t.exports=(e=>((e,t,a,o)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let l of s(t))!n.call(e,l)&&l!==a&&i(e,l,{get:()=>t[l],enumerable:!(o=r(t,l))||o.enumerable});return e})(i({},"__esModule",{value:!0}),e))(u);var c=e=>"function"==typeof e?e:function(){return e},f=typeof self<"u"?self:null,p=typeof window<"u"?window:null,m=f||p||m,g=0,v=1,E=2,y=3,b="closed",T="errored",S="joined",A="joining",_="leaving",w="phx_close",k="phx_error",L="phx_join",R="phx_reply",I="phx_leave",C="longpoll",D="websocket",x=4,M=class{constructor(e,t,i,r){this.channel=e,this.event=t,this.payload=i||function(){return{}},this.receivedResp=null,this.timeout=r,this.timeoutTimer=null,this.recHooks=[],this.sent=!1}resend(e){this.timeout=e,this.reset(),this.send()}send(){this.hasReceived("timeout")||(this.startTimeout(),this.sent=!0,this.channel.socket.push({topic:this.channel.topic,event:this.event,payload:this.payload(),ref:this.ref,join_ref:this.channel.joinRef()}))}receive(e,t){return this.hasReceived(e)&&t(this.receivedResp.response),this.recHooks.push({status:e,callback:t}),this}reset(){this.cancelRefEvent(),this.ref=null,this.refEvent=null,this.receivedResp=null,this.sent=!1}matchReceive({status:e,response:t,_ref:i}){this.recHooks.filter((t=>t.status===e)).forEach((e=>e.callback(t)))}cancelRefEvent(){this.refEvent&&this.channel.off(this.refEvent)}cancelTimeout(){clearTimeout(this.timeoutTimer),this.timeoutTimer=null}startTimeout(){this.timeoutTimer&&this.cancelTimeout(),this.ref=this.channel.socket.makeRef(),this.refEvent=this.channel.replyEventName(this.ref),this.channel.on(this.refEvent,(e=>{this.cancelRefEvent(),this.cancelTimeout(),this.receivedResp=e,this.matchReceive(e)})),this.timeoutTimer=setTimeout((()=>{this.trigger("timeout",{})}),this.timeout)}hasReceived(e){return this.receivedResp&&this.receivedResp.status===e}trigger(e,t){this.channel.trigger(this.refEvent,{status:e,response:t})}},P=class{constructor(e,t){this.callback=e,this.timerCalc=t,this.timer=null,this.tries=0}reset(){this.tries=0,clearTimeout(this.timer)}scheduleTimeout(){clearTimeout(this.timer),this.timer=setTimeout((()=>{this.tries=this.tries+1,this.callback()}),this.timerCalc(this.tries+1))}},O=class{constructor(e,t,i){this.state=b,this.topic=e,this.params=c(t||{}),this.socket=i,this.bindings=[],this.bindingRef=0,this.timeout=this.socket.timeout,this.joinedOnce=!1,this.joinPush=new M(this,L,this.params,this.timeout),this.pushBuffer=[],this.stateChangeRefs=[],this.rejoinTimer=new P((()=>{this.socket.isConnected()&&this.rejoin()}),this.socket.rejoinAfterMs),this.stateChangeRefs.push(this.socket.onError((()=>this.rejoinTimer.reset()))),this.stateChangeRefs.push(this.socket.onOpen((()=>{this.rejoinTimer.reset(),this.isErrored()&&this.rejoin()}))),this.joinPush.receive("ok",(()=>{this.state=S,this.rejoinTimer.reset(),this.pushBuffer.forEach((e=>e.send())),this.pushBuffer=[]})),this.joinPush.receive("error",(()=>{this.state=T,this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()})),this.onClose((()=>{this.rejoinTimer.reset(),this.socket.hasLogger()&&this.socket.log("channel",`close ${this.topic} ${this.joinRef()}`),this.state=b,this.socket.remove(this)})),this.onError((e=>{this.socket.hasLogger()&&this.socket.log("channel",`error ${this.topic}`,e),this.isJoining()&&this.joinPush.reset(),this.state=T,this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()})),this.joinPush.receive("timeout",(()=>{this.socket.hasLogger()&&this.socket.log("channel",`timeout ${this.topic} (${this.joinRef()})`,this.joinPush.timeout),new M(this,I,c({}),this.timeout).send(),this.state=T,this.joinPush.reset(),this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()})),this.on(R,((e,t)=>{this.trigger(this.replyEventName(t),e)}))}join(e=this.timeout){if(this.joinedOnce)throw new Error("tried to join multiple times. 'join' can only be called a single time per channel instance");return this.timeout=e,this.joinedOnce=!0,this.rejoin(),this.joinPush}onClose(e){this.on(w,e)}onError(e){return this.on(k,(t=>e(t)))}on(e,t){let i=this.bindingRef++;return this.bindings.push({event:e,ref:i,callback:t}),i}off(e,t){this.bindings=this.bindings.filter((i=>!(i.event===e&&(typeof t>"u"||t===i.ref))))}canPush(){return this.socket.isConnected()&&this.isJoined()}push(e,t,i=this.timeout){if(t=t||{},!this.joinedOnce)throw new Error(`tried to push '${e}' to '${this.topic}' before joining. Use channel.join() before pushing events`);let r=new M(this,e,(function(){return t}),i);return this.canPush()?r.send():(r.startTimeout(),this.pushBuffer.push(r)),r}leave(e=this.timeout){this.rejoinTimer.reset(),this.joinPush.cancelTimeout(),this.state=_;let t=()=>{this.socket.hasLogger()&&this.socket.log("channel",`leave ${this.topic}`),this.trigger(w,"leave")},i=new M(this,I,c({}),e);return i.receive("ok",(()=>t())).receive("timeout",(()=>t())),i.send(),this.canPush()||i.trigger("ok",{}),i}onMessage(e,t,i){return t}isMember(e,t,i,r){return this.topic===e&&(!r||r===this.joinRef()||(this.socket.hasLogger()&&this.socket.log("channel","dropping outdated message",{topic:e,event:t,payload:i,joinRef:r}),!1))}joinRef(){return this.joinPush.ref}rejoin(e=this.timeout){this.isLeaving()||(this.socket.leaveOpenTopic(this.topic),this.state=A,this.joinPush.resend(e))}trigger(e,t,i,r){let s=this.onMessage(e,t,i,r);if(t&&!s)throw new Error("channel onMessage callbacks must return the payload, modified or unmodified");let n=this.bindings.filter((t=>t.event===e));for(let e=0;e<n.length;e++)n[e].callback(s,i,r||this.joinRef())}replyEventName(e){return`chan_reply_${e}`}isClosed(){return this.state===b}isErrored(){return this.state===T}isJoined(){return this.state===S}isJoining(){return this.state===A}isLeaving(){return this.state===_}},U=class{static request(e,t,i,r,s,n,a){if(m.XDomainRequest){let i=new m.XDomainRequest;return this.xdomainRequest(i,e,t,r,s,n,a)}{let o=new m.XMLHttpRequest;return this.xhrRequest(o,e,t,i,r,s,n,a)}}static xdomainRequest(e,t,i,r,s,n,a){return e.timeout=s,e.open(t,i),e.onload=()=>{let t=this.parseJSON(e.responseText);a&&a(t)},n&&(e.ontimeout=n),e.onprogress=()=>{},e.send(r),e}static xhrRequest(e,t,i,r,s,n,a,o){return e.open(t,i,!0),e.timeout=n,e.setRequestHeader("Content-Type",r),e.onerror=()=>o&&o(null),e.onreadystatechange=()=>{if(e.readyState===x&&o){let t=this.parseJSON(e.responseText);o(t)}},a&&(e.ontimeout=a),e.send(s),e}static parseJSON(e){if(!e||""===e)return null;try{return JSON.parse(e)}catch{return console&&console.log("failed to parse JSON response",e),null}}static serialize(e,t){let i=[];for(var r in e){if(!Object.prototype.hasOwnProperty.call(e,r))continue;let s=t?`${t}[${r}]`:r,n=e[r];"object"==typeof n?i.push(this.serialize(n,s)):i.push(encodeURIComponent(s)+"="+encodeURIComponent(n))}return i.join("&")}static appendParams(e,t){if(0===Object.keys(t).length)return e;let i=e.match(/\?/)?"&":"?";return`${e}${i}${this.serialize(t)}`}},N=class{constructor(e){this.endPoint=null,this.token=null,this.skipHeartbeat=!0,this.reqs=new Set,this.awaitingBatchAck=!1,this.currentBatch=null,this.currentBatchTimer=null,this.batchBuffer=[],this.onopen=function(){},this.onerror=function(){},this.onmessage=function(){},this.onclose=function(){},this.pollEndpoint=this.normalizeEndpoint(e),this.readyState=g,setTimeout((()=>this.poll()),0)}normalizeEndpoint(e){return e.replace("ws://","http://").replace("wss://","https://").replace(new RegExp("(.*)/"+D),"$1/"+C)}endpointURL(){return U.appendParams(this.pollEndpoint,{token:this.token})}closeAndRetry(e,t,i){this.close(e,t,i),this.readyState=g}ontimeout(){this.onerror("timeout"),this.closeAndRetry(1005,"timeout",!1)}isActive(){return this.readyState===v||this.readyState===g}poll(){this.ajax("GET","application/json",null,(()=>this.ontimeout()),(e=>{if(e){var{status:t,token:i,messages:r}=e;this.token=i}else t=0;switch(t){case 200:r.forEach((e=>{setTimeout((()=>this.onmessage({data:e})),0)})),this.poll();break;case 204:this.poll();break;case 410:this.readyState=v,this.onopen({}),this.poll();break;case 403:this.onerror(403),this.close(1008,"forbidden",!1);break;case 0:case 500:this.onerror(500),this.closeAndRetry(1011,"internal server error",500);break;default:throw new Error(`unhandled poll status ${t}`)}}))}send(e){"string"!=typeof e&&(e=(e=>{let t="",i=new Uint8Array(e),r=i.byteLength;for(let e=0;e<r;e++)t+=String.fromCharCode(i[e]);return btoa(t)})(e)),this.currentBatch?this.currentBatch.push(e):this.awaitingBatchAck?this.batchBuffer.push(e):(this.currentBatch=[e],this.currentBatchTimer=setTimeout((()=>{this.batchSend(this.currentBatch),this.currentBatch=null}),0))}batchSend(e){this.awaitingBatchAck=!0,this.ajax("POST","application/x-ndjson",e.join("\n"),(()=>this.onerror("timeout")),(e=>{this.awaitingBatchAck=!1,e&&200===e.status?this.batchBuffer.length>0&&(this.batchSend(this.batchBuffer),this.batchBuffer=[]):(this.onerror(e&&e.status),this.closeAndRetry(1011,"internal server error",!1))}))}close(e,t,i){for(let e of this.reqs)e.abort();this.readyState=y;let r=Object.assign({code:1e3,reason:void 0,wasClean:!0},{code:e,reason:t,wasClean:i});this.batchBuffer=[],clearTimeout(this.currentBatchTimer),this.currentBatchTimer=null,typeof CloseEvent<"u"?this.onclose(new CloseEvent("close",r)):this.onclose(r)}ajax(e,t,i,r,s){let n;n=U.request(e,this.endpointURL(),t,i,this.timeout,(()=>{this.reqs.delete(n),r()}),(e=>{this.reqs.delete(n),this.isActive()&&s(e)})),this.reqs.add(n)}},$={HEADER_LENGTH:1,META_LENGTH:4,KINDS:{push:0,reply:1,broadcast:2},encode(e,t){if(e.payload.constructor===ArrayBuffer)return t(this.binaryEncode(e));{let i=[e.join_ref,e.ref,e.topic,e.event,e.payload];return t(JSON.stringify(i))}},decode(e,t){if(e.constructor===ArrayBuffer)return t(this.binaryDecode(e));{let[i,r,s,n,a]=JSON.parse(e);return t({join_ref:i,ref:r,topic:s,event:n,payload:a})}},binaryEncode(e){let{join_ref:t,ref:i,event:r,topic:s,payload:n}=e,a=this.META_LENGTH+t.length+i.length+s.length+r.length,o=new ArrayBuffer(this.HEADER_LENGTH+a),l=new DataView(o),h=0;l.setUint8(h++,this.KINDS.push),l.setUint8(h++,t.length),l.setUint8(h++,i.length),l.setUint8(h++,s.length),l.setUint8(h++,r.length),Array.from(t,(e=>l.setUint8(h++,e.charCodeAt(0)))),Array.from(i,(e=>l.setUint8(h++,e.charCodeAt(0)))),Array.from(s,(e=>l.setUint8(h++,e.charCodeAt(0)))),Array.from(r,(e=>l.setUint8(h++,e.charCodeAt(0))));var d=new Uint8Array(o.byteLength+n.byteLength);return d.set(new Uint8Array(o),0),d.set(new Uint8Array(n),o.byteLength),d.buffer},binaryDecode(e){let t=new DataView(e),i=t.getUint8(0),r=new TextDecoder;switch(i){case this.KINDS.push:return this.decodePush(e,t,r);case this.KINDS.reply:return this.decodeReply(e,t,r);case this.KINDS.broadcast:return this.decodeBroadcast(e,t,r)}},decodePush(e,t,i){let r=t.getUint8(1),s=t.getUint8(2),n=t.getUint8(3),a=this.HEADER_LENGTH+this.META_LENGTH-1,o=i.decode(e.slice(a,a+r));a+=r;let l=i.decode(e.slice(a,a+s));a+=s;let h=i.decode(e.slice(a,a+n));return a+=n,{join_ref:o,ref:null,topic:l,event:h,payload:e.slice(a,e.byteLength)}},decodeReply(e,t,i){let r=t.getUint8(1),s=t.getUint8(2),n=t.getUint8(3),a=t.getUint8(4),o=this.HEADER_LENGTH+this.META_LENGTH,l=i.decode(e.slice(o,o+r));o+=r;let h=i.decode(e.slice(o,o+s));o+=s;let d=i.decode(e.slice(o,o+n));o+=n;let u=i.decode(e.slice(o,o+a));o+=a;let c=e.slice(o,e.byteLength);return{join_ref:l,ref:h,topic:d,event:R,payload:{status:u,response:c}}},decodeBroadcast(e,t,i){let r=t.getUint8(1),s=t.getUint8(2),n=this.HEADER_LENGTH+2,a=i.decode(e.slice(n,n+r));n+=r;let o=i.decode(e.slice(n,n+s));return n+=s,{join_ref:null,ref:null,topic:a,event:o,payload:e.slice(n,e.byteLength)}}},F=class{constructor(e,t={}){this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.channels=[],this.sendBuffer=[],this.ref=0,this.timeout=t.timeout||1e4,this.transport=t.transport||m.WebSocket||N,this.primaryPassedHealthCheck=!1,this.longPollFallbackMs=t.longPollFallbackMs,this.fallbackTimer=null,this.sessionStore=t.sessionStorage||m&&m.sessionStorage,this.establishedConnections=0,this.defaultEncoder=$.encode.bind($),this.defaultDecoder=$.decode.bind($),this.closeWasClean=!1,this.binaryType=t.binaryType||"arraybuffer",this.connectClock=1,this.transport!==N?(this.encode=t.encode||this.defaultEncoder,this.decode=t.decode||this.defaultDecoder):(this.encode=this.defaultEncoder,this.decode=this.defaultDecoder);let i=null;p&&p.addEventListener&&(p.addEventListener("pagehide",(e=>{this.conn&&(this.disconnect(),i=this.connectClock)})),p.addEventListener("pageshow",(e=>{i===this.connectClock&&(i=null,this.connect())}))),this.heartbeatIntervalMs=t.heartbeatIntervalMs||3e4,this.rejoinAfterMs=e=>t.rejoinAfterMs?t.rejoinAfterMs(e):[1e3,2e3,5e3][e-1]||1e4,this.reconnectAfterMs=e=>t.reconnectAfterMs?t.reconnectAfterMs(e):[10,50,100,150,200,250,500,1e3,2e3][e-1]||5e3,this.logger=t.logger||null,!this.logger&&t.debug&&(this.logger=(e,t,i)=>{console.log(`${e}: ${t}`,i)}),this.longpollerTimeout=t.longpollerTimeout||2e4,this.params=c(t.params||{}),this.endPoint=`${e}/${D}`,this.vsn=t.vsn||"2.0.0",this.heartbeatTimeoutTimer=null,this.heartbeatTimer=null,this.pendingHeartbeatRef=null,this.reconnectTimer=new P((()=>{this.teardown((()=>this.connect()))}),this.reconnectAfterMs)}getLongPollTransport(){return N}replaceTransport(e){this.connectClock++,this.closeWasClean=!0,clearTimeout(this.fallbackTimer),this.reconnectTimer.reset(),this.conn&&(this.conn.close(),this.conn=null),this.transport=e}protocol(){return location.protocol.match(/^https/)?"wss":"ws"}endPointURL(){let e=U.appendParams(U.appendParams(this.endPoint,this.params()),{vsn:this.vsn});return"/"!==e.charAt(0)?e:"/"===e.charAt(1)?`${this.protocol()}:${e}`:`${this.protocol()}://${location.host}${e}`}disconnect(e,t,i){this.connectClock++,this.closeWasClean=!0,clearTimeout(this.fallbackTimer),this.reconnectTimer.reset(),this.teardown(e,t,i)}connect(e){e&&(console&&console.log("passing params to connect is deprecated. Instead pass :params to the Socket constructor"),this.params=c(e)),!this.conn&&(this.longPollFallbackMs&&this.transport!==N?this.connectWithFallback(N,this.longPollFallbackMs):this.transportConnect())}log(e,t,i){this.logger&&this.logger(e,t,i)}hasLogger(){return null!==this.logger}onOpen(e){let t=this.makeRef();return this.stateChangeCallbacks.open.push([t,e]),t}onClose(e){let t=this.makeRef();return this.stateChangeCallbacks.close.push([t,e]),t}onError(e){let t=this.makeRef();return this.stateChangeCallbacks.error.push([t,e]),t}onMessage(e){let t=this.makeRef();return this.stateChangeCallbacks.message.push([t,e]),t}ping(e){if(!this.isConnected())return!1;let t=this.makeRef(),i=Date.now();this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:t});let r=this.onMessage((s=>{s.ref===t&&(this.off([r]),e(Date.now()-i))}));return!0}transportConnect(){this.connectClock++,this.closeWasClean=!1,this.conn=new this.transport(this.endPointURL()),this.conn.binaryType=this.binaryType,this.conn.timeout=this.longpollerTimeout,this.conn.onopen=()=>this.onConnOpen(),this.conn.onerror=e=>this.onConnError(e),this.conn.onmessage=e=>this.onConnMessage(e),this.conn.onclose=e=>this.onConnClose(e)}getSession(e){return this.sessionStore&&this.sessionStore.getItem(e)}storeSession(e,t){this.sessionStore&&this.sessionStore.setItem(e,t)}connectWithFallback(e,t=2500){clearTimeout(this.fallbackTimer);let i,r=!1,s=!0,n=t=>{this.log("transport",`falling back to ${e.name}...`,t),this.off([undefined,i]),s=!1,this.replaceTransport(e),this.transportConnect()};if(this.getSession(`phx:fallback:${e.name}`))return n("memorized");this.fallbackTimer=setTimeout(n,t),i=this.onError((e=>{this.log("transport","error",e),s&&!r&&(clearTimeout(this.fallbackTimer),n(e))})),this.onOpen((()=>{if(r=!0,!s)return this.primaryPassedHealthCheck||this.storeSession(`phx:fallback:${e.name}`,"true"),this.log("transport",`established ${e.name} fallback`);clearTimeout(this.fallbackTimer),this.fallbackTimer=setTimeout(n,t),this.ping((e=>{this.log("transport","connected to primary after",e),this.primaryPassedHealthCheck=!0,clearTimeout(this.fallbackTimer)}))})),this.transportConnect()}clearHeartbeats(){clearTimeout(this.heartbeatTimer),clearTimeout(this.heartbeatTimeoutTimer)}onConnOpen(){this.hasLogger()&&this.log("transport",`${this.transport.name} connected to ${this.endPointURL()}`),this.closeWasClean=!1,this.establishedConnections++,this.flushSendBuffer(),this.reconnectTimer.reset(),this.resetHeartbeat(),this.stateChangeCallbacks.open.forEach((([,e])=>e()))}heartbeatTimeout(){this.pendingHeartbeatRef&&(this.pendingHeartbeatRef=null,this.hasLogger()&&this.log("transport","heartbeat timeout. Attempting to re-establish connection"),this.triggerChanError(),this.closeWasClean=!1,this.teardown((()=>this.reconnectTimer.scheduleTimeout()),1e3,"heartbeat timeout"))}resetHeartbeat(){this.conn&&this.conn.skipHeartbeat||(this.pendingHeartbeatRef=null,this.clearHeartbeats(),this.heartbeatTimer=setTimeout((()=>this.sendHeartbeat()),this.heartbeatIntervalMs))}teardown(e,t,i){if(!this.conn)return e&&e();this.waitForBufferDone((()=>{this.conn&&(t?this.conn.close(t,i||""):this.conn.close()),this.waitForSocketClosed((()=>{this.conn&&(this.conn.onopen=function(){},this.conn.onerror=function(){},this.conn.onmessage=function(){},this.conn.onclose=function(){},this.conn=null),e&&e()}))}))}waitForBufferDone(e,t=1){5!==t&&this.conn&&this.conn.bufferedAmount?setTimeout((()=>{this.waitForBufferDone(e,t+1)}),150*t):e()}waitForSocketClosed(e,t=1){5!==t&&this.conn&&this.conn.readyState!==y?setTimeout((()=>{this.waitForSocketClosed(e,t+1)}),150*t):e()}onConnClose(e){let t=e&&e.code;this.hasLogger()&&this.log("transport","close",e),this.triggerChanError(),this.clearHeartbeats(),!this.closeWasClean&&1e3!==t&&this.reconnectTimer.scheduleTimeout(),this.stateChangeCallbacks.close.forEach((([,t])=>t(e)))}onConnError(e){this.hasLogger()&&this.log("transport",e);let t=this.transport,i=this.establishedConnections;this.stateChangeCallbacks.error.forEach((([,r])=>{r(e,t,i)})),(t===this.transport||i>0)&&this.triggerChanError()}triggerChanError(){this.channels.forEach((e=>{e.isErrored()||e.isLeaving()||e.isClosed()||e.trigger(k)}))}connectionState(){switch(this.conn&&this.conn.readyState){case g:return"connecting";case v:return"open";case E:return"closing";default:return"closed"}}isConnected(){return"open"===this.connectionState()}remove(e){this.off(e.stateChangeRefs),this.channels=this.channels.filter((t=>t!==e))}off(e){for(let t in this.stateChangeCallbacks)this.stateChangeCallbacks[t]=this.stateChangeCallbacks[t].filter((([t])=>-1===e.indexOf(t)))}channel(e,t={}){let i=new O(e,t,this);return this.channels.push(i),i}push(e){if(this.hasLogger()){let{topic:t,event:i,payload:r,ref:s,join_ref:n}=e;this.log("push",`${t} ${i} (${n}, ${s})`,r)}this.isConnected()?this.encode(e,(e=>this.conn.send(e))):this.sendBuffer.push((()=>this.encode(e,(e=>this.conn.send(e)))))}makeRef(){let e=this.ref+1;return e===this.ref?this.ref=0:this.ref=e,this.ref.toString()}sendHeartbeat(){this.pendingHeartbeatRef&&!this.isConnected()||(this.pendingHeartbeatRef=this.makeRef(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef}),this.heartbeatTimeoutTimer=setTimeout((()=>this.heartbeatTimeout()),this.heartbeatIntervalMs))}flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>0&&(this.sendBuffer.forEach((e=>e())),this.sendBuffer=[])}onConnMessage(e){this.decode(e.data,(e=>{let{topic:t,event:i,payload:r,ref:s,join_ref:n}=e;s&&s===this.pendingHeartbeatRef&&(this.clearHeartbeats(),this.pendingHeartbeatRef=null,this.heartbeatTimer=setTimeout((()=>this.sendHeartbeat()),this.heartbeatIntervalMs)),this.hasLogger()&&this.log("receive",`${r.status||""} ${t} ${i} ${s&&"("+s+")"||""}`,r);for(let e=0;e<this.channels.length;e++){let a=this.channels[e];a.isMember(t,i,r,n)&&a.trigger(i,r,s,n)}for(let t=0;t<this.stateChangeCallbacks.message.length;t++){let[,i]=this.stateChangeCallbacks.message[t];i(e)}}))}leaveOpenTopic(e){let t=this.channels.find((t=>t.topic===e&&(t.isJoined()||t.isJoining())));t&&(this.hasLogger()&&this.log("transport",`leaving duplicate topic "${e}"`),t.leave())}};var B,H,G,j,V,K,W=class{constructor(){l(this,B,void 0),l(this,H,void 0),l(this,G,void 0),l(this,j,!1),l(this,V,!1),l(this,K,new Map)}static set config(e){W.instance||(W.instance=new W),h(W.instance,H,e.socketPath),h(W.instance,G,e.apiKey)}static connect(){if(W.instance||(W.instance=new W),!o(W.instance,G)&&!o(W.instance,V)&&(console.warn("[metrics]: Set apiKey using `Metrics.config = {apiKey: 'your_key'}`"),h(W.instance,V,!0)),!o(W.instance,H)&&!o(W.instance,j)&&(console.warn("[metrics]: Set path using `Metrics.config = {socketPath: 'ws://localhost:3000/socket`}"),h(W.instance,j,!0)),!o(W.instance,B)&&window){let e=e=>[1e3,5e3,1e4][e-1]||25e3;h(W.instance,B,new F(o(W.instance,H)||"ws://localhost:3000/socket",{params:{source_url:`${window.location.protocol}//${window.location.host}${window.location.pathname}`,key:o(W.instance,G)},reconnectAfterMs:e,rejoinAfterMs:e})),o(W.instance,B).connect()}return o(W.instance,B)}static startSession(e,t){let i=o(W.instance,K).get(e);if(i)return i;let r=o(W.instance,B).channel(`session:${crypto.getRandomValues(new Uint8Array(21)).reduce(((e,t)=>e+((t&=63)<36?t.toString(36):t<62?(t-26).toString(36).toUpperCase():t<63?"_":"-")),"")}`,{...t,source_url:window.location.href,key:o(W.instance,G)});return o(W.instance,K).set(e,r),r.join(),r}static stopSession(e){let t=o(W.instance,K).get(e);t&&(t.leave(),o(W.instance,K).delete(e))}},q=W;B=new WeakMap,H=new WeakMap,G=new WeakMap,j=new WeakMap,V=new WeakMap,K=new WeakMap;var Y,z,X,Q,Z,J,ee,te,ie,re,se,ne,ae,oe,le,he,de=class{static log(e){console.log(`[mave_metrics]: ${e}`)}static error(e){console.error(`[mave_metrics]: ${e}`)}},ue=(e=>(e.DURATIONCHANGE="durationchange",e.LOADEDMETADATA="loadedmetadata",e.TIMEUPDATE="timeupdate",e.LOADEDDATA="loadeddata",e.CANPLAY="canplay",e.CANPLAYTHROUGH="canplaythrough",e.SEEKING="seeking",e.SEEKED="seeked",e.RATECHANGE="ratechange",e.VOLUMECHANGE="volumechange",e.PLAYING="playing",e.ENDED="ended",e.PLAY="play",e.PAUSE="pause",e.ERROR="error",e))(ue||{}),ce=class{constructor(...e){l(this,ee),l(this,ie),l(this,se),l(this,ae),l(this,le),this.VERSION="0.1.5",this.timeout=1e4,l(this,Y,void 0),l(this,z,void 0),l(this,X,void 0),l(this,Q,null),this.bufferTimeInterval=50,this.bufferOffset=(this.bufferTimeInterval-40)/1e3,this.fullscreen=!1,l(this,Z,void 0),l(this,J,!1),e.length<=1?de.error("Metrics requires at least two arguments: a querySelectorable, hls instance or HTMLMediaElement/HTMLVideoElement and a metadata object to identify your video."):("string"==typeof e[0]&&(this.querySelectorable=e[0],this.identifier=e[1]),e[0]instanceof HTMLVideoElement||e[0]instanceof HTMLMediaElement?h(this,Y,e[0]):"object"==typeof e[0]&&(this.hls=e[0]),2==e.length&&"object"==typeof e[1]?this.metadata=e[1]:this.identifier=e[1],e[2]&&(this.metadata=e[2]),e[3]&&(this.session_data=e[3]))}static set config(e){q.config=e}monitor(){let e=this.querySelectorable?document.querySelector(this.querySelectorable):this.hls?.media;return o(this,J)||(e||o(this,Y)?(o(this,Y)||h(this,Y,e),h(this,z,d(this,ee,te).call(this,o(this,Y))),d(this,ie,re).call(this),h(this,J,!0)):de.error(`${this.querySelectorable} is not a valid reference to a HTMLVideoElement.`)),this}demonitor(){o(this,J)&&(o(this,Z)?.unobserve(o(this,Y)),d(this,se,ne).call(this),o(this,z)&&o(this,Y)&&q.stopSession(o(this,Y)))}};Y=new WeakMap,z=new WeakMap,X=new WeakMap,Q=new WeakMap,Z=new WeakMap,J=new WeakMap,ee=new WeakSet,te=function(e){return q.connect(),q.startSession(e,{identifier:this.identifier,metadata:this.metadata,session_data:this.session_data})},ie=new WeakSet,re=function(){for(let e of Object.values(ue))o(this,Y).addEventListener(e,d(this,ae,oe).bind(this))},se=new WeakSet,ne=function(){for(let e of Object.values(ue))o(this,Y).removeEventListener(e,d(this,ae,oe).bind(this))},ae=new WeakSet,oe=function(e){let t={name:e.type,duration:o(this,Y)?.duration};switch(e.type){case"playing":if("play"===o(this,Q))break;o(this,z)?.push("event",{...t,name:"play",from:o(this,Y)?.currentTime<1?0:d(this,le,he).call(this)},this.timeout),h(this,Q,"play");break;case"pause":if(4===o(this,Y)?.readyState){if("pause"===o(this,Q))break;o(this,z)?.push("event",{...t,to:d(this,le,he).call(this)},this.timeout)}h(this,Q,"pause");break;case"timeupdate":if(o(this,Y)?.ended){h(this,X,void 0);break}if(o(this,X)&&!o(this,Y).paused&&Math.abs(o(this,Y)?.currentTime-o(this,X))>.5){if("pause"===o(this,Q))break;o(this,z)?.push("event",{...t,name:"pause",to:o(this,X)},this.timeout),h(this,Q,"pause")}h(this,X,o(this,Y)?.currentTime)}},le=new WeakSet,he=function(){return o(this,Y)?.currentTime.toFixed(2)}})),cn=class{constructor(e,{target:t,config:i,callback:r,skipInitial:s}){this.t=new Set,this.o=!1,this.i=!1,this.h=e,null!==t&&this.t.add(t??e),this.o=s??this.o,this.callback=r,window.IntersectionObserver?(this.u=new IntersectionObserver((e=>{let t=this.i;this.i=!1,this.o&&t||(this.handleChanges(e),this.h.requestUpdate())}),i),e.addController(this)):console.warn("IntersectionController error: browser does not support IntersectionObserver.")}handleChanges(e){this.value=this.callback?.(e,this.u)}hostConnected(){for(let e of this.t)this.observe(e)}hostDisconnected(){this.disconnect()}async hostUpdated(){let e=this.u.takeRecords();e.length&&this.handleChanges(e)}observe(e){this.t.add(e),this.u.observe(e),this.i=!0}unobserve(e){this.t.delete(e),this.u.unobserve(e)}disconnect(){this.u.disconnect()}},fn=(e,t)=>{let i=e._$AN;if(void 0===i)return!1;for(let e of i)e._$AO?.(t,!1),fn(e,t);return!0},pn=e=>{let t,i;do{if(void 0===(t=e._$AM))break;i=t._$AN,i.delete(e),e=t}while(0===i?.size)},mn=e=>{for(let t;t=e._$AM;e=t){let i=t._$AN;if(void 0===i)t._$AN=i=new Set;else if(i.has(e))break;i.add(e),Rn(t)}};function gn(e){void 0!==this._$AN?(pn(this),this._$AM=e,mn(this)):this._$AM=e}function vn(e,t=!1,i=0){let r=this._$AH,s=this._$AN;if(void 0!==s&&0!==s.size)if(t)if(Array.isArray(r))for(let e=i;e<r.length;e++)fn(r[e],!1),pn(r[e]);else null!=r&&(fn(r,!1),pn(r));else fn(this,e)}var En,yn,bn,Tn,Sn,An,_n,wn,kn,Ln,Rn=e=>{e.type==ze&&(e._$AP??(e._$AP=vn),e._$AQ??(e._$AQ=gn))},In=class extends Qe{constructor(){super(...arguments),this._$AN=void 0}_$AT(e,t,i){super._$AT(e,t,i),mn(this),this.isConnected=e._$AU}_$AO(e,t=!0){e!==this.isConnected&&(this.isConnected=e,e?this.reconnected?.():this.disconnected?.()),t&&(fn(this,e),pn(this))}setValue(e){if((e=>void 0===e.strings)(this._$Ct))this._$Ct._$AI(e,this);else{let t=[...this._$Ct._$AH];t[this._$Ci]=e,this._$Ct._$AI(t,this,0)}}disconnected(){}reconnected(){}},Cn=new WeakMap,Dn=Xe(class extends In{render(e){return G}update(e,[t]){let i=t!==this.Y;return i&&void 0!==this.Y&&this.rt(void 0),(i||this.lt!==this.ct)&&(this.Y=t,this.ht=e.options?.host,this.rt(this.ct=e.element)),G}rt(e){if("function"==typeof this.Y){let t=this.ht??globalThis,i=Cn.get(t);void 0===i&&(i=new WeakMap,Cn.set(t,i)),void 0!==i.get(this.Y)&&this.Y.call(this.ht,void 0),i.set(this.Y,e),void 0!==e&&this.Y.call(this.ht,e)}else this.Y.value=e}get lt(){return"function"==typeof this.Y?Cn.get(this.ht??globalThis)?.get(this.Y):this.Y?.value}disconnected(){this.lt===this.ct&&this.rt(void 0)}reconnected(){this.rt(this.ct)}}),xn=["audioprocess","canplay","canplaythrough","complete","duration_change","emptied","ended","error","loadeddata","loadedmetadata","loadstart","pause","play","playing","progress","ratechange","seeked","seeking","stalled","suspend","timeupdate","volumechange","waiting"],Mn=E.api.endpoint,Pn=(e=>(e[e.Collection=0]="Collection",e[e.Embed=1]="Embed",e))(Pn||{}),On=class{constructor(e,t=1){this.caching=!0,this.loading=!0,this.host=e,this.type=t,this.loading=!0,this.task=new g(this.host,(async()=>{try{if(1==this.type&&!this.embed)return;if(0==this.type&&!this.token)return void console.warn("No token attr provided for mave-list");let e=await(await fetch(this.manifest_url)).json();return this.loading=!1,1==this.type?(this._embedData=e,this.version=this._embedData.video?.version||0,this._embedData):e}catch(e){throw console.log(e),new Error(`Failed to fetch "${this.embed}"`)}}),(()=>[this.embed]))}get manifest_url(){if(1==this.type)return this.embedFile("manifest.json");{let e=new URL(`${Mn}/collection/${this.token}`);return this.embed&&this.embed?.length>1&&e.searchParams.append("embed",this.embed),e.toString()}}set embed(e){this._embed!=e&&(this._embed=e,this.loading=!0,this.host.requestUpdate())}get embed(){return this._embed}set token(e){this._token!=e&&(this._token=e,this.host.requestUpdate())}get token(){return this._token}get spaceId(){return this.embed?.substring(0,5)}get embedId(){return this.embed?.substring(5,this.embed?.length)}get version(){return this._version?`/v${this._version}/`:"/"}set version(e){this._version!=e&&(this._version=e,this.host.requestUpdate())}get cdnRoot(){return E.cdn.endpoint.replace("${this.spaceId}",this.spaceId)}refresh(){return this.loading=!0,this.task?.run()}embedFile(e,t=new URLSearchParams){let i=new URL(`${this.cdnRoot}/${this.embedId}${"manifest"==e?"/":this.version}${e}`);if(e.includes("?")){let[i,r]=e.split("?");new URLSearchParams(r).forEach(((e,i)=>{t.append(i,e)}))}if(this.token&&t.append("token",this.token),"manifest"==e&&(t.has("e")&&t.delete("e"),t.append("e",(new Date).getTime().toString())),"manifest"!==e&&this._embedData?.created_at){let e=this.caching?new Date(this._embedData.created_at):new Date;t.has("e")||t.append("e",e.getTime().toString())}return i.search=t.toString(),i.toString()}render(e){return this.task?.render(e)}},Un=yt(un(),1),Nn=class extends _e{constructor(){super(...arguments),At(this,En),this.autoplay="lazy",this.quality="auto",this.fallback="placeholder",this._queue=[],this._failedPlay=!1,this._intersectionObserver=new cn(this,{callback:_t(this,En,kn).bind(this)}),this.embedController=new On(this)}get embed(){return this._embedId}set embed(e){this._embedId!=e&&(this._embedId=e,this.requestUpdate("embed"),this.embedController.embed=this.embed)}set loop(e){this._loop=(""===e||"true"==e||1==e)??!1}get loop(){return this._loop}get poster(){return this.embedController.embedFile(`${this.fallback}.jpg`)}set poster(e){if(e){let t=this._poster;this._poster=e,this.requestUpdate("poster",t)}}get token(){return this._token}set token(e){this._token!=e&&(this._token=e,this.requestUpdate("token"),this.embedController.token=this._token)}get sources(){let e="scroll"===this.autoplay?["clip_keyframes"]:["video","clip"],t=this._embed.video.renditions.filter((t=>("auto"==this.quality?"uhd"!==t.size:St(this,En,bn).indexOf(t.size)<=St(this,En,bn).indexOf(this.quality))&&"mp4"===t.container&&St(this,En,Tn).includes(t.codec)&&(!t.type||e.includes(t.type)))).sort(((e,t)=>e.size===t.size?St(this,En,Tn).indexOf(e.codec)-St(this,En,Tn).indexOf(t.codec):St(this,En,bn).indexOf(t.size)-St(this,En,bn).indexOf(e.size))).map((e=>{let t=St(this,En,An).find((t=>t.size===e.size))?.media,i=`${e.codec}_${e.size}${e.type&&"video"!=e.type?`_${e.type}`:""}.mp4`;return{media:t,src:this.embedController.embedFile(i),codec:St(this,En,Sn)[e.codec]}})),i=this._embed.video.renditions.filter((t=>St(this,En,bn).indexOf(t.size)<=St(this,En,bn).indexOf("fhd")&&"mp4"===t.container&&St(this,En,Tn).includes(t.codec)&&(!t.type||e.includes(t.type)))).sort(((e,t)=>St(this,En,bn).indexOf(t.size)-St(this,En,bn).indexOf(e.size)));if(i.length>0){let e=i[0],r=`${e.codec}_${e.size}${e.type&&"video"!=e.type?`_${e.type}`:""}.mp4`,s={media:void 0,src:this.embedController.embedFile(r),codec:St(this,En,Sn)[e.codec]};t.push(s)}return t}connectedCallback(){super.connectedCallback(),"scroll"===this.autoplay&&document.addEventListener("scroll",_t(this,En,yn).bind(this))}disconnectedCallback(){super.disconnectedCallback(),"scroll"===this.autoplay&&document.removeEventListener("scroll",_t(this,En,yn).bind(this)),this._metricsInstance?.demonitor()}set muted(e){this._videoElement?this._videoElement.muted=e:this._queue.push((()=>this._videoElement.muted=e))}get muted(){return this._videoElement?.muted||!1}get paused(){return this._videoElement?.paused||!0}get duration(){return new Promise(((e,t)=>{if(this._videoElement&&!isNaN(this._videoElement.duration))return e(this._videoElement.duration);let i=()=>{this._videoElement?.addEventListener("loadedmetadata",(()=>{this._videoElement&&e(this._videoElement.duration)})),this._videoElement?.addEventListener("error",(e=>{t(new Error("Failed to load video metadata."))}))};this._videoElement?i():this.addEventListener("mave:video_element_ready",(()=>{i()}))}))}set currentTime(e){this._videoElement?this._videoElement.currentTime=e:this._queue.push((()=>this._videoElement.currentTime=e))}get currentTime(){return this._videoElement?this._videoElement?.currentTime:0}play(){this._videoElement?_t(this,En,_n).call(this):this._queue.push((()=>_t(this,En,_n).call(this)))}pause(){this._videoElement?this._videoElement.pause():this._queue.push((()=>this._videoElement?.pause()))}render(){return B`
      ${this.embedController.render({complete:e=>{if(this._embed=e,e)return B`
            <video
              @click=${_t(this,En,Ln)}
              preload="metadata"
              style=${qe(this._failedPlay||"off"===this.autoplay?"cursor: pointer":void 0)}
              muted
              playsinline
              poster=${qe(this._failedPlay?this.poster:void 0)}
              ${Dn(_t(this,En,wn))}
              ?autoplay=${"always"===this.autoplay}
              ?loop=${this.loop||!0}
            >
              ${this.sources.map((e=>B`
                  <source
                    media=${qe(e.media?`(min-width: ${e.media}px)`:void 0)}
                    src=${e.src}
                    type=${`video/mp4; ${e.codec}`}
                  />
                `))}
            </video>
          `}})}
    `}};En=new WeakSet,yn=function(){let{height:e,top:t,bottom:i}=this.getBoundingClientRect(),r=window.innerHeight;if(this._videoElement){this._videoElement.duration||this._videoElement.load();let s=0;if(t<r&&i>0){s=(r-t)/(e+r)*this._videoElement.duration}s>=0&&s<=this._videoElement.duration&&(this._videoElement.currentTime=s)}},bn=function(){return["sd","hd","fhd","qhd","uhd"]},Tn=function(){let e=navigator.userAgent,t=/Edg/.test(e)&&/Mac OS/.test(e),i=/Safari/.test(e)&&!/Chrome/.test(e),r=/Mac OS/.test(e),s=/iPhone|iPad/.test(e);return r&&(i||t)||s?["hevc","h264"]:["av1","h264"]},Sn=function(){return{av1:"av01.0.08M.08.0.110.01.01.01.0,opus",hevc:"hevc.01.00.78,mp4a.40.2",h264:"avc1.64.00.28,mp4a.40.2"}},An=function(){return[{size:"qhd",media:1280},{size:"fhd",media:1080},{size:"hd",media:720},{size:"sd",media:640}]},_n=function(){this._metricsInstance?.monitor(),this._videoElement&&(this._videoElement.muted=!0,this._videoElement.play().catch((e=>{this._failedPlay=!0})))},wn=function(e){if(this._videoElement||(this._videoElement=e,this.dispatchEvent(new CustomEvent("mave:video_element_ready",{detail:this._videoElement,bubbles:!0,composed:!0}))),this._intersectionObserver.observe(this._videoElement),this._videoElement&&this._embed){xn.forEach((e=>{this._videoElement?.addEventListener(e,(t=>{!this._canPlay&&"scroll"===this.autoplay&&"canplay"===e&&(this._canPlay=!0,_t(this,En,yn).call(this)),this.dispatchEvent(new CustomEvent(e,{detail:t,bubbles:!0,composed:!0}))}))}));let e={component:"clip",video_id:this._embed.video.id,space_id:this._embed.space_id};Un.Metrics.config={socketPath:E.metrics.socket,apiKey:this._embed.metrics_key},E.metrics.enabled&&(this._metricsInstance=new Un.Metrics(this._videoElement,this.embed,e))}this._queue.length&&(this._queue.forEach((e=>e())),this._queue=[])},kn=function(e){for(let{isIntersecting:t}of e){if("always"===this.autoplay)return;!t||"lazy"!==this.autoplay&&"true"!==this.autoplay?this._videoElement?.paused||this._videoElement?.pause():this._videoElement?.paused&&_t(this,En,_n).call(this)}},Ln=function(){("off"===this.autoplay||this._failedPlay)&&(this._videoElement?.paused?_t(this,En,_n).call(this):this._videoElement?.pause())},Nn.styles=oe`
    :host {
      display: block;
      position: relative;
      overflow: hidden;
    }

    video {
      all: initial;
      display: block;
      width: 100%;
      height: 100%;
      object-fit: cover;
    }
  `,bt([rt()],Nn.prototype,"embed",1),bt([rt()],Nn.prototype,"autoplay",2),bt([rt()],Nn.prototype,"quality",2),bt([rt()],Nn.prototype,"fallback",2),bt([rt()],Nn.prototype,"loop",1),bt([rt()],Nn.prototype,"poster",1),bt([rt()],Nn.prototype,"token",1),bt([st()],Nn.prototype,"_failedPlay",2),window&&window.customElements&&(window.customElements.get("mave-clip")||window.customElements.define("mave-clip",Nn));var $n=class extends _e{constructor(){super(...arguments),this.EVENT_TYPES={CLICK:"user_click"}}get embed(){return this._embed}set embed(e){this._embed=e}get embedId(){return this._embed?.substring(5,this._embed?.length)}get spaceId(){return this.embed?.substring(0,5)}get cdn_root(){return E.cdn.endpoint.replace("${this.spaceId}",this.spaceId)}get _stylesheets(){let e=document.querySelectorAll('style, link[rel="stylesheet"]');return B`${Array.from(e).map((e=>e.cloneNode(!0)))}`}durationToTime(e){let t=Math.floor(e),i=Math.floor(t/3600),r=Math.floor(t%3600/60),s=t%60;return i>0?`${i}:${r.toString().padStart(2,"0")}:${s.toString().padStart(2,"0")}`:`${r}:${s.toString().padStart(2,"0")}`}emit(e,t){this.dispatchEvent(new CustomEvent(`mave:${e}`,{detail:{...t,eventType:e}})),this.dispatchEvent(new CustomEvent("mave:*",{detail:{...t,eventType:e}}))}};bt([rt({type:String})],$n.prototype,"embed",1);var Fn,Bn,Hn,Gn,jn,Vn=class extends $n{constructor(){super(...arguments),At(this,Fn),this.embedController=new On(this)}get embed(){return this._embed}set embed(e){this._embed!==e&&(this._embed=e,this.requestUpdate("embed"),this.embedController.embed=this.embed)}get _slottedChildren(){return this.shadowRoot?.querySelector("slot")?.assignedElements({flatten:!0})||[]}render(){return B`
      ${this.embedController.render({pending:this.renderPending,complete:e=>{if(this._data=e,!e)return;let t=this._slottedChildren.map((e=>{function t(){let t;return t="TEMPLATE"===e.nodeName?e.content.cloneNode(!0):e.cloneNode(!0),t}if("mave-files-video"==e.getAttribute("name")){let e=t(),i=new Date(this._data.created_at);i&&_t(this,Fn,Bn).call(this,e,'[slot="date"]',i.toLocaleDateString().replaceAll("/","-"));let r=this._data.video.duration;r&&_t(this,Fn,Bn).call(this,e,'[slot="duration"]',this.durationToTime(r));let s=this._data.video.filetype;s&&_t(this,Fn,Bn).call(this,e,'[slot="filetype"]',s);let n=this._data.video.size,a=n/1e6;n&&_t(this,Fn,Bn).call(this,e,'[slot="size"]',`${a.toFixed(1)} MB`);let o=_t(this,Fn,jn).call(this,`${this.cdn_root}/${this.embedId}/h264_hd.mp4`,`${this._data.name}.mp4`);return o.setAttribute("aria-label","Download video"),o.appendChild(e),B`${o}`}if(this._data.video.audio&&"mave-files-audio"==e.getAttribute("name")){let e=t();_t(this,Fn,Bn).call(this,e,'[slot="filetype"]',"mp3");let i=_t(this,Fn,jn).call(this,`${this.cdn_root}/${this.embedId}/audio.mp3`,`${this._data.name}.mp3`);return i.setAttribute("aria-label","Download audio"),i.appendChild(e),B`${i}`}let i=this._data.subtitles.find((e=>e.language==this._data.video.language));if(i&&"mave-files-subtitles"==e.getAttribute("name")){let e=t();_t(this,Fn,Bn).call(this,e,'[slot="filetype"]',"vtt");let r=_t(this,Fn,jn).call(this,i.path,`${this._data.name}.vtt`);return r.setAttribute("aria-label","Download subtitles"),r.appendChild(e),B`${r}`}}));return B`${this._stylesheets} ${t}`}})}
    `}renderPending(){return B`<slot style="display: none"></slot>`}};Fn=new WeakSet,Bn=function(e,t,i){let r=e.querySelector(t);r&&(r.textContent=i,r.removeAttribute("slot"))},Hn=function(e,t){let i=window.URL.createObjectURL(e),r=document.createElement("a");r.style.display="none",r.href=i,r.download=t,this.appendChild(r),r.click(),window.URL.revokeObjectURL(i),this.removeChild(r)},Gn=function(e,t){return fetch(e).then((e=>{if(!e.ok)throw new Error("Network response was not ok");return e.blob()})).then((e=>_t(this,Fn,Hn).call(this,e,t))).catch((e=>console.error("Something went wrong:",e)))},jn=function(e,t){let i=document.createElement("a");i.classList.add("link"),i.setAttribute("href",e),i.setAttribute("download",t),i.setAttribute("target","new");let r=!1;return i.addEventListener("click",(s=>{s.preventDefault(),!r&&(r=!0,i.style.cursor="wait",i.style.opacity="0.5",_t(this,Fn,Gn).call(this,e,t).then((()=>{r=!1,i.style.cursor="pointer",i.style.opacity="1"})))})),i},Vn.styles=oe`
    :host {
      display: block;
      --link-color: #006fc6;
      --link-decoration: underline;
      --link-decoration-thickness: 1px;
      --link-decoration-offset: 1px;
      --link-cursor: pointer;
    }

    a {
      text-decoration: var(--link-decoration);
      text-decoration-thickness: var(--link-decoration-thickness);
      text-underline-offset: var(--link-decoration-thickness);
      color: var(--link-color);
      cursor: var(--link-cursor);
    }
  `,bt([rt({type:String})],Vn.prototype,"embed",1),window&&window.customElements&&(window.customElements.get("mave-files")||window.customElements.define("mave-files",Vn));var Kn=class extends $n{get poster(){return`${this.cdn_root}/${this.embedId}/poster.webp`}render(){return B`<img src=${this.poster} />`}};Kn.styles=oe`
    :host {
      display: block;
    }

    img {
      width: 100%;
      max-height: 100vh;
    }
  `,window&&window.customElements&&(window.customElements.get("mave-img")||window.customElements.define("mave-img",Kn));var Wn=["default","synthwave","dolphin"],qn=class e{constructor(){this.themes=[]}static async get(t,i,r=!0){if(e.instance||(e.instance=new e),e.instance.themes.find((e=>e.name===t)))return Promise.resolve(e.instance);e.instance.themes.push({name:t});try{if(r&&!Wn.includes(t)){let e=document.createElement("link");e.rel="stylesheet",e.href=`${i}/${t}.css`,document.head.appendChild(e)}if(i&&!Wn.includes(t)){let{build:e}=await import(`${i}/${t}.js`);e(t,_e,B,oe)}else{let e=`./${_i()}themes/${t}.js`,{build:i}=await import(e);i(t,_e,B,oe)}}catch(e){console.log("[mave-player]: theme not loaded",e)}return Promise.resolve(e.instance)}},Yn={MEDIA_PLAY_REQUEST:"mediaplayrequest",MEDIA_PAUSE_REQUEST:"mediapauserequest",MEDIA_MUTE_REQUEST:"mediamuterequest",MEDIA_UNMUTE_REQUEST:"mediaunmuterequest",MEDIA_VOLUME_REQUEST:"mediavolumerequest",MEDIA_SEEK_REQUEST:"mediaseekrequest",MEDIA_AIRPLAY_REQUEST:"mediaairplayrequest",MEDIA_ENTER_FULLSCREEN_REQUEST:"mediaenterfullscreenrequest",MEDIA_EXIT_FULLSCREEN_REQUEST:"mediaexitfullscreenrequest",MEDIA_PREVIEW_REQUEST:"mediapreviewrequest",MEDIA_ENTER_PIP_REQUEST:"mediaenterpiprequest",MEDIA_EXIT_PIP_REQUEST:"mediaexitpiprequest",MEDIA_ENTER_CAST_REQUEST:"mediaentercastrequest",MEDIA_EXIT_CAST_REQUEST:"mediaexitcastrequest",MEDIA_SHOW_TEXT_TRACKS_REQUEST:"mediashowtexttracksrequest",MEDIA_HIDE_TEXT_TRACKS_REQUEST:"mediahidetexttracksrequest",MEDIA_SHOW_SUBTITLES_REQUEST:"mediashowsubtitlesrequest",MEDIA_DISABLE_SUBTITLES_REQUEST:"mediadisablesubtitlesrequest",MEDIA_TOGGLE_SUBTITLES_REQUEST:"mediatogglesubtitlesrequest",MEDIA_PLAYBACK_RATE_REQUEST:"mediaplaybackraterequest",MEDIA_RENDITION_REQUEST:"mediarenditionrequest",MEDIA_AUDIO_TRACK_REQUEST:"mediaaudiotrackrequest",MEDIA_SEEK_TO_LIVE_REQUEST:"mediaseektoliverequest",REGISTER_MEDIA_STATE_RECEIVER:"registermediastatereceiver",UNREGISTER_MEDIA_STATE_RECEIVER:"unregistermediastatereceiver"},zn="mediachromeattributes",Xn="mediacontroller",Qn={MEDIA_AIRPLAY_UNAVAILABLE:"mediaAirplayUnavailable",MEDIA_FULLSCREEN_UNAVAILABLE:"mediaFullscreenUnavailable",MEDIA_PIP_UNAVAILABLE:"mediaPipUnavailable",MEDIA_CAST_UNAVAILABLE:"mediaCastUnavailable",MEDIA_RENDITION_UNAVAILABLE:"mediaRenditionUnavailable",MEDIA_AUDIO_TRACK_UNAVAILABLE:"mediaAudioTrackUnavailable",MEDIA_PAUSED:"mediaPaused",MEDIA_HAS_PLAYED:"mediaHasPlayed",MEDIA_ENDED:"mediaEnded",MEDIA_MUTED:"mediaMuted",MEDIA_VOLUME_LEVEL:"mediaVolumeLevel",MEDIA_VOLUME:"mediaVolume",MEDIA_VOLUME_UNAVAILABLE:"mediaVolumeUnavailable",MEDIA_IS_PIP:"mediaIsPip",MEDIA_IS_CASTING:"mediaIsCasting",MEDIA_IS_AIRPLAYING:"mediaIsAirplaying",MEDIA_SUBTITLES_LIST:"mediaSubtitlesList",MEDIA_SUBTITLES_SHOWING:"mediaSubtitlesShowing",MEDIA_IS_FULLSCREEN:"mediaIsFullscreen",MEDIA_PLAYBACK_RATE:"mediaPlaybackRate",MEDIA_CURRENT_TIME:"mediaCurrentTime",MEDIA_DURATION:"mediaDuration",MEDIA_SEEKABLE:"mediaSeekable",MEDIA_PREVIEW_TIME:"mediaPreviewTime",MEDIA_PREVIEW_IMAGE:"mediaPreviewImage",MEDIA_PREVIEW_COORDS:"mediaPreviewCoords",MEDIA_PREVIEW_CHAPTER:"mediaPreviewChapter",MEDIA_LOADING:"mediaLoading",MEDIA_BUFFERED:"mediaBuffered",MEDIA_STREAM_TYPE:"mediaStreamType",MEDIA_TARGET_LIVE_WINDOW:"mediaTargetLiveWindow",MEDIA_TIME_IS_LIVE:"mediaTimeIsLive",MEDIA_RENDITION_LIST:"mediaRenditionList",MEDIA_RENDITION_SELECTED:"mediaRenditionSelected",MEDIA_AUDIO_TRACK_LIST:"mediaAudioTrackList",MEDIA_AUDIO_TRACK_ENABLED:"mediaAudioTrackEnabled",MEDIA_CHAPTERS_CUES:"mediaChaptersCues"},Zn=Object.entries(Qn),Jn=Zn.reduce(((e,[t,i])=>(e[t]=`${i.toLowerCase()}`,e)),{}),ea=Zn.reduce(((e,[t,i])=>(e[t]=`${i.toLowerCase()}`,e)),{USER_INACTIVE:"userinactivechange",BREAKPOINTS_CHANGE:"breakpointchange",BREAKPOINTS_COMPUTED:"breakpointscomputed"});Object.entries(ea).reduce(((e,[t,i])=>{let r=Jn[t];return r&&(e[i]=r),e}),{userinactivechange:"userinactive"});var ta=Object.entries(Jn).reduce(((e,[t,i])=>{let r=ea[t];return r&&(e[i]=r),e}),{userinactive:"userinactivechange"}),ia={SUBTITLES:"subtitles",CAPTIONS:"captions",CHAPTERS:"chapters",METADATA:"metadata"},ra="disabled",sa="showing",na="mouse",aa="touch",oa="unavailable",la="unsupported",ha={LIVE:"live",ON_DEMAND:"on-demand",UNKNOWN:"unknown"},da=()=>"audio player",ua=()=>"video player",ca=()=>"volume",fa=()=>"seek",pa=()=>"closed captions",ma=({playbackRate:e=1}={})=>`current playback rate ${e}`,ga=()=>"playback time",va=()=>"media loading",Ea=()=>"play",ya=()=>"pause",ba=()=>"mute",Ta=()=>"unmute",Sa=()=>"start airplay",Aa=()=>"stop airplay",_a=()=>"start casting",wa=()=>"stop casting",ka=()=>"enter fullscreen mode",La=()=>"exit fullscreen mode",Ra=()=>"enter picture in picture mode",Ia=()=>"exit picture in picture mode",Ca=({seekOffset:e=30}={})=>`seek forward ${e} seconds`,Da=({seekOffset:e=30}={})=>`seek back ${e} seconds`,xa=()=>"seek to live",Ma=()=>"playing live";function Pa(e){if(e){let{id:t,width:i,height:r}=e;return[t,i,r].filter((e=>null!=e)).join(":")}}function Oa(e){if(e){let{id:t,kind:i,language:r,label:s}=e;return[t,i,r,s].filter((e=>null!=e)).join(":")}}function Ua(e,t=!1){return e.split("_").map((function(e,i){return(i||t?e[0].toUpperCase():e[0].toLowerCase())+e.slice(1).toLowerCase()})).join("")}var Na=e=>new Promise((t=>setTimeout(t,e))),$a=[{singular:"hour",plural:"hours"},{singular:"minute",plural:"minutes"},{singular:"second",plural:"seconds"}],Fa=e=>{if(!function(e){return"number"==typeof e&&!Number.isNaN(e)&&Number.isFinite(e)}(e))return"";let t=Math.abs(e),i=t!==e,r=new Date(0,0,0,0,0,t,0);return`${[r.getHours(),r.getMinutes(),r.getSeconds()].map(((e,t)=>e&&((e,t)=>`${e} ${1===e?$a[t].singular:$a[t].plural}`)(e,t))).filter((e=>e)).join(", ")}${i?" remaining":""}`};function Ba(e,t){let i=!1;e<0&&(i=!0,e=0-e),e=e<0?0:e;let r=Math.floor(e%60),s=Math.floor(e/60%60),n=Math.floor(e/3600),a=Math.floor(t/60%60),o=Math.floor(t/3600);return(isNaN(e)||e===1/0)&&(n=s=r="0"),n=n>0||o>0?n+":":"",s=((n||a>=10)&&s<10?"0"+s:s)+":",r=r<10?"0"+r:r,(i?"-":"")+n+s+r}var Ha=(e,t,i=".value")=>{let r=e.querySelector(i);r&&(r.textContent=t)},Ga=(e,t)=>((e,t)=>{let i=`slot[name="${t}"]`,r=e.shadowRoot.querySelector(i);return r?r.children:[]})(e,t)[0],ja=(e,t)=>!(!e||!t)&&(!!e.contains(t)||ja(e,t.getRootNode().host)),Va=(e,t)=>{if(!e)return null;return e.closest(t)||Va(e.getRootNode().host,t)};function Ka(e=document){var t;let i=e?.activeElement;return i?null!=(t=Ka(i.shadowRoot))?t:i:null}function Wa(e,t){return Math.sqrt(Math.pow(t.x-e.x,2)+Math.pow(t.y-e.y,2))}function qa(e,t){let i=function(e,t){var i;let r;for(r of e.querySelectorAll("style")){let e;try{e=null==(i=r.sheet)?void 0:i.cssRules}catch{continue}for(let i of e??[])if(t(i.selectorText))return i}}(e,(e=>e===t));return i||Ya(e,t)}function Ya(e,t){var i,r;let s=null!=(i=e.querySelectorAll("style"))?i:[],n=s?.[s.length-1];return n?.sheet?(n?.sheet.insertRule(`${t}{}`,n.sheet.cssRules.length),null==(r=n.sheet.cssRules)?void 0:r[n.sheet.cssRules.length-1]):(console.warn("Media Chrome: No style sheet found on style tag of",e),{style:{setProperty:()=>{},removeProperty:()=>"",getPropertyValue:()=>""}})}function za(e,t,i=Number.NaN){let r=e.getAttribute(t);return null!=r?+r:i}function Xa(e,t,i){let r=+i;null==i||Number.isNaN(r)?e.hasAttribute(t)&&e.removeAttribute(t):za(e,t,void 0)!==r&&e.setAttribute(t,`${r}`)}function Qa(e,t){return e.hasAttribute(t)}function Za(e,t,i){null!=i?Qa(e,t)!=i&&e.toggleAttribute(t,i):e.hasAttribute(t)&&e.removeAttribute(t)}function Ja(e,t,i=null){var r;return null!=(r=e.getAttribute(t))?r:i}function eo(e,t,i){if(null==i)return void(e.hasAttribute(t)&&e.removeAttribute(t));let r=`${i}`;Ja(e,t,void 0)!==r&&e.setAttribute(t,r)}var to,io,ro,so,no=class{addEventListener(){}removeEventListener(){}dispatchEvent(){return!0}},ao={createElement:function(){return new oo.HTMLElement},createElementNS:function(){return new oo.HTMLElement},addEventListener(){},removeEventListener(){}},oo={ResizeObserver:class{observe(){}unobserve(){}disconnect(){}},document:ao,HTMLElement:class extends no{},DocumentFragment:class extends no{},customElements:{get:function(){},define:function(){},whenDefined:function(){}},CustomEvent:function(){},getComputedStyle:function(){},navigator:{languages:[],get userAgent(){return""}},matchMedia:e=>({matches:!1,media:e})},lo=typeof window>"u"||typeof window.customElements>"u",ho=Object.keys(oo).every((e=>e in globalThis)),uo=lo&&!ho?oo:globalThis,co=lo&&!ho?ao:globalThis.document,fo=Object.defineProperty,po=(e,t,i)=>(((e,t,i)=>{t in e?fo(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i})(e,t+"",i),i),mo=(e,t,i)=>{if(!t.has(e))throw TypeError("Cannot "+i)},go=(e,t,i)=>(mo(e,t,"read from private field"),i?i.call(e):t.get(e)),vo=(e,t,i)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,i)},Eo=(e,t,i,r)=>(mo(e,t,"write to private field"),t.set(e,i),i),yo=co.createElement("template");yo.innerHTML="\n<style>\n  :host {\n    font: var(--media-font,\n      var(--media-font-weight, bold)\n      var(--media-font-size, 14px) /\n      var(--media-text-content-height, var(--media-control-height, 24px))\n      var(--media-font-family, helvetica neue, segoe ui, roboto, arial, sans-serif));\n    color: var(--media-text-color, var(--media-primary-color, rgb(238 238 238)));\n    background: var(--media-control-background, var(--media-secondary-color, rgb(20 20 30 / .7)));\n    padding: var(--media-button-padding, var(--media-control-padding, 10px));\n    justify-content: var(--media-button-justify-content, center);\n    display: inline-flex;\n    align-items: center;\n    vertical-align: middle;\n    box-sizing: border-box;\n    transition: background .15s linear;\n    pointer-events: auto;\n    cursor: pointer;\n    -webkit-tap-highlight-color: transparent;\n  }\n\n  \n  :host(:focus-visible) {\n    box-shadow: inset 0 0 0 2px rgb(27 127 204 / .9);\n    outline: 0;\n  }\n  \n  :host(:where(:focus)) {\n    box-shadow: none;\n    outline: 0;\n  }\n\n  :host(:hover) {\n    background: var(--media-control-hover-background, rgba(50 50 70 / .7));\n  }\n\n  svg, img, ::slotted(svg), ::slotted(img) {\n    width: var(--media-button-icon-width);\n    height: var(--media-button-icon-height, var(--media-control-height, 24px));\n    transform: var(--media-button-icon-transform);\n    transition: var(--media-button-icon-transition);\n    fill: var(--media-icon-color, var(--media-primary-color, rgb(238 238 238)));\n    vertical-align: middle;\n    max-width: 100%;\n    max-height: 100%;\n    min-width: 100%;\n  }\n</style>\n";var bo=class extends uo.HTMLElement{constructor(e={}){if(super(),vo(this,to,void 0),po(this,"preventClick",!1),vo(this,io,(e=>{this.preventClick||this.handleClick(e)})),vo(this,ro,(e=>{let{key:t}=e;this.keysUsed.includes(t)?this.preventClick||this.handleClick(e):this.removeEventListener("keyup",go(this,ro))})),vo(this,so,(e=>{let{metaKey:t,altKey:i,key:r}=e;t||i||!this.keysUsed.includes(r)?this.removeEventListener("keyup",go(this,ro)):this.addEventListener("keyup",go(this,ro),{once:!0})})),!this.shadowRoot){this.attachShadow({mode:"open"});let t=yo.content.cloneNode(!0);this.nativeEl=t;let i=e.slotTemplate;i||(i=co.createElement("template"),i.innerHTML=`<slot>${e.defaultContent||""}</slot>`),this.nativeEl.appendChild(i.content.cloneNode(!0)),this.shadowRoot.appendChild(t)}}static get observedAttributes(){return["disabled",Xn]}enable(){this.addEventListener("click",go(this,io)),this.addEventListener("keydown",go(this,so)),this.tabIndex=0}disable(){this.removeEventListener("click",go(this,io)),this.removeEventListener("keydown",go(this,so)),this.removeEventListener("keyup",go(this,ro)),this.tabIndex=-1}attributeChangedCallback(e,t,i){var r,s,n,a,o;e===Xn?(t&&(null==(s=null==(r=go(this,to))?void 0:r.unassociateElement)||s.call(r,this),Eo(this,to,null)),i&&this.isConnected&&(Eo(this,to,null==(n=this.getRootNode())?void 0:n.getElementById(i)),null==(o=null==(a=go(this,to))?void 0:a.associateElement)||o.call(a,this))):"disabled"===e&&i!==t&&(null==i?this.enable():this.disable())}connectedCallback(){var e,t,i;let{style:r}=qa(this.shadowRoot,":host");r.setProperty("display",`var(--media-control-display, var(--${this.localName}-display, inline-flex))`),this.hasAttribute("disabled")||this.enable(),this.setAttribute("role","button");let s=this.getAttribute(Xn);s&&(Eo(this,to,null==(e=this.getRootNode())?void 0:e.getElementById(s)),null==(i=null==(t=go(this,to))?void 0:t.associateElement)||i.call(t,this))}disconnectedCallback(){var e,t;this.disable(),null==(t=null==(e=go(this,to))?void 0:e.unassociateElement)||t.call(e,this),Eo(this,to,null)}get keysUsed(){return["Enter"," "]}handleClick(e){}};to=new WeakMap,io=new WeakMap,ro=new WeakMap,so=new WeakMap,uo.customElements.get("media-chrome-button")||uo.customElements.define("media-chrome-button",bo);var To='<svg aria-hidden="true" viewBox="0 0 26 24">\n  <path d="M22.13 3H3.87a.87.87 0 0 0-.87.87v13.26a.87.87 0 0 0 .87.87h3.4L9 16H5V5h16v11h-4l1.72 2h3.4a.87.87 0 0 0 .87-.87V3.87a.87.87 0 0 0-.86-.87Zm-8.75 11.44a.5.5 0 0 0-.76 0l-4.91 5.73a.5.5 0 0 0 .38.83h9.82a.501.501 0 0 0 .38-.83l-4.91-5.73Z"/>\n</svg>\n',So=co.createElement("template");So.innerHTML=`\n  <style>\n  :host([${Jn.MEDIA_IS_AIRPLAYING}]) slot:not([name=exit]):not([name=icon]) {\n    display: none !important;\n  }\n\n  \n  :host(:not([${Jn.MEDIA_IS_AIRPLAYING}])) slot:not([name=enter]):not([name=icon]) {\n    display: none !important;\n  }\n  </style>\n\n  <slot name="icon">\n    <slot name="enter">${To}</slot>\n    <slot name="exit">${To}</slot>\n  </slot>\n`;var Ao=e=>{let t=e.mediaIsAirplaying?Aa():Sa();e.setAttribute("aria-label",t)};uo.customElements.get("media-airplay-button")||uo.customElements.define("media-airplay-button",class extends bo{static get observedAttributes(){return[...super.observedAttributes,Jn.MEDIA_IS_AIRPLAYING,Jn.MEDIA_AIRPLAY_UNAVAILABLE]}constructor(e={}){super({slotTemplate:So,...e})}connectedCallback(){super.connectedCallback(),Ao(this)}attributeChangedCallback(e,t,i){super.attributeChangedCallback(e,t,i),e===Jn.MEDIA_IS_AIRPLAYING&&Ao(this)}get mediaIsAirplaying(){return Qa(this,Jn.MEDIA_IS_AIRPLAYING)}set mediaIsAirplaying(e){Za(this,Jn.MEDIA_IS_AIRPLAYING,e)}get mediaAirplayUnavailable(){return Ja(this,Jn.MEDIA_AIRPLAY_UNAVAILABLE)}set mediaAirplayUnavailable(e){eo(this,Jn.MEDIA_AIRPLAY_UNAVAILABLE,e)}handleClick(){let e=new uo.CustomEvent(Yn.MEDIA_AIRPLAY_REQUEST,{composed:!0,bubbles:!0});this.dispatchEvent(e)}});var _o=co.createElement("template");_o.innerHTML=`\n  <style>\n  :host([${Jn.MEDIA_IS_CASTING}]) slot:not([name=exit]):not([name=icon]) {\n    display: none !important;\n  }\n\n  \n  :host(:not([${Jn.MEDIA_IS_CASTING}])) slot:not([name=enter]):not([name=icon]) {\n    display: none !important;\n  }\n  </style>\n\n  <slot name="icon">\n    <slot name="enter"><svg aria-hidden="true" viewBox="0 0 24 24"><g><path class="cast_caf_icon_arch0" d="M1,18 L1,21 L4,21 C4,19.3 2.66,18 1,18 L1,18 Z"/><path class="cast_caf_icon_arch1" d="M1,14 L1,16 C3.76,16 6,18.2 6,21 L8,21 C8,17.13 4.87,14 1,14 L1,14 Z"/><path class="cast_caf_icon_arch2" d="M1,10 L1,12 C5.97,12 10,16.0 10,21 L12,21 C12,14.92 7.07,10 1,10 L1,10 Z"/><path class="cast_caf_icon_box" d="M21,3 L3,3 C1.9,3 1,3.9 1,5 L1,8 L3,8 L3,5 L21,5 L21,19 L14,19 L14,21 L21,21 C22.1,21 23,20.1 23,19 L23,5 C23,3.9 22.1,3 21,3 L21,3 Z"/></g></svg></slot>\n    <slot name="exit"><svg aria-hidden="true" viewBox="0 0 24 24"><g><path class="cast_caf_icon_arch0" d="M1,18 L1,21 L4,21 C4,19.3 2.66,18 1,18 L1,18 Z"/><path class="cast_caf_icon_arch1" d="M1,14 L1,16 C3.76,16 6,18.2 6,21 L8,21 C8,17.13 4.87,14 1,14 L1,14 Z"/><path class="cast_caf_icon_arch2" d="M1,10 L1,12 C5.97,12 10,16.0 10,21 L12,21 C12,14.92 7.07,10 1,10 L1,10 Z"/><path class="cast_caf_icon_box" d="M21,3 L3,3 C1.9,3 1,3.9 1,5 L1,8 L3,8 L3,5 L21,5 L21,19 L14,19 L14,21 L21,21 C22.1,21 23,20.1 23,19 L23,5 C23,3.9 22.1,3 21,3 L21,3 Z"/><path class="cast_caf_icon_boxfill" d="M5,7 L5,8.63 C8,8.6 13.37,14 13.37,17 L19,17 L19,7 Z"/></g></svg></slot>\n  </slot>\n`;var wo=e=>{let t=e.mediaIsCasting?wa():_a();e.setAttribute("aria-label",t)};uo.customElements.get("media-cast-button")||uo.customElements.define("media-cast-button",class extends bo{static get observedAttributes(){return[...super.observedAttributes,Jn.MEDIA_IS_CASTING,Jn.MEDIA_CAST_UNAVAILABLE]}constructor(e={}){super({slotTemplate:_o,...e})}connectedCallback(){super.connectedCallback(),wo(this)}attributeChangedCallback(e,t,i){super.attributeChangedCallback(e,t,i),e===Jn.MEDIA_IS_CASTING&&wo(this)}get mediaIsCasting(){return Qa(this,Jn.MEDIA_IS_CASTING)}set mediaIsCasting(e){Za(this,Jn.MEDIA_IS_CASTING,e)}get mediaCastUnavailable(){return Ja(this,Jn.MEDIA_CAST_UNAVAILABLE)}set mediaCastUnavailable(e){eo(this,Jn.MEDIA_CAST_UNAVAILABLE,e)}handleClick(){let e=this.mediaIsCasting?Yn.MEDIA_EXIT_CAST_REQUEST:Yn.MEDIA_ENTER_CAST_REQUEST;this.dispatchEvent(new uo.CustomEvent(e,{composed:!0,bubbles:!0}))}});var ko,Lo=(e,t,i)=>{if(!t.has(e))throw TypeError("Cannot "+i)},Ro=(e,t,i)=>(Lo(e,t,"read from private field"),i?i.call(e):t.get(e)),Io=(e,t,i,r)=>(Lo(e,t,"write to private field"),t.set(e,i),i),Co=co.createElement("template");Co.innerHTML="\n<style>\n  :host {\n    display: var(--media-control-display, var(--media-gesture-receiver-display, inline-block));\n    box-sizing: border-box;\n  }\n</style>\n";var Do=class extends uo.HTMLElement{constructor(e={}){if(super(),((e,t,i)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,i)})(this,ko,void 0),!this.shadowRoot){let t=this.attachShadow({mode:"open"}),i=Co.content.cloneNode(!0);this.nativeEl=i;let r=e.slotTemplate;r||(r=co.createElement("template"),r.innerHTML=`<slot>${e.defaultContent||""}</slot>`),this.nativeEl.appendChild(r.content.cloneNode(!0)),t.appendChild(i)}}static get observedAttributes(){return[Xn,Jn.MEDIA_PAUSED]}attributeChangedCallback(e,t,i){var r,s,n,a,o;e===Xn&&(t&&(null==(s=null==(r=Ro(this,ko))?void 0:r.unassociateElement)||s.call(r,this),Io(this,ko,null)),i&&this.isConnected&&(Io(this,ko,null==(n=this.getRootNode())?void 0:n.getElementById(i)),null==(o=null==(a=Ro(this,ko))?void 0:a.associateElement)||o.call(a,this)))}connectedCallback(){var e,t,i,r;this.tabIndex=-1,this.setAttribute("aria-hidden","true"),Io(this,ko,function(e){var t;let i=e.getAttribute(Xn);return i?null==(t=e.getRootNode())?void 0:t.getElementById(i):Va(e,"media-controller")}(this)),this.getAttribute(Xn)&&(null==(t=null==(e=Ro(this,ko))?void 0:e.associateElement)||t.call(e,this)),null==(i=Ro(this,ko))||i.addEventListener("pointerdown",this),null==(r=Ro(this,ko))||r.addEventListener("click",this)}disconnectedCallback(){var e,t,i,r;this.getAttribute(Xn)&&(null==(t=null==(e=Ro(this,ko))?void 0:e.unassociateElement)||t.call(e,this)),null==(i=Ro(this,ko))||i.removeEventListener("pointerdown",this),null==(r=Ro(this,ko))||r.removeEventListener("click",this),Io(this,ko,null)}handleEvent(e){var t;let i=null==(t=e.composedPath())?void 0:t[0];if(["video","media-controller"].includes(i?.localName))if("pointerdown"===e.type)this._pointerType=e.pointerType;else if("click"===e.type){let{clientX:t,clientY:i}=e,{left:r,top:s,width:n,height:a}=this.getBoundingClientRect(),o=t-r,l=i-s;if(o<0||l<0||o>n||l>a||0===n&&0===a)return;let{pointerType:h=this._pointerType}=e;if(this._pointerType=void 0,h===aa)return void this.handleTap(e);if(h===na)return void this.handleMouseClick(e)}}get mediaPaused(){return Qa(this,Jn.MEDIA_PAUSED)}set mediaPaused(e){Za(this,Jn.MEDIA_PAUSED,e)}handleTap(e){}handleMouseClick(e){let t=this.mediaPaused?Yn.MEDIA_PLAY_REQUEST:Yn.MEDIA_PAUSE_REQUEST;this.dispatchEvent(new uo.CustomEvent(t,{composed:!0,bubbles:!0}))}};ko=new WeakMap,uo.customElements.get("media-gesture-receiver")||uo.customElements.define("media-gesture-receiver",Do);var xo=new WeakMap,Mo=e=>{let t=xo.get(e);return t||xo.set(e,t=new Set),t},Po=new uo.ResizeObserver((e=>{for(let t of e)for(let e of Mo(t.target))e(t)}));function Oo(e,t){Mo(e).add(t),Po.observe(e)}function Uo(e,t){let i=Mo(e);i.delete(t),i.size||Po.unobserve(e)}var No,$o,Fo,Bo,Ho,Go,jo,Vo,Ko,Wo,qo,Yo,zo=Object.defineProperty,Xo=(e,t,i)=>(((e,t,i)=>{t in e?zo(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i})(e,t+"",i),i),Qo=(e,t,i)=>{if(!t.has(e))throw TypeError("Cannot "+i)},Zo=(e,t,i)=>(Qo(e,t,"read from private field"),t.get(e)),Jo=(e,t,i)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,i)},el=(e,t,i,r)=>(Qo(e,t,"write to private field"),t.set(e,i),i),tl=(e,t,i)=>(Qo(e,t,"access private method"),i),il={AUDIO:"audio",AUTOHIDE:"autohide",BREAKPOINTS:"breakpoints",GESTURES_DISABLED:"gesturesdisabled",KEYBOARD_CONTROL:"keyboardcontrol",NO_AUTOHIDE:"noautohide",USER_INACTIVE:"userinactive"},rl=co.createElement("template");rl.innerHTML=`\n  <style>\n    \n    :host([${Jn.MEDIA_IS_FULLSCREEN}]) ::slotted([slot=media]) {\n      outline: none;\n    }\n\n    :host {\n      box-sizing: border-box;\n      position: relative;\n      display: inline-block;\n      line-height: 0;\n      background-color: var(--media-background-color, #000);\n    }\n\n    :host(:not([${il.AUDIO}])) [part~=layer]:not([part~=media-layer]) {\n      position: absolute;\n      top: 0;\n      left: 0;\n      bottom: 0;\n      right: 0;\n      display: flex;\n      flex-flow: column nowrap;\n      align-items: start;\n      pointer-events: none;\n      background: none;\n    }\n\n    slot[name=media] {\n      display: var(--media-slot-display, contents);\n    }\n\n    \n    :host([${il.AUDIO}]) slot[name=media] {\n      display: var(--media-slot-display, none);\n    }\n\n    \n    :host([${il.AUDIO}]) [part~=layer][part~=gesture-layer] {\n      height: 0;\n      display: block;\n    }\n\n    \n    :host(:not([${il.AUDIO}])[${il.GESTURES_DISABLED}]) ::slotted([slot=gestures-chrome]),\n    :host(:not([${il.AUDIO}])[${il.GESTURES_DISABLED}]) media-gesture-receiver[slot=gestures-chrome] {\n      display: none;\n    }\n\n    \n    ::slotted(:not([slot=media]):not([slot=poster]):not(media-loading-indicator):not([hidden])) {\n      pointer-events: auto;\n    }\n\n    :host(:not([${il.AUDIO}])) *[part~=layer][part~=centered-layer] {\n      align-items: center;\n      justify-content: center;\n    }\n\n    :host(:not([${il.AUDIO}])) ::slotted(media-gesture-receiver[slot=gestures-chrome]),\n    :host(:not([${il.AUDIO}])) media-gesture-receiver[slot=gestures-chrome] {\n      align-self: stretch;\n      flex-grow: 1;\n    }\n\n    slot[name=middle-chrome] {\n      display: inline;\n      flex-grow: 1;\n      pointer-events: none;\n      background: none;\n    }\n\n    \n    ::slotted([slot=media]),\n    ::slotted([slot=poster]) {\n      width: 100%;\n      height: 100%;\n    }\n\n    \n    :host(:not([${il.AUDIO}])) .spacer {\n      flex-grow: 1;\n    }\n\n    \n    :host(:-webkit-full-screen) {\n      \n      width: 100% !important;\n      height: 100% !important;\n    }\n\n    \n    ::slotted(:not([slot=media]):not([slot=poster]):not([${il.NO_AUTOHIDE}]):not([hidden])) {\n      opacity: 1;\n      transition: opacity 0.25s;\n    }\n\n    \n    :host([${il.USER_INACTIVE}]:not([${Jn.MEDIA_PAUSED}]):not([${Jn.MEDIA_IS_AIRPLAYING}]):not([${Jn.MEDIA_IS_CASTING}]):not([${il.AUDIO}])) ::slotted(:not([slot=media]):not([slot=poster]):not([${il.NO_AUTOHIDE}])) {\n      opacity: 0;\n      transition: opacity 1s;\n    }\n\n    :host([${il.USER_INACTIVE}]:not([${Jn.MEDIA_PAUSED}]):not([${Jn.MEDIA_IS_CASTING}]):not([${il.AUDIO}])) ::slotted([slot=media]) {\n      cursor: none;\n    }\n\n    ::slotted(media-control-bar)  {\n      align-self: stretch;\n    }\n\n    \n    :host(:not([${il.AUDIO}])[${Jn.MEDIA_HAS_PLAYED}]) slot[name=poster] {\n      display: none;\n    }\n\n    ::slotted([role="menu"]) {\n      align-self: end;\n    }\n\n    ::slotted([role="dialog"]) {\n      align-self: center;\n    }\n  </style>\n\n  <slot name="media" part="layer media-layer"></slot>\n  <slot name="poster" part="layer poster-layer"></slot>\n  <slot name="gestures-chrome" part="layer gesture-layer">\n    <media-gesture-receiver slot="gestures-chrome"></media-gesture-receiver>\n  </slot>\n  <span part="layer vertical-layer">\n    <slot name="top-chrome" part="top chrome"></slot>\n    <slot name="middle-chrome" part="middle chrome"></slot>\n    <slot name="centered-chrome" part="layer centered-layer center centered chrome"></slot>\n    \n    <slot part="bottom chrome"></slot>\n  </span>\n`;var sl=Object.values(Jn),nl="sm:384 md:576 lg:768 xl:960";function al(e){!function(e,t){var i;if(!e.isConnected)return;let r=null!=(i=e.getAttribute(il.BREAKPOINTS))?i:nl,s=function(e){let t=e.split(/\s+/);return Object.fromEntries(t.map((e=>e.split(":"))))}(r),n=function(e,t){return Object.keys(e).filter((i=>t>=e[i]))}(s,t),a=!1;if(Object.keys(s).forEach((t=>{n.includes(t)?e.hasAttribute(`breakpoint${t}`)||(e.setAttribute(`breakpoint${t}`,""),a=!0):e.hasAttribute(`breakpoint${t}`)&&(e.removeAttribute(`breakpoint${t}`),a=!0)})),a){let t=new CustomEvent(ea.BREAKPOINTS_CHANGE,{detail:n});e.dispatchEvent(t)}}(e.target,e.contentRect.width)}var ol=class extends uo.HTMLElement{constructor(){super(),Jo(this,Fo),Jo(this,Ho),Jo(this,jo),Jo(this,Ko),Jo(this,qo),Jo(this,No,0),Jo(this,$o,void 0),Xo(this,"breakpointsComputed",!1),this.shadowRoot||(this.attachShadow({mode:"open"}),this.shadowRoot.appendChild(rl.content.cloneNode(!0)));new MutationObserver((e=>{let t=this.media;for(let i of e)"childList"===i.type&&(i.removedNodes.forEach((e=>{if("media"==e.slot&&i.target==this){let r=i.previousSibling&&i.previousSibling.previousElementSibling;if(r&&t){let t="media"!==r.slot;for(;null!==(r=r.previousSibling);)"media"==r.slot&&(t=!1);t&&this.mediaUnsetCallback(e)}else this.mediaUnsetCallback(e)}})),t&&i.addedNodes.forEach((e=>{e===t&&this.handleMediaUpdated(t)})))})).observe(this,{childList:!0,subtree:!0});let e=!1;Oo(this,(t=>{e||(setTimeout((()=>{al(t),e=!1,this.breakpointsComputed||(this.breakpointsComputed=!0,this.dispatchEvent(new CustomEvent(ea.BREAKPOINTS_COMPUTED,{bubbles:!0,composed:!0})))}),0),e=!0)}));let t=this.querySelector(":scope > slot[slot=media]");t&&t.addEventListener("slotchange",(()=>{t.assignedElements({flatten:!0}).length?this.handleMediaUpdated(this.media):Zo(this,$o)&&this.mediaUnsetCallback(Zo(this,$o))}))}static get observedAttributes(){return[il.AUTOHIDE,il.GESTURES_DISABLED].concat(sl).filter((e=>![Jn.MEDIA_RENDITION_LIST,Jn.MEDIA_AUDIO_TRACK_LIST,Jn.MEDIA_CHAPTERS_CUES].includes(e)))}attributeChangedCallback(e,t,i){e.toLowerCase()==il.AUTOHIDE&&(this.autohide=i)}get media(){let e=this.querySelector(":scope > [slot=media]");return"SLOT"==e?.nodeName&&(e=e.assignedElements({flatten:!0})[0]),e}async handleMediaUpdated(e){e&&(el(this,$o,e),e.localName.includes("-")&&await uo.customElements.whenDefined(e.localName),this.mediaSetCallback(e))}connectedCallback(){var e;let t=null!=this.getAttribute(il.AUDIO)?da():ua();this.setAttribute("role","region"),this.setAttribute("aria-label",t),this.handleMediaUpdated(this.media),this.setAttribute(il.USER_INACTIVE,""),this.addEventListener("pointerdown",this),this.addEventListener("pointermove",this),this.addEventListener("pointerup",this),this.addEventListener("mouseleave",this),this.addEventListener("keyup",this),null==(e=uo.window)||e.addEventListener("mouseup",this)}disconnectedCallback(){var e;this.media&&this.mediaUnsetCallback(this.media),null==(e=uo.window)||e.removeEventListener("mouseup",this)}mediaSetCallback(e){}mediaUnsetCallback(e){el(this,$o,null)}handleEvent(e){switch(e.type){case"pointerdown":el(this,No,e.timeStamp);break;case"pointermove":tl(this,Fo,Bo).call(this,e);break;case"pointerup":tl(this,Ho,Go).call(this,e);break;case"mouseleave":tl(this,jo,Vo).call(this);break;case"mouseup":this.removeAttribute(il.KEYBOARD_CONTROL);break;case"keyup":tl(this,qo,Yo).call(this),this.setAttribute(il.KEYBOARD_CONTROL,"")}}set autohide(e){e=Number(e),this._autohide=isNaN(e)?0:e}get autohide(){return void 0===this._autohide?2:this._autohide}};No=new WeakMap,$o=new WeakMap,Fo=new WeakSet,Bo=function(e){"mouse"!==e.pointerType&&e.timeStamp-Zo(this,No)<250||(tl(this,Ko,Wo).call(this),clearTimeout(this._inactiveTimeout),[this,this.media].includes(e.target)&&tl(this,qo,Yo).call(this))},Ho=new WeakSet,Go=function(e){if("touch"===e.pointerType){let t=!this.hasAttribute(il.USER_INACTIVE);[this,this.media].includes(e.target)&&t?tl(this,jo,Vo).call(this):tl(this,qo,Yo).call(this)}else e.composedPath().some((e=>["media-play-button","media-fullscreen-button"].includes(e?.localName)))&&tl(this,qo,Yo).call(this)},jo=new WeakSet,Vo=function(){if(this.autohide<0||this.hasAttribute(il.USER_INACTIVE))return;this.setAttribute(il.USER_INACTIVE,"");let e=new uo.CustomEvent(ea.USER_INACTIVE,{composed:!0,bubbles:!0,detail:!0});this.dispatchEvent(e)},Ko=new WeakSet,Wo=function(){if(!this.hasAttribute(il.USER_INACTIVE))return;this.removeAttribute(il.USER_INACTIVE);let e=new uo.CustomEvent(ea.USER_INACTIVE,{composed:!0,bubbles:!0,detail:!1});this.dispatchEvent(e)},qo=new WeakSet,Yo=function(){tl(this,Ko,Wo).call(this),clearTimeout(this._inactiveTimeout),!(this.autohide<0)&&(this._inactiveTimeout=setTimeout((()=>{tl(this,jo,Vo).call(this)}),1e3*this.autohide))};var ll,hl,dl,ul,cl,fl,pl=(e,t,i)=>{if(!t.has(e))throw TypeError("Cannot "+i)},ml=(e,t,i)=>(pl(e,t,"read from private field"),i?i.call(e):t.get(e)),gl=(e,t,i)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,i)},vl=(e,t,i,r)=>(pl(e,t,"write to private field"),t.set(e,i),i),El=class{constructor(e,t,{defaultValue:i}={defaultValue:void 0}){gl(this,cl),gl(this,ll,void 0),gl(this,hl,void 0),gl(this,dl,void 0),gl(this,ul,new Set),vl(this,ll,e),vl(this,hl,t),vl(this,dl,new Set(i))}[Symbol.iterator](){return ml(this,cl,fl).values()}get length(){return ml(this,cl,fl).size}get value(){var e;return null!=(e=[...ml(this,cl,fl)].join(" "))?e:""}set value(e){var t;e!==this.value&&(vl(this,ul,new Set),this.add(...null!=(t=e?.split(" "))?t:[]))}toString(){return this.value}item(e){return[...ml(this,cl,fl)][e]}values(){return ml(this,cl,fl).values()}forEach(e){ml(this,cl,fl).forEach(e)}add(...e){var t,i;e.forEach((e=>ml(this,ul).add(e))),(""!==this.value||null!=(t=ml(this,ll))&&t.hasAttribute(`${ml(this,hl)}`))&&(null==(i=ml(this,ll))||i.setAttribute(`${ml(this,hl)}`,`${this.value}`))}remove(...e){var t;e.forEach((e=>ml(this,ul).delete(e))),null==(t=ml(this,ll))||t.setAttribute(`${ml(this,hl)}`,`${this.value}`)}contains(e){return ml(this,cl,fl).has(e)}toggle(e,t){return typeof t<"u"?t?(this.add(e),!0):(this.remove(e),!1):this.contains(e)?(this.remove(e),!1):(this.add(e),!0)}replace(e,t){return this.remove(e),this.add(t),e===t}};ll=new WeakMap,hl=new WeakMap,dl=new WeakMap,ul=new WeakMap,cl=new WeakSet,fl=function(){return ml(this,ul).size?ml(this,ul):ml(this,dl)};var yl=(e="")=>{let[t,i,r]=e.split(":");return t="cc"===t?"captions":"subtitles",{kind:t,language:i,label:r?decodeURIComponent(r):void 0}},bl=(e="",t={})=>((e="")=>e.split(/\s+/))(e).map((e=>{let i=yl(e);return{...t,...i}})),Tl=e=>Array.isArray(e)?e.map((e=>"string"==typeof e?yl(e):e)):"string"==typeof e?bl(e):[e],Sl=({kind:e,label:t,language:i}={kind:"subtitles"})=>t?`${"captions"===e?"cc":"sb"}:${i}:${encodeURIComponent(t)}`:i,Al=(e=[])=>Array.prototype.map.call(e,Sl).join(" "),_l=e=>{let t=Object.entries(e).map((([e,t])=>((e,t)=>i=>i[e]===t)(e,t)));return e=>t.every((t=>t(e)))},wl=(e,t=[],i=[])=>{let r=Tl(i).map(_l);Array.from(t).filter((e=>r.some((t=>t(e))))).forEach((t=>{t.mode=e}))},kl=(e,t=()=>!0)=>{if(!e?.textTracks)return[];let i="function"==typeof t?t:_l(t);return Array.from(e.textTracks).filter(i)},Ll={enter:"requestFullscreen",exit:"exitFullscreen",rootEvents:["fullscreenchange"],mediaEvents:[],element:"fullscreenElement",error:"fullscreenerror",enabled:"fullscreenEnabled"};void 0===co.fullscreenElement&&(Ll.enter="webkitRequestFullScreen",Ll.exit=null!=co.webkitExitFullscreen?"webkitExitFullscreen":"webkitCancelFullScreen",Ll.rootEvents=["webkitfullscreenchange"],Ll.mediaEvents=["webkitbeginfullscreen","webkitendfullscreen"],Ll.element="webkitFullscreenElement",Ll.error="webkitfullscreenerror",Ll.enabled="webkitFullscreenEnabled");var Rl,Il,Cl,Dl,xl,Ml,Pl,Ol,Ul,Nl=()=>{var e,t;return Rl||(Rl=null==(t=null==(e=co)?void 0:e.createElement)?void 0:t.call(e,"video"))},$l=/.*Version\/.*Safari\/.*/.test(uo.navigator.userAgent),Fl=((e=Nl())=>{let t=co[Ll.enabled];return!t&&e&&(t="webkitSupportsFullscreen"in e),t})(),Bl=((e=Nl())=>(!uo.matchMedia("(display-mode: standalone)").matches||!$l)&&"function"==typeof e?.requestPictureInPicture)(),Hl=!!uo.WebKitPlaybackTargetAvailabilityEvent,Gl=!!uo.chrome,jl=(async(e=Nl())=>{if(!e)return!1;let t=e.volume;return e.volume=t/2+.1,await Na(0),e.volume!==t})().then((e=>Il=e)),Vl=Object.values(ha),Kl=e=>kl(e.media,(e=>[ia.SUBTITLES,ia.CAPTIONS].includes(e.kind))).sort(((e,t)=>e.kind>=t.kind?1:-1)),Wl=e=>kl(e.media,(e=>e.mode===sa&&[ia.SUBTITLES,ia.CAPTIONS].includes(e.kind))),ql={MEDIA_PAUSED:{get:function(e){let{media:t}=e;return!t||t.paused},mediaEvents:["play","playing","pause","emptied"]},MEDIA_HAS_PLAYED:{get:function(e){let{media:t}=e;return!!t&&!t.paused},mediaEvents:["playing","emptied"]},MEDIA_ENDED:{get:function(e){let{media:t}=e;return!!t&&t.ended},mediaEvents:["seeked","ended","emptied"]},MEDIA_PLAYBACK_RATE:{get:function(e){let{media:t}=e;return!t||typeof t.playbackRate>"u"?1:t.playbackRate},mediaEvents:["ratechange","loadstart"]},MEDIA_MUTED:{get:function(e){let{media:t}=e;return!(!t||typeof t.muted>"u")&&t.muted},mediaEvents:["volumechange"]},MEDIA_VOLUME:{get:function(e){let{media:t}=e;return!t||typeof t.volume>"u"?1:Number(t.volume)},mediaEvents:["volumechange"]},MEDIA_VOLUME_LEVEL:{get:function(e){let{media:t}=e,i="high";if(!t||typeof t.volume>"u")return i;let{muted:r,volume:s}=t;return 0===s||r?i="off":s<.5?i="low":s<.75&&(i="medium"),i},mediaEvents:["volumechange"]},MEDIA_CURRENT_TIME:{get:function(e){let{media:t}=e;return!t||typeof t.currentTime>"u"?0:t.currentTime},mediaEvents:["playing","pause","timeupdate","loadedmetadata"]},MEDIA_DURATION:{get:function(e){let{media:t}=e;return!e.hasAttribute("defaultduration")||t&&t.duration&&!Number.isNaN(t.duration)&&Number.isFinite(t.duration)?t&&Number.isFinite(t.duration)?t.duration:Number.NaN:+e.getAttribute("defaultduration")},mediaEvents:["durationchange","loadedmetadata","emptied"]},MEDIA_SEEKABLE:{get:function(e){var t;let{media:i}=e;if(null==(t=i?.seekable)||!t.length)return;let r=i.seekable.start(0),s=i.seekable.end(i.seekable.length-1);return r||s?[Number(r.toFixed(3)),Number(s.toFixed(3))]:void 0},mediaEvents:["loadedmetadata","emptied","progress"]},MEDIA_LOADING:{get:function(e){var t;return(null==(t=e.media)?void 0:t.readyState)<3},mediaEvents:["waiting","playing","emptied"]},MEDIA_BUFFERED:{get:function(e){var t,i,r;let s=null==(t=e.media)?void 0:t.buffered;return Array.from(null!=(r=null==(i=e.media)?void 0:i.buffered)?r:[]).map(((e,t)=>[Number(s.start(t)).toFixed(3),Number(s.end(t)).toFixed(3)]))},mediaEvents:["progress","emptied"]},MEDIA_STREAM_TYPE:{get:function(e){let{media:t}=e;if(!t)return;let{streamType:i}=t;if(Vl.includes(i)){if(i===ha.UNKNOWN){let t=e.getAttribute("defaultstreamtype");return[ha.LIVE,ha.ON_DEMAND].includes(t)?t:void 0}return i}let r=t.duration;if(r===1/0)return ha.LIVE;if(Number.isFinite(r))return ha.ON_DEMAND;{let t=e.getAttribute("defaultstreamtype");if([ha.LIVE,ha.ON_DEMAND].includes(t))return t}},mediaEvents:["emptied","durationchange","loadedmetadata","streamtypechange"]},MEDIA_TARGET_LIVE_WINDOW:{get:function(e){let{media:t}=e;if(!t)return Number.NaN;let{targetLiveWindow:i}=t,r=ql.MEDIA_STREAM_TYPE.get(e);return null!=i&&!Number.isNaN(i)||r!==ha.LIVE?i:0},mediaEvents:["emptied","durationchange","loadedmetadata","streamtypechange","targetlivewindowchange"]},MEDIA_TIME_IS_LIVE:{get:function(e){let{media:t}=e;if(!t)return!1;if("number"==typeof t.liveEdgeStart)return!Number.isNaN(t.liveEdgeStart)&&t.currentTime>=t.liveEdgeStart;if("live"!==ql.MEDIA_STREAM_TYPE.get(e))return!1;let i=t.seekable;if(!i)return!0;if(!i.length)return!1;let r=e.hasAttribute("liveedgeoffset")?Number(e.getAttribute("liveedgeoffset")):10,s=i.end(i.length-1)-r;return t.currentTime>=s},mediaEvents:["playing","timeupdate","progress","waiting","emptied"]},MEDIA_IS_FULLSCREEN:{get:function(e,t){var i,r;let s,n=e.media;return n&&void 0===co[Ll.element]&&"webkitDisplayingFullscreen"in n?n.webkitDisplayingFullscreen&&"fullscreen"===n.webkitPresentationMode:(s=t?co[Ll.element]?t.target:null:null!=(r=null==(i=function(e){var t;let i=null==(t=e?.getRootNode)?void 0:t.call(e);return i instanceof ShadowRoot||i instanceof Document?i:null}(e))?void 0:i.fullscreenElement)?r:co[Ll.element],ja(e.fullscreenElement,s))},rootEvents:Ll.rootEvents,mediaEvents:Ll.mediaEvents},MEDIA_IS_PIP:{get:function(e,t){var i;let r=e.media;if(!r)return!1;if(t)return"enterpictureinpicture"==t.type;{let t=null!=(i=e.getRootNode().pictureInPictureElement)?i:co.pictureInPictureElement;return ja(r,t)}},mediaEvents:["enterpictureinpicture","leavepictureinpicture"]},MEDIA_IS_AIRPLAYING:{get:function(e){var t;let{media:i}=e;return!(!i?.remote||"disconnected"===(null==(t=i.remote)?void 0:t.state))&&i.remote.state},remoteEvents:["playing","connect","connecting","disconnect"]},MEDIA_IS_CASTING:{get:function(e){var t;let{media:i}=e;return!(!i?.remote||"disconnected"===(null==(t=i.remote)?void 0:t.state))&&i.remote.state},remoteEvents:["connect","connecting","disconnect"]},MEDIA_AIRPLAY_UNAVAILABLE:{get:function(e,{availability:t=!1}={}){return Hl?null!=t&&!0!==t?oa:void 0:la},mediaSetCallback(e,t){var i;e.disableRemotePlayback||e.hasAttribute("disableremoteplayback")||null==(i=e.remote)||i.watchAvailability((e=>t({availability:e}))).catch((e=>{"NotSupportedError"===e.name?t({availability:null}):t({availability:!1})}))},mediaUnsetCallback(e){var t;e.disableRemotePlayback||e.hasAttribute("disableremoteplayback")||null==(t=e.remote)||t.cancelWatchAvailability()}},MEDIA_CAST_UNAVAILABLE:{get:function(e,{availability:t=!1}={}){var i;let{media:r}=e;return Gl&&null!=(i=r?.remote)&&i.state?null!=t&&!0!==t?oa:void 0:la},mediaSetCallback(e,t){var i;e.disableRemotePlayback||e.hasAttribute("disableremoteplayback")||null==(i=e.remote)||i.watchAvailability((e=>t({availability:e}))).catch((e=>{"NotSupportedError"===e.name?t({availability:null}):t({availability:!1})}))},mediaUnsetCallback(e){var t;e.disableRemotePlayback||e.hasAttribute("disableremoteplayback")||null==(t=e.remote)||t.cancelWatchAvailability()}},MEDIA_FULLSCREEN_UNAVAILABLE:{get:function(){return Fl?void 0:oa}},MEDIA_PIP_UNAVAILABLE:{get:function(){return Bl?void 0:la}},MEDIA_RENDITION_UNAVAILABLE:{get:function(e){var t;let{media:i}=e;return i?.videoRenditions?null!=(t=i.videoRenditions)&&t.length?void 0:oa:la},mediaEvents:["emptied","loadstart"],videoRenditionsEvents:["addrendition","removerendition"]},MEDIA_AUDIO_TRACK_UNAVAILABLE:{get:function(e){var t,i;let{media:r}=e;return r?.audioTracks?(null!=(i=null==(t=r.audioTracks)?void 0:t.length)?i:0)<=1?oa:void 0:la},mediaEvents:["emptied","loadstart"],audioTracksEvents:["addtrack","removetrack"]},MEDIA_VOLUME_UNAVAILABLE:{get:function(e){if(void 0!==Il&&!Il)return la;let{media:t}=e;return t&&typeof t.volume>"u"?oa:void 0},mediaEvents:["loadstart"]},MEDIA_SUBTITLES_LIST:{get:function(e){return Kl(e).map((({kind:e,label:t,language:i})=>({kind:e,label:t,language:i})))},mediaEvents:["loadstart"],textTracksEvents:["addtrack","removetrack"]},MEDIA_SUBTITLES_SHOWING:{get:function(e,t){var i;return e.hasAttribute("defaultsubtitles")&&["addtrack","removetrack"].includes(t?.type)&&[ia.CAPTIONS,ia.SUBTITLES].includes(null==(i=t?.track)?void 0:i.kind)&&Yl.MEDIA_TOGGLE_SUBTITLES_REQUEST(void 0,{detail:!0},e),Wl(e).map((({kind:e,label:t,language:i})=>({kind:e,label:t,language:i})))},mediaEvents:["loadstart"],textTracksEvents:["addtrack","removetrack","change"]},MEDIA_CHAPTERS_CUES:{get:function(e){var t;let{media:i}=e;if(!i)return[];let[r]=kl(i,{kind:ia.CHAPTERS});return Array.from(null!=(t=r?.cues)?t:[]).map((({text:e,startTime:t,endTime:i})=>({text:e,startTime:t,endTime:i})))},mediaEvents:["loadstart","loadedmetadata"],textTracksEvents:["addtrack","removetrack"]},MEDIA_RENDITION_LIST:{get:function(e){var t;let{media:i}=e;return[...null!=(t=i?.videoRenditions)?t:[]]},mediaEvents:["emptied","loadstart"],videoRenditionsEvents:["addrendition","removerendition"]},MEDIA_RENDITION_SELECTED:{get:function(e){var t,i,r;let{media:s}=e;return null==(r=null==(i=s?.videoRenditions)?void 0:i[null==(t=s.videoRenditions)?void 0:t.selectedIndex])?void 0:r.id},mediaEvents:["emptied"],videoRenditionsEvents:["addrendition","removerendition","change"]},MEDIA_AUDIO_TRACK_LIST:{get:function(e){var t;let{media:i}=e;return[...null!=(t=i?.audioTracks)?t:[]]},mediaEvents:["emptied","loadstart"],audioTracksEvents:["addtrack","removetrack"]},MEDIA_AUDIO_TRACK_ENABLED:{get:function(e){var t,i;let{media:r}=e;return null==(i=[...null!=(t=r?.audioTracks)?t:[]].find((e=>e.enabled)))?void 0:i.id},mediaEvents:["emptied"],audioTracksEvents:["addtrack","removetrack","change"]}},Yl={MEDIA_PLAY_REQUEST:(e,t,i)=>{var r;let s=ql.MEDIA_STREAM_TYPE.get(i),n=null===i.getAttribute("noautoseektolive");s==ha.LIVE&&n&&Yl.MEDIA_SEEK_TO_LIVE_REQUEST(e),null==(r=e.play())||r.catch((()=>{}))},MEDIA_PAUSE_REQUEST:e=>e.pause(),MEDIA_MUTE_REQUEST:e=>e.muted=!0,MEDIA_UNMUTE_REQUEST:e=>{e.muted=!1,0===e.volume&&(e.volume=.25)},MEDIA_VOLUME_REQUEST:(e,t,i)=>{let r=t.detail;if(e.volume=r,r>0&&e.muted&&(e.muted=!1),!i.hasAttribute("novolumepref"))try{uo.localStorage.setItem("media-chrome-pref-volume",r.toString())}catch{}},MEDIA_ENTER_FULLSCREEN_REQUEST:(e,t,i)=>{Fl?(co.pictureInPictureElement&&co.exitPictureInPicture(),i[Ll.enter]?i.fullscreenElement[Ll.enter]():e.webkitEnterFullscreen?e.webkitEnterFullscreen():e.requestFullscreen?e.requestFullscreen():console.warn("MediaChrome: Fullscreen not supported")):console.warn("MediaChrome: Fullscreen support is unavailable; not entering fullscreen")},MEDIA_EXIT_FULLSCREEN_REQUEST:()=>{co[Ll.exit]()},MEDIA_ENTER_PIP_REQUEST:e=>{if(!co.pictureInPictureEnabled)return void console.warn("MediaChrome: Picture-in-picture is not enabled");if(!e.requestPictureInPicture)return void console.warn("MediaChrome: The current media does not support picture-in-picture");co[Ll.element]&&co[Ll.exit]();let t=()=>{console.warn("MediaChrome: The media is not ready for picture-in-picture. It must have a readyState > 0.")};e.requestPictureInPicture().catch((i=>{if(11!==i.code)throw i;if(0!==e.readyState||"none"!==e.preload)throw i;{let i=()=>{e.removeEventListener("loadedmetadata",r),e.preload="none"},r=()=>{e.requestPictureInPicture().catch(t),i()};e.addEventListener("loadedmetadata",r),e.preload="metadata",setTimeout((()=>{0===e.readyState&&t(),i()}),1e3)}}))},MEDIA_EXIT_PIP_REQUEST:()=>{co.pictureInPictureElement&&co.exitPictureInPicture()},MEDIA_ENTER_CAST_REQUEST:async e=>{var t;if("disconnected"===(null==(t=e.remote)?void 0:t.state)){if(co[Ll.element]&&co[Ll.exit](),!e.remote.prompt)return void console.warn("MediaChrome: Casting is not supported in this environment");try{await e.remote.prompt()}catch{}}},MEDIA_EXIT_CAST_REQUEST:e=>{var t;"connected"===(null==(t=e.remote)?void 0:t.state)&&e.remote.prompt()},MEDIA_SEEK_REQUEST:(e,t)=>{let i=t.detail;(e.readyState>0||void 0===e.readyState)&&(e.currentTime=i)},MEDIA_PLAYBACK_RATE_REQUEST:(e,t)=>{e.playbackRate=t.detail},MEDIA_PREVIEW_REQUEST:(e,t,i)=>{var r,s,n,a,o,l;if(!e)return;let h=t.detail;if(null===h)return i.propagateMediaState(Jn.MEDIA_PREVIEW_TIME,void 0),i.propagateMediaState(Jn.MEDIA_PREVIEW_IMAGE,void 0),void i.propagateMediaState(Jn.MEDIA_PREVIEW_COORDS,void 0);i.propagateMediaState(Jn.MEDIA_PREVIEW_TIME,h);let[d]=kl(e,{kind:ia.CHAPTERS}),u=Array.from(null!=(r=d?.cues)?r:[]).find((e=>e.startTime<=h&&e.endTime>h));i.propagateMediaState(Jn.MEDIA_PREVIEW_CHAPTER,u?.text);let[c]=kl(e,{kind:ia.METADATA,label:"thumbnails"}),f=Array.from(null!=(s=c?.cues)?s:[]).find((e=>e.startTime>=h));if(!f)return;let p=/'^(?:[a-z]+:)?\/\//i.test(null!=(n=f?.text)?n:"")||null==(a=e.querySelector('track[label="thumbnails"]'))?void 0:a.src,m=new URL(null!=(o=f?.text)?o:"./",p),g=null!=(l=new URLSearchParams(m.hash).get("#xywh"))?l:"";i.propagateMediaState(Jn.MEDIA_PREVIEW_IMAGE,m.href),i.propagateMediaState(Jn.MEDIA_PREVIEW_COORDS,g.split(","))},MEDIA_SHOW_SUBTITLES_REQUEST:(e,t,i)=>{var r;let s=Kl(i),{detail:n=[]}=t,a=Tl(n),o=null==(r=a[0])?void 0:r.language;o&&!i?.hasAttribute("nosubtitleslangpref")&&uo.localStorage.setItem("media-chrome-pref-subtitles-lang",o),wl(sa,s,a)},MEDIA_DISABLE_SUBTITLES_REQUEST:(e,t,i)=>{let r=Kl(i),{detail:s=[]}=t;wl(ra,r,s)},MEDIA_TOGGLE_SUBTITLES_REQUEST:(e,t,i)=>{let{detail:r}=t??{},s=Kl(i),n=Wl(i),a=!!n.length;if(s.length)if(!1===r||a&&!0!==r)wl(ra,s,n);else if(!0===r||!a&&!1!==r){let e=s[0];if(!i?.hasAttribute("nosubtitleslangpref")){let t=uo.localStorage.getItem("media-chrome-pref-subtitles-lang"),i=t?[t,...uo.navigator.languages]:uo.navigator.languages,r=s.filter((e=>i.some((t=>e.language.toLowerCase().startsWith(t.split("-")[0]))))).sort(((e,t)=>{let r=i.findIndex((t=>e.language.toLowerCase().startsWith(t.split("-")[0]))),s=i.findIndex((e=>t.language.toLowerCase().startsWith(e.split("-")[0])));return r-s}));r[0]&&(e=r[0])}let{language:t,label:r,kind:a}=e;wl(ra,s,n),wl(sa,s,[{language:t,label:r,kind:a}])}},MEDIA_AIRPLAY_REQUEST:async e=>{if(e?.remote){if(!e.remote.prompt)return void console.warn("MediaChrome: AirPlay is not supported in this environment");try{await e.remote.prompt()}catch{}}},MEDIA_SEEK_TO_LIVE_REQUEST:e=>{let t=e.seekable;t?t.length?e.currentTime=t.end(t.length-1):console.warn("MediaChrome: Media is unable to seek to live."):console.warn("MediaChrome: Media element does not support seeking to live.")},MEDIA_RENDITION_REQUEST:(e,t)=>{if(!e?.videoRenditions)return void console.warn("MediaChrome: Rendition selection not supported by this media.");let i=t.detail,r=[...e.videoRenditions].findIndex((e=>e.id==i));e.videoRenditions.selectedIndex!=r&&(e.videoRenditions.selectedIndex=r)},MEDIA_AUDIO_TRACK_REQUEST:(e,t)=>{if(!e?.audioTracks)return void console.warn("MediaChrome: Audio track selection not supported by this media.");let i=t.detail;for(let t of e.audioTracks)t.enabled=i==t.id}},zl=(e,t,i)=>{if(!t.has(e))throw TypeError("Cannot "+i)},Xl=(e,t,i)=>(zl(e,t,"read from private field"),i?i.call(e):t.get(e)),Ql=(e,t,i)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,i)},Zl=(e,t,i,r)=>(zl(e,t,"write to private field"),t.set(e,i),i),Jl=(e,t,i)=>(zl(e,t,"access private method"),i),eh=["ArrowLeft","ArrowRight","Enter"," ","f","m","k","c"],th="defaultsubtitles",ih="defaultstreamtype",rh="defaultduration",sh="fullscreenelement",nh="hotkeys",ah="keysused",oh="nohotkeys";Cl=new WeakMap,Dl=new WeakMap,xl=new WeakMap,Ml=new WeakSet,Pl=function(e){let{key:t}=e;eh.includes(t)?this.keyboardShortcutHandler(e):this.removeEventListener("keyup",Jl(this,Ml,Pl))},Ol=new WeakSet,Ul=function(e){let{metaKey:t,altKey:i,key:r}=e;t||i||!eh.includes(r)?this.removeEventListener("keyup",Jl(this,Ml,Pl)):([" ","ArrowLeft","ArrowRight"].includes(r)&&!(Xl(this,Cl).contains(`no${r.toLowerCase()}`)||" "===r&&Xl(this,Cl).contains("nospace"))&&e.preventDefault(),this.addEventListener("keyup",Jl(this,Ml,Pl),{once:!0}))};var lh=Object.values(Jn),hh=Object.values(Qn),dh=e=>{var t,i,r,s;let{observedAttributes:n}=e.constructor;!n&&null!=(t=e.nodeName)&&t.includes("-")&&(uo.customElements.upgrade(e),({observedAttributes:n}=e.constructor));let a=null==(s=null==(r=null==(i=e?.getAttribute)?void 0:i.call(e,zn))?void 0:r.split)?void 0:s.call(r,/\s+/);return Array.isArray(n||a)?(n||a).filter((e=>lh.includes(e))):[]},uh=e=>(e=>{var t,i;return null!=(t=e.nodeName)&&t.includes("-")&&uo.customElements.get(null==(i=e.nodeName)?void 0:i.toLowerCase())&&!(e instanceof uo.customElements.get(e.nodeName.toLowerCase()))&&uo.customElements.upgrade(e),hh.some((t=>t in e))})(e)||!!dh(e).length,ch=e=>{var t;return null==(t=e?.join)?void 0:t.call(e,":")},fh={[Jn.MEDIA_SUBTITLES_LIST]:Al,[Jn.MEDIA_SUBTITLES_SHOWING]:Al,[Jn.MEDIA_SEEKABLE]:ch,[Jn.MEDIA_BUFFERED]:e=>e?.map(ch).join(" "),[Jn.MEDIA_PREVIEW_COORDS]:e=>e?.join(" "),[Jn.MEDIA_RENDITION_LIST]:function(e){return e?.map(Pa).join(" ")},[Jn.MEDIA_AUDIO_TRACK_LIST]:function(e){return e?.map(Oa).join(" ")}},ph=(e,t)=>{if((e=>{var t;return!(null==(t=e.closest)||!t.call(e,'*[slot="media"]'))})(e))return;let i=(e,t)=>{var i,r;uh(e)&&t(e);let{children:s=[]}=e??{};[...s,...null!=(r=null==(i=e?.shadowRoot)?void 0:i.children)?r:[]].forEach((e=>ph(e,t)))},r=e?.nodeName.toLowerCase();!r.includes("-")||uh(e)?i(e,t):uo.customElements.whenDefined(r).then((()=>{i(e,t)}))},mh=(e,t,i)=>{e.forEach((e=>{if(t in e)return void(e[t]=i);let r=dh(e),s=t.toLowerCase();r.includes(s)&&(async(e,t,i)=>{var r,s;if(e.isConnected||await Na(0),"boolean"==typeof i||null==i)return Za(e,t,i);if("number"==typeof i)return Xa(e,t,i);if("string"==typeof i)return eo(e,t,i);if(Array.isArray(i)&&!i.length)return e.removeAttribute(t);let n=null!=(s=null==(r=fh[t])?void 0:r.call(fh,i))?s:i;e.setAttribute(t,n)})(e,s,i)}))},gh=(e,t)=>{for(let i of e){if(t in i)return i[t];let e=dh(i),r=t.toLowerCase();if(e.includes(r))return i.getAttribute(r)}},vh=(e,t,i)=>{ph(e,t);let r=e=>{var i;let r=null!=(i=e?.composedPath()[0])?i:e.target;t(r)},s=e=>{var t;let r=null!=(t=e?.composedPath()[0])?t:e.target;i(r)};e.addEventListener(Yn.REGISTER_MEDIA_STATE_RECEIVER,r),e.addEventListener(Yn.UNREGISTER_MEDIA_STATE_RECEIVER,s);let n=[],a=e=>{let r=e.target;"media"!==r.name&&(n.forEach((e=>ph(e,i))),n=[...r.assignedElements({flatten:!0})],n.forEach((e=>ph(e,t))))};e.addEventListener("slotchange",a);let o=new MutationObserver((e=>{e.forEach((e=>{let{addedNodes:r=[],removedNodes:s=[],type:n,target:a,attributeName:o}=e;"childList"===n?(Array.prototype.forEach.call(r,(e=>ph(e,t))),Array.prototype.forEach.call(s,(e=>ph(e,i)))):"attributes"===n&&o===zn&&(uh(a)?t(a):i(a))}))}));return o.observe(e,{childList:!0,attributes:!0,subtree:!0}),()=>{ph(e,i),e.removeEventListener("slotchange",a),o.disconnect(),e.removeEventListener(Yn.REGISTER_MEDIA_STATE_RECEIVER,r),e.removeEventListener(Yn.UNREGISTER_MEDIA_STATE_RECEIVER,s)}};uo.customElements.get("media-controller")||uo.customElements.define("media-controller",class extends ol{constructor(){super(),Ql(this,Ml),Ql(this,Ol),Ql(this,Cl,new El(this,nh)),Ql(this,Dl,void 0),Ql(this,xl,void 0),void 0===ql.MEDIA_VOLUME_UNAVAILABLE.get(this)&&jl.then((()=>{this.propagateMediaState(Jn.MEDIA_VOLUME_UNAVAILABLE,ql.MEDIA_VOLUME_UNAVAILABLE.get(this))})),this.mediaStateReceivers=[],this.associatedElementSubscriptions=new Map,this.associateElement(this),Object.keys(Yl).forEach((e=>{let t=`_handle${Ua(e,!0)}`;this[t]=t=>{t.stopPropagation(),this.media?Yl[e](this.media,t,this):console.warn("Media Chrome: No media available.")},this.addEventListener(Yn[e],this[t])})),this._mediaStatePropagators={},Object.keys(ql).forEach((e=>{this._mediaStatePropagators[e]=t=>{this.propagateMediaState(Qn[e],ql[e].get(this,t))}}))}static get observedAttributes(){return super.observedAttributes.concat(oh,nh,ih,th,rh)}get fullscreenElement(){var e;return null!=(e=Xl(this,Dl))?e:this}set fullscreenElement(e){this.hasAttribute(sh)&&this.removeAttribute(sh),Zl(this,Dl,e)}attributeChangedCallback(e,t,i){var r;if(super.attributeChangedCallback(e,t,i),e===oh)i!==t&&""===i?(this.hasAttribute(nh)&&console.warn("Media Chrome: Both `hotkeys` and `nohotkeys` have been set. All hotkeys will be disabled."),this.disableHotkeys()):i!==t&&null===i&&this.enableHotkeys();else if(e===nh)Xl(this,Cl).value=i;else if(e===th&&i!==t&&""===i)this.dispatchEvent(new uo.CustomEvent(Yn.MEDIA_TOGGLE_SUBTITLES_REQUEST,{composed:!0,bubbles:!0,detail:!0}));else if(e===ih)this.propagateMediaState(Qn.MEDIA_STREAM_TYPE);else if(e===sh){let e=i?null==(r=Xl(this,xl))?void 0:r.getElementById(i):void 0;Zl(this,Dl,e)}}connectedCallback(){Zl(this,xl,this.getRootNode()),super.connectedCallback(),this.enableHotkeys()}disconnectedCallback(){super.disconnectedCallback(),this.disableHotkeys(),this.dispatchEvent(new uo.CustomEvent(Yn.MEDIA_TOGGLE_SUBTITLES_REQUEST,{composed:!0,bubbles:!0,detail:!1}))}mediaSetCallback(e){if(super.mediaSetCallback(e),e.hasAttribute("tabindex")||(e.tabIndex=-1),Object.keys(ql).forEach((t=>{let{mediaSetCallback:i,mediaEvents:r,rootEvents:s,textTracksEvents:n,videoRenditionsEvents:a,audioTracksEvents:o,remoteEvents:l}=ql[t],h=this._mediaStatePropagators[t];i&&(i(e,h),h()),r?.forEach((t=>{e.addEventListener(t,h),h()})),s?.forEach((e=>{var t;null==(t=Xl(this,xl))||t.addEventListener(e,h),h()})),n?.forEach((t=>{var i;null==(i=e.textTracks)||i.addEventListener(t,h),h()})),a?.forEach((t=>{var i;null==(i=e.videoRenditions)||i.addEventListener(t,h),h()})),o?.forEach((t=>{var i;null==(i=e.audioTracks)||i.addEventListener(t,h),h()})),l?.forEach((t=>{var i;null==(i=e.remote)||i.addEventListener(t,h),h()}))})),!this.hasAttribute("novolumepref"))try{let t=uo.localStorage.getItem("media-chrome-pref-volume");null!==t&&(e.volume=t)}catch(e){console.debug("Media Chrome: Error getting volume pref",e)}}mediaUnsetCallback(e){super.mediaUnsetCallback(e),Object.keys(ql).forEach((t=>{let{mediaUnsetCallback:i,mediaEvents:r,rootEvents:s,textTracksEvents:n,videoRenditionsEvents:a,audioTracksEvents:o,remoteEvents:l}=ql[t],h=this._mediaStatePropagators[t];r?.forEach((t=>{e.removeEventListener(t,h)})),s?.forEach((e=>{var t;null==(t=Xl(this,xl))||t.removeEventListener(e,h)})),n?.forEach((t=>{var i;null==(i=e.textTracks)||i.removeEventListener(t,h)})),a?.forEach((t=>{var i;null==(i=e.videoRenditions)||i.removeEventListener(t,h),h()})),o?.forEach((t=>{var i;null==(i=e.audioTracks)||i.removeEventListener(t,h),h()})),l?.forEach((t=>{var i;null==(i=e.remote)||i.removeEventListener(t,h),h()})),i&&(i(e,h),h())})),this.propagateMediaState(Qn.MEDIA_PAUSED,!0)}propagateMediaState(e,t){let i=gh(this.mediaStateReceivers,e);if(mh(this.mediaStateReceivers,e,t),i===gh(this.mediaStateReceivers,e))return;let r=e.toLowerCase(),s=new uo.CustomEvent(ta[r],{composed:!0,bubbles:!0,detail:t});this.dispatchEvent(s)}associateElement(e){if(!e)return;let{associatedElementSubscriptions:t}=this;if(t.has(e))return;let i=this.registerMediaStateReceiver.bind(this),r=this.unregisterMediaStateReceiver.bind(this),s=vh(e,i,r);Object.keys(Yn).forEach((t=>{e.addEventListener(Yn[t],this[`_handle${Ua(t,!0)}`])})),t.set(e,s)}unassociateElement(e){if(!e)return;let{associatedElementSubscriptions:t}=this;t.has(e)&&(t.get(e)(),t.delete(e),Object.keys(Yn).forEach((t=>{e.removeEventListener(Yn[t],this[`_handle${Ua(t,!0)}`])})))}registerMediaStateReceiver(e){if(!e)return;let t=this.mediaStateReceivers;t.indexOf(e)>-1||(t.push(e),Object.keys(ql).forEach((t=>{let i=ql[t];mh([e],Qn[t],i.get(this))})))}unregisterMediaStateReceiver(e){let t=this.mediaStateReceivers,i=t.indexOf(e);i<0||t.splice(i,1)}enableHotkeys(){this.addEventListener("keydown",Jl(this,Ol,Ul))}disableHotkeys(){this.removeEventListener("keydown",Jl(this,Ol,Ul)),this.removeEventListener("keyup",Jl(this,Ml,Pl))}get hotkeys(){return Xl(this,Cl)}keyboardShortcutHandler(e){var t,i,r,s;if((null!=(s=null!=(r=null==(t=e.target.getAttribute(ah))?void 0:t.split(" "))?r:null==(i=e.target)?void 0:i.keysUsed)?s:[]).map((e=>"Space"===e?" ":e)).filter(Boolean).includes(e.key))return;let n,a,o,l,h;if(!(Xl(this,Cl).contains(`no${e.key.toLowerCase()}`)||" "===e.key&&Xl(this,Cl).contains("nospace")))switch(e.key){case" ":case"k":n=null!=this.getAttribute(Jn.MEDIA_PAUSED)?Yn.MEDIA_PLAY_REQUEST:Yn.MEDIA_PAUSE_REQUEST,this.dispatchEvent(new uo.CustomEvent(n,{composed:!0,bubbles:!0}));break;case"m":n="off"===this.getAttribute(Jn.MEDIA_VOLUME_LEVEL)?Yn.MEDIA_UNMUTE_REQUEST:Yn.MEDIA_MUTE_REQUEST,this.dispatchEvent(new uo.CustomEvent(n,{composed:!0,bubbles:!0}));break;case"f":n=null!=this.getAttribute(Jn.MEDIA_IS_FULLSCREEN)?Yn.MEDIA_EXIT_FULLSCREEN_REQUEST:Yn.MEDIA_ENTER_FULLSCREEN_REQUEST,this.dispatchEvent(new uo.CustomEvent(n,{composed:!0,bubbles:!0}));break;case"c":this.dispatchEvent(new uo.CustomEvent(Yn.MEDIA_TOGGLE_SUBTITLES_REQUEST,{composed:!0,bubbles:!0}));break;case"ArrowLeft":a=this.getAttribute(Jn.MEDIA_CURRENT_TIME),o=a&&!Number.isNaN(+a)?+a:0,l=Math.max(o-10,0),h=new uo.CustomEvent(Yn.MEDIA_SEEK_REQUEST,{composed:!0,bubbles:!0,detail:l}),this.dispatchEvent(h);break;case"ArrowRight":a=this.getAttribute(Jn.MEDIA_CURRENT_TIME),o=a&&!Number.isNaN(+a)?+a:0,l=Math.max(o+10,0),h=new uo.CustomEvent(Yn.MEDIA_SEEK_REQUEST,{composed:!0,bubbles:!0,detail:l}),this.dispatchEvent(h)}}});var Eh,yh,bh,Th,Sh,Ah,_h,wh,kh,Lh,Rh,Ih,Ch,Dh,xh,Mh,Ph,Oh,Uh,Nh,$h,Fh,Bh,Hh,Gh,jh=(e,t,i)=>{if(!t.has(e))throw TypeError("Cannot "+i)},Vh=(e,t,i)=>(jh(e,t,"read from private field"),i?i.call(e):t.get(e)),Kh=(e,t,i)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,i)},Wh=(e,t,i,r)=>(jh(e,t,"write to private field"),t.set(e,i),i),qh=(e,t,i)=>(jh(e,t,"access private method"),i),Yh=co.createElement("template");Yh.innerHTML='\n  <style>\n    :host {\n      --_focus-box-shadow: var(--media-focus-box-shadow, inset 0 0 0 2px rgb(27 127 204 / .9));\n      --_media-range-padding: var(--media-range-padding, var(--media-control-padding, 10px));\n\n      box-shadow: var(--_focus-visible-box-shadow, none);\n      background: var(--media-control-background, var(--media-secondary-color, rgb(20 20 30 / .7)));\n      height: calc(var(--media-control-height, 24px) + 2 * var(--_media-range-padding));\n      display: inline-flex;\n      align-items: center;\n      \n      vertical-align: middle;\n      box-sizing: border-box;\n      position: relative;\n      width: 100px;\n      transition: background .15s linear;\n      cursor: pointer;\n      pointer-events: auto;\n      touch-action: none; \n      z-index: 1; \n    }\n\n    \n    input[type=range]:focus {\n      outline: 0;\n    }\n    input[type=range]:focus::-webkit-slider-runnable-track {\n      outline: 0;\n    }\n\n    :host(:hover) {\n      background: var(--media-control-hover-background, rgb(50 50 70 / .7));\n    }\n\n    #leftgap {\n      padding-left: var(--media-range-padding-left, var(--_media-range-padding));\n    }\n\n    #rightgap {\n      padding-right: var(--media-range-padding-right, var(--_media-range-padding));\n    }\n\n    #startpoint,\n    #endpoint {\n      position: absolute;\n    }\n\n    #endpoint {\n      right: 0;\n    }\n\n    #container {\n      \n      width: var(--media-range-track-width, 100%);\n      transform: translate(var(--media-range-track-translate-x, 0px), var(--media-range-track-translate-y, 0px));\n      position: relative;\n      height: 100%;\n      display: flex;\n      align-items: center;\n      min-width: 40px;\n    }\n\n    #range {\n      \n      display: var(--media-time-range-hover-display, block);\n      bottom: var(--media-time-range-hover-bottom, -7px);\n      height: var(--media-time-range-hover-height, max(100% + 7px, 25px));\n      width: 100%;\n      position: absolute;\n      cursor: pointer;\n\n      -webkit-appearance: none; \n      -webkit-tap-highlight-color: transparent;\n      background: transparent; \n      margin: 0;\n      z-index: 1;\n    }\n\n    @media (hover: hover) {\n      #range {\n        bottom: var(--media-time-range-hover-bottom, -5px);\n        height: var(--media-time-range-hover-height, max(100% + 5px, 20px));\n      }\n    }\n\n    \n    \n    #range::-webkit-slider-thumb {\n      -webkit-appearance: none;\n      background: transparent;\n      width: .1px;\n      height: .1px;\n    }\n\n    \n    #range::-moz-range-thumb {\n      background: transparent;\n      border: transparent;\n      width: .1px;\n      height: .1px;\n    }\n\n    #appearance {\n      height: var(--media-range-track-height, 4px);\n      display: flex;\n      flex-direction: column;\n      justify-content: center;\n      width: 100%;\n      position: absolute;\n      \n      will-change: transform;\n    }\n\n    #background,\n    #track {\n      border-radius: var(--media-range-track-border-radius, 1px);\n      position: absolute;\n      width: 100%;\n      height: 100%;\n    }\n\n    #background {\n      background: var(--media-range-track-background, rgb(255 255 255 / .2));\n      backdrop-filter: var(--media-range-track-background-backdrop-filter);\n      -webkit-backdrop-filter: var(--media-range-track-background-backdrop-filter);\n    }\n\n    #track {\n      border: var(--media-range-track-border, none);\n      outline: var(--media-range-track-outline);\n      outline-offset: var(--media-range-track-outline-offset);\n      backdrop-filter: var(--media-range-track-backdrop-filter);\n      -webkit-backdrop-filter: var(--media-range-track-backdrop-filter);\n      box-shadow: var(--media-range-track-box-shadow, none);\n      overflow: hidden;\n    }\n\n    #progress,\n    #highlight,\n    #pointer {\n      position: absolute;\n      height: 100%;\n      will-change: width;\n    }\n\n    #progress {\n      background: var(--media-range-bar-color, var(--media-primary-color, rgb(238 238 238)));\n      transition: var(--media-range-track-transition);\n    }\n\n    #pointer {\n      background: var(--media-range-track-pointer-background);\n      border-right: var(--media-range-track-pointer-border-right);\n      transition: visibility .25s, opacity .25s;\n      visibility: hidden;\n      opacity: 0;\n    }\n\n    @media (hover: hover) {\n      :host(:hover) #pointer {\n        transition: visibility .5s, opacity .5s;\n        visibility: visible;\n        opacity: 1;\n      }\n    }\n\n    #thumb {\n      width: var(--media-range-thumb-width, 10px);\n      height: var(--media-range-thumb-height, 10px);\n      margin-left: calc(var(--media-range-thumb-width, 10px) / -2);\n      border: var(--media-range-thumb-border, none);\n      border-radius: var(--media-range-thumb-border-radius, 10px);\n      background: var(--media-range-thumb-background, var(--media-primary-color, rgb(238 238 238)));\n      box-shadow: var(--media-range-thumb-box-shadow, 1px 1px 1px transparent);\n      transition: var(--media-range-thumb-transition);\n      transform: var(--media-range-thumb-transform, none);\n      opacity: var(--media-range-thumb-opacity, 1);\n      position: absolute;\n      left: 0;\n      cursor: pointer;\n    }\n\n    :host([disabled]) #thumb {\n      background-color: #777;\n    }\n\n    .segments #appearance {\n      height: var(--media-range-segment-hover-height, 7px);\n    }\n\n    #background,\n    #track {\n      clip-path: url(#segments-clipping);\n    }\n\n    #segments {\n      --segments-gap: var(--media-range-segments-gap, 2px);\n      position: absolute;\n      width: 100%;\n      height: 100%;\n    }\n\n    #segments-clipping {\n      transform: translateX(calc(var(--segments-gap) / 2));\n    }\n\n    #segments-clipping:empty {\n      display: none;\n    }\n\n    #segments-clipping rect {\n      height: var(--media-range-track-height, 4px);\n      y: calc((var(--media-range-segment-hover-height, 7px) - var(--media-range-track-height, 4px)) / 2);\n      transition: var(--media-range-segment-transition, transform .1s ease-in-out);\n      transform: var(--media-range-segment-transform, scaleY(1));\n      transform-origin: center;\n    }\n  </style>\n  <div id="leftgap"></div>\n  <div id="container">\n    <div id="startpoint"></div>\n    <div id="endpoint"></div>\n    <div id="appearance" part="appearance">\n      <div id="background"></div>\n      <div id="track">\n        <div id="highlight"></div>\n        <div id="pointer"></div>\n        <div id="progress"></div>\n      </div>\n      <div id="thumb"></div>\n      <svg id="segments"><clipPath id="segments-clipping"></clipPath></svg>\n    </div>\n    <input id="range" type="range" min="0" max="1" step="any" value="0">\n  </div>\n  <div id="rightgap"></div>\n';var zh=class extends uo.HTMLElement{constructor(){super(),Kh(this,Lh),Kh(this,Ih),Kh(this,Dh),Kh(this,Mh),Kh(this,Oh),Kh(this,Nh),Kh(this,Fh),Kh(this,Hh),Kh(this,Eh,void 0),Kh(this,yh,void 0),Kh(this,bh,void 0),Kh(this,Th,void 0),Kh(this,Sh,{}),Kh(this,Ah,[]),Kh(this,_h,(()=>{if(this.range.matches(":focus-visible")){let{style:e}=qa(this.shadowRoot,":host");e.setProperty("--_focus-visible-box-shadow","var(--_focus-box-shadow)")}})),Kh(this,wh,(()=>{let{style:e}=qa(this.shadowRoot,":host");e.removeProperty("--_focus-visible-box-shadow")})),Kh(this,kh,(()=>{let e=this.shadowRoot.querySelector("#segments-clipping");e&&e.parentNode.append(e)})),this.shadowRoot||(this.attachShadow({mode:"open"}),this.shadowRoot.appendChild(Yh.content.cloneNode(!0))),this.container=this.shadowRoot.querySelector("#container"),Wh(this,bh,this.shadowRoot.querySelector("#startpoint")),Wh(this,Th,this.shadowRoot.querySelector("#endpoint")),this.range=this.shadowRoot.querySelector("#range"),this.appearance=this.shadowRoot.querySelector("#appearance")}static get observedAttributes(){return["disabled","aria-disabled",Xn]}attributeChangedCallback(e,t,i){var r,s,n,a,o;e===Xn?(t&&(null==(s=null==(r=Vh(this,Eh))?void 0:r.unassociateElement)||s.call(r,this),Wh(this,Eh,null)),i&&this.isConnected&&(Wh(this,Eh,null==(n=this.getRootNode())?void 0:n.getElementById(i)),null==(o=null==(a=Vh(this,Eh))?void 0:a.associateElement)||o.call(a,this))):("disabled"===e||"aria-disabled"===e&&t!==i)&&(null==i?(this.range.removeAttribute(e),qh(this,Ih,Ch).call(this)):(this.range.setAttribute(e,i),qh(this,Dh,xh).call(this)))}connectedCallback(){var e,t,i;let{style:r}=qa(this.shadowRoot,":host");r.setProperty("display",`var(--media-control-display, var(--${this.localName}-display, inline-flex))`),Vh(this,Sh).pointer=qa(this.shadowRoot,"#pointer"),Vh(this,Sh).progress=qa(this.shadowRoot,"#progress"),Vh(this,Sh).thumb=qa(this.shadowRoot,"#thumb");let s=this.getAttribute(Xn);s&&(Wh(this,Eh,null==(e=this.getRootNode())?void 0:e.getElementById(s)),null==(i=null==(t=Vh(this,Eh))?void 0:t.associateElement)||i.call(t,this)),this.updateBar(),this.shadowRoot.addEventListener("focusin",Vh(this,_h)),this.shadowRoot.addEventListener("focusout",Vh(this,wh)),qh(this,Ih,Ch).call(this),Oo(this.container,Vh(this,kh))}disconnectedCallback(){var e,t;qh(this,Dh,xh).call(this),null==(t=null==(e=Vh(this,Eh))?void 0:e.unassociateElement)||t.call(e,this),Wh(this,Eh,null),this.shadowRoot.removeEventListener("focusin",Vh(this,_h)),this.shadowRoot.removeEventListener("focusout",Vh(this,wh)),Uo(this.container,Vh(this,kh))}updatePointerBar(e){var t;null==(t=Vh(this,Sh).pointer)||t.style.setProperty("width",100*this.getPointerRatio(e)+"%")}updateBar(){var e,t;let i=100*this.range.valueAsNumber;null==(e=Vh(this,Sh).progress)||e.style.setProperty("width",`${i}%`),null==(t=Vh(this,Sh).thumb)||t.style.setProperty("left",`${i}%`)}updateSegments(e){let t=this.shadowRoot.querySelector("#segments-clipping");if(t.textContent="",!e?.length)return;Vh(this,Sh).activeSegment=Ya(this.shadowRoot,"#segments-clipping rect:nth-child(0)"),this.container.classList.toggle("segments",!!e.length);let i=[...new Set([+this.range.min,...e.flatMap((e=>[e.start,e.end])),+this.range.max])];Wh(this,Ah,[...i]);let r=i.pop();for(let[e,s]of i.entries()){let[n,a]=[0===e,e===i.length-1],o=n?"calc(var(--segments-gap) / -1)":100*s+"%",l=`calc(${100*((a?r:i[e+1])-s)}%${n||a?"":" - var(--segments-gap)"})`,h=co.createElementNS("http://www.w3.org/2000/svg","rect"),d=qa(this.shadowRoot,`#segments-clipping rect:nth-child(${e+1})`);d.style.setProperty("x",o),d.style.setProperty("width",l),t.append(h)}}getPointerRatio(e){let t=function(e,t,i,r){let s=Wa(i,r),n=Wa(i,{x:e,y:t}),a=Wa(r,{x:e,y:t});return n>s||a>s?n>a?1:0:n/s}(e.clientX,e.clientY,Vh(this,bh).getBoundingClientRect(),Vh(this,Th).getBoundingClientRect());return Math.max(0,Math.min(1,t))}get dragging(){return this.hasAttribute("dragging")}handleEvent(e){switch(e.type){case"pointermove":qh(this,Hh,Gh).call(this,e);break;case"input":this.updateBar();break;case"pointerenter":qh(this,Oh,Uh).call(this,e);break;case"pointerdown":qh(this,Mh,Ph).call(this,e);break;case"pointerup":qh(this,Nh,$h).call(this);break;case"pointerleave":qh(this,Fh,Bh).call(this)}}get keysUsed(){return["ArrowUp","ArrowRight","ArrowDown","ArrowLeft"]}};Eh=new WeakMap,yh=new WeakMap,bh=new WeakMap,Th=new WeakMap,Sh=new WeakMap,Ah=new WeakMap,_h=new WeakMap,wh=new WeakMap,kh=new WeakMap,Lh=new WeakSet,Rh=function(e){let t=Vh(this,Sh).activeSegment;if(!t)return;let i=this.getPointerRatio(e),r=`#segments-clipping rect:nth-child(${Vh(this,Ah).findIndex(((e,t,r)=>{let s=r[t+1];return null!=s&&i>=e&&i<=s}))+1})`;(t.selectorText!=r||!t.style.transform)&&(t.selectorText=r,t.style.setProperty("transform","var(--media-range-segment-hover-transform, scaleY(2))"))},Ih=new WeakSet,Ch=function(){this.hasAttribute("disabled")||(this.addEventListener("input",this),this.addEventListener("pointerdown",this),this.addEventListener("pointerenter",this))},Dh=new WeakSet,xh=function(){var e,t;this.removeEventListener("input",this),this.removeEventListener("pointerdown",this),this.removeEventListener("pointerenter",this),null==(e=uo.window)||e.removeEventListener("pointerup",this),null==(t=uo.window)||t.removeEventListener("pointermove",this)},Mh=new WeakSet,Ph=function(e){var t;Wh(this,yh,e.composedPath().includes(this.range)),null==(t=uo.window)||t.addEventListener("pointerup",this)},Oh=new WeakSet,Uh=function(e){var t;"mouse"!==e.pointerType&&qh(this,Mh,Ph).call(this,e),this.addEventListener("pointerleave",this),null==(t=uo.window)||t.addEventListener("pointermove",this)},Nh=new WeakSet,$h=function(){var e;null==(e=uo.window)||e.removeEventListener("pointerup",this),this.toggleAttribute("dragging",!1),this.range.disabled=this.hasAttribute("disabled")},Fh=new WeakSet,Bh=function(){var e,t;this.removeEventListener("pointerleave",this),null==(e=uo.window)||e.removeEventListener("pointermove",this),this.toggleAttribute("dragging",!1),this.range.disabled=this.hasAttribute("disabled"),null==(t=Vh(this,Sh).activeSegment)||t.style.removeProperty("transform")},Hh=new WeakSet,Gh=function(e){this.toggleAttribute("dragging",1===e.buttons||"mouse"!==e.pointerType),this.updatePointerBar(e),qh(this,Lh,Rh).call(this,e),this.dragging&&("mouse"!==e.pointerType||!Vh(this,yh))&&(this.range.disabled=!0,this.range.valueAsNumber=this.getPointerRatio(e),this.range.dispatchEvent(new Event("input",{bubbles:!0,composed:!0})))},uo.customElements.get("media-chrome-range")||uo.customElements.define("media-chrome-range",zh);var Xh,Qh=(e,t,i)=>{if(!t.has(e))throw TypeError("Cannot "+i)},Zh=(e,t,i)=>(Qh(e,t,"read from private field"),i?i.call(e):t.get(e)),Jh=(e,t,i,r)=>(Qh(e,t,"write to private field"),t.set(e,i),i),ed=co.createElement("template");ed.innerHTML="\n  <style>\n    :host {\n      \n      box-sizing: border-box;\n      display: var(--media-control-display, var(--media-control-bar-display, inline-flex));\n      color: var(--media-text-color, var(--media-primary-color, rgb(238 238 238)));\n      --media-loading-indicator-icon-height: 44px;\n    }\n\n    ::slotted(media-time-range),\n    ::slotted(media-volume-range) {\n      min-height: 100%;\n    }\n\n    ::slotted(media-time-range),\n    ::slotted(media-clip-selector) {\n      flex-grow: 1;\n    }\n  </style>\n\n  <slot></slot>\n";var td=class extends uo.HTMLElement{constructor(){super(),((e,t,i)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,i)})(this,Xh,void 0),this.shadowRoot||(this.attachShadow({mode:"open"}),this.shadowRoot.appendChild(ed.content.cloneNode(!0)))}static get observedAttributes(){return[Xn]}attributeChangedCallback(e,t,i){var r,s,n,a,o;e===Xn&&(t&&(null==(s=null==(r=Zh(this,Xh))?void 0:r.unassociateElement)||s.call(r,this),Jh(this,Xh,null)),i&&this.isConnected&&(Jh(this,Xh,null==(n=this.getRootNode())?void 0:n.getElementById(i)),null==(o=null==(a=Zh(this,Xh))?void 0:a.associateElement)||o.call(a,this)))}connectedCallback(){var e,t,i;let r=this.getAttribute(Xn);r&&(Jh(this,Xh,null==(e=this.getRootNode())?void 0:e.getElementById(r)),null==(i=null==(t=Zh(this,Xh))?void 0:t.associateElement)||i.call(t,this))}disconnectedCallback(){var e,t;null==(t=null==(e=Zh(this,Xh))?void 0:e.unassociateElement)||t.call(e,this),Jh(this,Xh,null)}};Xh=new WeakMap,uo.customElements.get("media-control-bar")||uo.customElements.define("media-control-bar",td);var id,rd=(e,t,i)=>{if(!t.has(e))throw TypeError("Cannot "+i)},sd=(e,t,i)=>(rd(e,t,"read from private field"),i?i.call(e):t.get(e)),nd=(e,t,i,r)=>(rd(e,t,"write to private field"),t.set(e,i),i),ad=co.createElement("template");ad.innerHTML="\n  <style>\n    :host {\n      font: var(--media-font,\n        var(--media-font-weight, normal)\n        var(--media-font-size, 14px) /\n        var(--media-text-content-height, var(--media-control-height, 24px))\n        var(--media-font-family, helvetica neue, segoe ui, roboto, arial, sans-serif));\n      color: var(--media-text-color, var(--media-primary-color, rgb(238 238 238)));\n      background: var(--media-text-background, var(--media-control-background, var(--media-secondary-color, rgb(20 20 30 / .7))));\n      padding: var(--media-control-padding, 10px);\n      display: inline-flex;\n      justify-content: center;\n      align-items: center;\n      vertical-align: middle;\n      box-sizing: border-box;\n      text-align: center;\n      pointer-events: auto;\n    }\n\n    \n    :host(:focus-visible) {\n      box-shadow: inset 0 0 0 2px rgb(27 127 204 / .9);\n      outline: 0;\n    }\n\n    \n    :host(:where(:focus)) {\n      box-shadow: none;\n      outline: 0;\n    }\n  </style>\n  <slot></slot>\n";var od=class extends uo.HTMLElement{constructor(){super(),((e,t,i)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,i)})(this,id,void 0),this.shadowRoot||(this.attachShadow({mode:"open"}),this.shadowRoot.appendChild(ad.content.cloneNode(!0)))}static get observedAttributes(){return[Xn]}attributeChangedCallback(e,t,i){var r,s,n,a,o;e===Xn&&(t&&(null==(s=null==(r=sd(this,id))?void 0:r.unassociateElement)||s.call(r,this),nd(this,id,null)),i&&this.isConnected&&(nd(this,id,null==(n=this.getRootNode())?void 0:n.getElementById(i)),null==(o=null==(a=sd(this,id))?void 0:a.associateElement)||o.call(a,this)))}connectedCallback(){var e,t,i;let{style:r}=qa(this.shadowRoot,":host");r.setProperty("display",`var(--media-control-display, var(--${this.localName}-display, inline-flex))`);let s=this.getAttribute(Xn);s&&(nd(this,id,null==(e=this.getRootNode())?void 0:e.getElementById(s)),null==(i=null==(t=sd(this,id))?void 0:t.associateElement)||i.call(t,this))}disconnectedCallback(){var e,t;null==(t=null==(e=sd(this,id))?void 0:e.unassociateElement)||t.call(e,this),nd(this,id,null)}};id=new WeakMap,uo.customElements.get("media-text-display")||uo.customElements.define("media-text-display",od);var ld,hd=od,dd=(e,t,i)=>{if(!t.has(e))throw TypeError("Cannot "+i)},ud=(e,t,i)=>(dd(e,t,"read from private field"),i?i.call(e):t.get(e));ld=new WeakMap,uo.customElements.get("media-duration-display")||uo.customElements.define("media-duration-display",class extends od{constructor(){super(),((e,t,i)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,i)})(this,ld,void 0),((e,t,i)=>{dd(e,t,"write to private field"),t.set(e,i)})(this,ld,this.shadowRoot.querySelector("slot")),ud(this,ld).textContent=Ba(0)}static get observedAttributes(){return[...super.observedAttributes,Jn.MEDIA_DURATION]}attributeChangedCallback(e,t,i){e===Jn.MEDIA_DURATION&&(ud(this,ld).textContent=Ba(i)),super.attributeChangedCallback(e,t,i)}get mediaDuration(){return za(this,Jn.MEDIA_DURATION)}set mediaDuration(e){Xa(this,Jn.MEDIA_DURATION,e)}});var cd,fd=(e,t,i)=>{if(!t.has(e))throw TypeError("Cannot "+i)},pd=(e,t,i)=>(fd(e,t,"read from private field"),i?i.call(e):t.get(e)),md={REMAINING:"remaining",SHOW_DURATION:"showduration",NO_TOGGLE:"notoggle"},gd=[...Object.values(md),Jn.MEDIA_CURRENT_TIME,Jn.MEDIA_DURATION,Jn.MEDIA_SEEKABLE],vd=["Enter"," "],Ed=(e,{timesSep:t="&nbsp;/&nbsp;"}={})=>{var i,r,s,n;let a=e.hasAttribute(md.REMAINING),o=e.hasAttribute(md.SHOW_DURATION),l=null!=(i=e.mediaCurrentTime)?i:0,[,h]=null!=(r=e.mediaSeekable)?r:[],d=null!=(n=null!=(s=e.mediaDuration)?s:h)?n:0,u=Ba(a?0-(d-l):l);return o?`${u}${t}${Ba(d)}`:u};cd=new WeakMap,uo.customElements.get("media-time-display")||uo.customElements.define("media-time-display",class extends od{constructor(){super(),((e,t,i)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,i)})(this,cd,void 0),((e,t,i)=>{fd(e,t,"write to private field"),t.set(e,i)})(this,cd,this.shadowRoot.querySelector("slot")),pd(this,cd).innerHTML=`${Ed(this)}`}static get observedAttributes(){return[...super.observedAttributes,...gd,"disabled"]}connectedCallback(){let{style:e}=qa(this.shadowRoot,":host(:hover:not([notoggle]))");e.setProperty("cursor","pointer"),e.setProperty("background","var(--media-control-hover-background, rgba(50 50 70 / .7))"),this.hasAttribute("disabled")||this.enable(),this.setAttribute("role","progressbar"),this.setAttribute("aria-label",ga());let t=e=>{let{key:i}=e;vd.includes(i)?this.toggleTimeDisplay():this.removeEventListener("keyup",t)};this.addEventListener("keydown",(e=>{let{metaKey:i,altKey:r,key:s}=e;i||r||!vd.includes(s)?this.removeEventListener("keyup",t):this.addEventListener("keyup",t)})),this.addEventListener("click",this.toggleTimeDisplay),super.connectedCallback()}toggleTimeDisplay(){this.noToggle||(this.hasAttribute("remaining")?this.removeAttribute("remaining"):this.setAttribute("remaining",""))}disconnectedCallback(){this.disable(),super.disconnectedCallback()}attributeChangedCallback(e,t,i){gd.includes(e)?this.update():"disabled"===e&&i!==t&&(null==i?this.enable():this.disable()),super.attributeChangedCallback(e,t,i)}enable(){this.tabIndex=0}disable(){this.tabIndex=-1}get remaining(){return Qa(this,md.REMAINING)}set remaining(e){Za(this,md.REMAINING,e)}get showDuration(){return Qa(this,md.SHOW_DURATION)}set showDuration(e){Za(this,md.SHOW_DURATION,e)}get noToggle(){return Qa(this,md.NO_TOGGLE)}set noToggle(e){Za(this,md.NO_TOGGLE,e)}get mediaDuration(){return za(this,Jn.MEDIA_DURATION)}set mediaDuration(e){Xa(this,Jn.MEDIA_DURATION,e)}get mediaCurrentTime(){return za(this,Jn.MEDIA_CURRENT_TIME)}set mediaCurrentTime(e){Xa(this,Jn.MEDIA_CURRENT_TIME,e)}get mediaSeekable(){let e=this.getAttribute(Jn.MEDIA_SEEKABLE);if(e)return e.split(":").map((e=>+e))}set mediaSeekable(e){null!=e?this.setAttribute(Jn.MEDIA_SEEKABLE,e.join(":")):this.removeAttribute(Jn.MEDIA_SEEKABLE)}update(){let e=Ed(this);(e=>{var t;let i=e.mediaCurrentTime,[,r]=null!=(t=e.mediaSeekable)?t:[],s=e.mediaDuration||r;if(null==i||null==s)return void e.setAttribute("aria-valuetext","video not loaded, unknown time.");let n=e.hasAttribute(md.REMAINING),a=e.hasAttribute(md.SHOW_DURATION),o=Fa(n?0-(s-i):i);if(!a)return void e.setAttribute("aria-valuetext",o);let l=`${o} of ${Fa(s)}`;e.setAttribute("aria-valuetext",l)})(this),e!==pd(this,cd).innerHTML&&(pd(this,cd).innerHTML=e)}});var yd=co.createElement("template");yd.innerHTML='\n  <style>\n    :host([aria-checked="true"]) slot[name=off] {\n      display: none !important;\n    }\n\n    \n    :host(:not([aria-checked="true"])) slot[name=on] {\n      display: none !important;\n    }\n  </style>\n\n  <slot name="icon">\n    <slot name="on"><svg aria-hidden="true" viewBox="0 0 26 24">\n  <path d="M22.83 5.68a2.58 2.58 0 0 0-2.3-2.5c-3.62-.24-11.44-.24-15.06 0a2.58 2.58 0 0 0-2.3 2.5c-.23 4.21-.23 8.43 0 12.64a2.58 2.58 0 0 0 2.3 2.5c3.62.24 11.44.24 15.06 0a2.58 2.58 0 0 0 2.3-2.5c.23-4.21.23-8.43 0-12.64Zm-11.39 9.45a3.07 3.07 0 0 1-1.91.57 3.06 3.06 0 0 1-2.34-1 3.75 3.75 0 0 1-.92-2.67 3.92 3.92 0 0 1 .92-2.77 3.18 3.18 0 0 1 2.43-1 2.94 2.94 0 0 1 2.13.78c.364.359.62.813.74 1.31l-1.43.35a1.49 1.49 0 0 0-1.51-1.17 1.61 1.61 0 0 0-1.29.58 2.79 2.79 0 0 0-.5 1.89 3 3 0 0 0 .49 1.93 1.61 1.61 0 0 0 1.27.58 1.48 1.48 0 0 0 1-.37 2.1 2.1 0 0 0 .59-1.14l1.4.44a3.23 3.23 0 0 1-1.07 1.69Zm7.22 0a3.07 3.07 0 0 1-1.91.57 3.06 3.06 0 0 1-2.34-1 3.75 3.75 0 0 1-.92-2.67 3.88 3.88 0 0 1 .93-2.77 3.14 3.14 0 0 1 2.42-1 3 3 0 0 1 2.16.82 2.8 2.8 0 0 1 .73 1.31l-1.43.35a1.49 1.49 0 0 0-1.51-1.21 1.61 1.61 0 0 0-1.29.58A2.79 2.79 0 0 0 15 12a3 3 0 0 0 .49 1.93 1.61 1.61 0 0 0 1.27.58 1.44 1.44 0 0 0 1-.37 2.1 2.1 0 0 0 .6-1.15l1.4.44a3.17 3.17 0 0 1-1.1 1.7Z"/>\n</svg></slot>\n    <slot name="off"><svg aria-hidden="true" viewBox="0 0 26 24">\n  <path d="M17.73 14.09a1.4 1.4 0 0 1-1 .37 1.579 1.579 0 0 1-1.27-.58A3 3 0 0 1 15 12a2.8 2.8 0 0 1 .5-1.85 1.63 1.63 0 0 1 1.29-.57 1.47 1.47 0 0 1 1.51 1.2l1.43-.34A2.89 2.89 0 0 0 19 9.07a3 3 0 0 0-2.14-.78 3.14 3.14 0 0 0-2.42 1 3.91 3.91 0 0 0-.93 2.78 3.74 3.74 0 0 0 .92 2.66 3.07 3.07 0 0 0 2.34 1 3.07 3.07 0 0 0 1.91-.57 3.17 3.17 0 0 0 1.07-1.74l-1.4-.45c-.083.43-.3.822-.62 1.12Zm-7.22 0a1.43 1.43 0 0 1-1 .37 1.58 1.58 0 0 1-1.27-.58A3 3 0 0 1 7.76 12a2.8 2.8 0 0 1 .5-1.85 1.63 1.63 0 0 1 1.29-.57 1.47 1.47 0 0 1 1.51 1.2l1.43-.34a2.81 2.81 0 0 0-.74-1.32 2.94 2.94 0 0 0-2.13-.78 3.18 3.18 0 0 0-2.43 1 4 4 0 0 0-.92 2.78 3.74 3.74 0 0 0 .92 2.66 3.07 3.07 0 0 0 2.34 1 3.07 3.07 0 0 0 1.91-.57 3.23 3.23 0 0 0 1.07-1.74l-1.4-.45a2.06 2.06 0 0 1-.6 1.07Zm12.32-8.41a2.59 2.59 0 0 0-2.3-2.51C18.72 3.05 15.86 3 13 3c-2.86 0-5.72.05-7.53.17a2.59 2.59 0 0 0-2.3 2.51c-.23 4.207-.23 8.423 0 12.63a2.57 2.57 0 0 0 2.3 2.5c1.81.13 4.67.19 7.53.19 2.86 0 5.72-.06 7.53-.19a2.57 2.57 0 0 0 2.3-2.5c.23-4.207.23-8.423 0-12.63Zm-1.49 12.53a1.11 1.11 0 0 1-.91 1.11c-1.67.11-4.45.18-7.43.18-2.98 0-5.76-.07-7.43-.18a1.11 1.11 0 0 1-.91-1.11c-.21-4.14-.21-8.29 0-12.43a1.11 1.11 0 0 1 .91-1.11C7.24 4.56 10 4.49 13 4.49s5.76.07 7.43.18a1.11 1.11 0 0 1 .91 1.11c.21 4.14.21 8.29 0 12.43Z"/>\n</svg></slot>\n  </slot>\n';var bd=e=>{e.setAttribute("aria-checked",(e=>!!e.getAttribute(Jn.MEDIA_SUBTITLES_SHOWING))(e))},Td=(e,t)=>{let i=e.getAttribute(t);return i?bl(i):[]},Sd=(e,t,i)=>{if(!i?.length)return void e.removeAttribute(t);let r=Al(i);e.getAttribute(t)!==r&&e.setAttribute(t,r)};uo.customElements.get("media-captions-button")||uo.customElements.define("media-captions-button",class extends bo{static get observedAttributes(){return[...super.observedAttributes,Jn.MEDIA_SUBTITLES_LIST,Jn.MEDIA_SUBTITLES_SHOWING]}constructor(e={}){super({slotTemplate:yd,...e}),this._captionsReady=!1}connectedCallback(){super.connectedCallback(),this.setAttribute("role","switch"),this.setAttribute("aria-label",pa()),bd(this)}attributeChangedCallback(e,t,i){super.attributeChangedCallback(e,t,i),e===Jn.MEDIA_SUBTITLES_SHOWING&&bd(this)}get mediaSubtitlesList(){return Td(this,Jn.MEDIA_SUBTITLES_LIST)}set mediaSubtitlesList(e){Sd(this,Jn.MEDIA_SUBTITLES_LIST,e)}get mediaSubtitlesShowing(){return Td(this,Jn.MEDIA_SUBTITLES_SHOWING)}set mediaSubtitlesShowing(e){Sd(this,Jn.MEDIA_SUBTITLES_SHOWING,e)}handleClick(){this.dispatchEvent(new uo.CustomEvent(Yn.MEDIA_TOGGLE_SUBTITLES_REQUEST,{composed:!0,bubbles:!0}))}});var Ad="seekoffset",_d=co.createElement("template");_d.innerHTML='\n  <slot name="icon"><svg aria-hidden="true" viewBox="0 0 20 24"><defs><style>.text{font-size:8px;font-family:Arial-BoldMT, Arial;font-weight:700;}</style></defs><text class="text value" transform="translate(8.9 19.87)">30</text><path d="M10 6V3l5.61 4L10 10.94V8a5.54 5.54 0 0 0-1.9 10.48v2.12A7.5 7.5 0 0 1 10 6Z"/></svg></slot>\n';uo.customElements.get("media-seek-forward-button")||uo.customElements.define("media-seek-forward-button",class extends bo{static get observedAttributes(){return[...super.observedAttributes,Jn.MEDIA_CURRENT_TIME,Ad]}constructor(e={}){super({slotTemplate:_d,...e})}connectedCallback(){this.seekOffset=za(this,Ad,30),super.connectedCallback()}attributeChangedCallback(e,t,i){e===Ad&&(this.seekOffset=za(this,Ad,30)),super.attributeChangedCallback(e,t,i)}get seekOffset(){return za(this,Ad,30)}set seekOffset(e){Xa(this,Ad,e),this.setAttribute("aria-label",Ca({seekOffset:this.seekOffset})),Ha(Ga(this,"icon"),this.seekOffset)}get mediaCurrentTime(){return za(this,Jn.MEDIA_CURRENT_TIME,0)}set mediaCurrentTime(e){Xa(this,Jn.MEDIA_CURRENT_TIME,e)}handleClick(){let e=this.mediaCurrentTime+this.seekOffset,t=new uo.CustomEvent(Yn.MEDIA_SEEK_REQUEST,{composed:!0,bubbles:!0,detail:e});this.dispatchEvent(t)}});var wd=co.createElement("template");wd.innerHTML=`\n  <style>\n  :host([${Jn.MEDIA_IS_FULLSCREEN}]) slot:not([name=exit]):not([name=icon]) {\n    display: none !important;\n  }\n\n  \n  :host(:not([${Jn.MEDIA_IS_FULLSCREEN}])) slot:not([name=enter]):not([name=icon]) {\n    display: none !important;\n  }\n  </style>\n\n  <slot name="icon">\n    <slot name="enter"><svg aria-hidden="true" viewBox="0 0 26 24">\n  <path d="M16 3v2.5h3.5V9H22V3h-6ZM4 9h2.5V5.5H10V3H4v6Zm15.5 9.5H16V21h6v-6h-2.5v3.5ZM6.5 15H4v6h6v-2.5H6.5V15Z"/>\n</svg></slot>\n    <slot name="exit"><svg aria-hidden="true" viewBox="0 0 26 24">\n  <path d="M18.5 6.5V3H16v6h6V6.5h-3.5ZM16 21h2.5v-3.5H22V15h-6v6ZM4 17.5h3.5V21H10v-6H4v2.5Zm3.5-11H4V9h6V3H7.5v3.5Z"/>\n</svg></slot>\n  </slot>\n`;var kd=e=>{let t=e.mediaIsFullscreen?La():ka();e.setAttribute("aria-label",t)};uo.customElements.get("media-fullscreen-button")||uo.customElements.define("media-fullscreen-button",class extends bo{static get observedAttributes(){return[...super.observedAttributes,Jn.MEDIA_IS_FULLSCREEN,Jn.MEDIA_FULLSCREEN_UNAVAILABLE]}constructor(e={}){super({slotTemplate:wd,...e})}connectedCallback(){kd(this),super.connectedCallback()}attributeChangedCallback(e,t,i){e===Jn.MEDIA_IS_FULLSCREEN&&kd(this),super.attributeChangedCallback(e,t,i)}get mediaFullscreenUnavailable(){return Ja(this,Jn.MEDIA_FULLSCREEN_UNAVAILABLE)}set mediaFullscreenUnavailable(e){eo(this,Jn.MEDIA_FULLSCREEN_UNAVAILABLE,e)}get mediaIsFullscreen(){return Qa(this,Jn.MEDIA_IS_FULLSCREEN)}set mediaIsFullscreen(e){Za(this,Jn.MEDIA_IS_FULLSCREEN,e)}handleClick(){let e=this.mediaIsFullscreen?Yn.MEDIA_EXIT_FULLSCREEN_REQUEST:Yn.MEDIA_ENTER_FULLSCREEN_REQUEST;this.dispatchEvent(new uo.CustomEvent(e,{composed:!0,bubbles:!0}))}});var{MEDIA_TIME_IS_LIVE:Ld,MEDIA_PAUSED:Rd}=Jn,{MEDIA_SEEK_TO_LIVE_REQUEST:Id,MEDIA_PLAY_REQUEST:Cd}=Yn,Dd=co.createElement("template");Dd.innerHTML=`\n  <style>\n\n  slot[name=indicator] > *,\n  :host ::slotted([slot=indicator]) {\n    \n    min-width: auto;\n    fill: var(--media-live-button-icon-color, rgb(140, 140, 140));\n    color: var(--media-live-button-icon-color, rgb(140, 140, 140));\n  }\n\n  :host([${Ld}]:not([${Rd}])) slot[name=indicator] > *,\n  :host([${Ld}]:not([${Rd}])) ::slotted([slot=indicator]) {\n    fill: var(--media-live-button-indicator-color, rgb(255, 0, 0));\n    color: var(--media-live-button-indicator-color, rgb(255, 0, 0));\n  }\n\n  :host([${Ld}]:not([${Rd}])) {\n    cursor: not-allowed;\n  }\n\n  </style>\n\n  <slot name="indicator"><svg viewBox="0 0 6 12"><circle cx="3" cy="6" r="2"></circle></svg></slot>\n  \n  <slot name="spacer">&nbsp;</slot><slot name="text">LIVE</slot>\n`;var xd=e=>{let t=e.mediaPaused||!e.mediaTimeIsLive,i=t?xa():Ma();e.setAttribute("aria-label",i),t?e.removeAttribute("aria-disabled"):e.setAttribute("aria-disabled","true")};uo.customElements.get("media-live-button")||uo.customElements.define("media-live-button",class extends bo{static get observedAttributes(){return[...super.observedAttributes,Rd,Ld]}constructor(e={}){super({slotTemplate:Dd,...e})}connectedCallback(){xd(this),super.connectedCallback()}attributeChangedCallback(e,t,i){super.attributeChangedCallback(e,t,i),xd(this)}get mediaPaused(){return Qa(this,Jn.MEDIA_PAUSED)}set mediaPaused(e){Za(this,Jn.MEDIA_PAUSED,e)}get mediaTimeIsLive(){return Qa(this,Jn.MEDIA_TIME_IS_LIVE)}set mediaTimeIsLive(e){Za(this,Jn.MEDIA_TIME_IS_LIVE,e)}handleClick(){!this.mediaPaused&&this.mediaTimeIsLive||(this.dispatchEvent(new uo.CustomEvent(Id,{composed:!0,bubbles:!0})),this.hasAttribute(Rd)&&this.dispatchEvent(new uo.CustomEvent(Cd,{composed:!0,bubbles:!0})))}});var{MEDIA_VOLUME_LEVEL:Md}=Jn,Pd='<svg aria-hidden="true" viewBox="0 0 24 24">\n  <path d="M3 9v6h4l5 5V4L7 9H3Zm13.5 3A4.5 4.5 0 0 0 14 8v8a4.47 4.47 0 0 0 2.5-4Z"/>\n</svg>',Od=co.createElement("template");Od.innerHTML=`\n  <style>\n  \n  :host(:not([${Md}])) slot:not([name=high]):not([name=icon]), \n  :host([${Md}=high]) slot:not([name=high]):not([name=icon]) {\n    display: none !important;\n  }\n\n  :host([${Md}=off]) slot:not([name=off]):not([name=icon]) {\n    display: none !important;\n  }\n\n  :host([${Md}=low]) slot:not([name=low]):not([name=icon]) {\n    display: none !important;\n  }\n\n  :host([${Md}=medium]) slot:not([name=medium]):not([name=icon]) {\n    display: none !important;\n  }\n  </style>\n\n  <slot name="icon">\n    <slot name="off"><svg aria-hidden="true" viewBox="0 0 24 24">\n  <path d="M16.5 12A4.5 4.5 0 0 0 14 8v2.18l2.45 2.45a4.22 4.22 0 0 0 .05-.63Zm2.5 0a6.84 6.84 0 0 1-.54 2.64L20 16.15A8.8 8.8 0 0 0 21 12a9 9 0 0 0-7-8.77v2.06A7 7 0 0 1 19 12ZM4.27 3 3 4.27 7.73 9H3v6h4l5 5v-6.73l4.25 4.25A6.92 6.92 0 0 1 14 18.7v2.06A9 9 0 0 0 17.69 19l2 2.05L21 19.73l-9-9L4.27 3ZM12 4 9.91 6.09 12 8.18V4Z"/>\n</svg></slot>\n    <slot name="low">${Pd}</slot>\n    <slot name="medium">${Pd}</slot>\n    <slot name="high"><svg aria-hidden="true" viewBox="0 0 24 24">\n  <path d="M3 9v6h4l5 5V4L7 9H3Zm13.5 3A4.5 4.5 0 0 0 14 8v8a4.47 4.47 0 0 0 2.5-4ZM14 3.23v2.06a7 7 0 0 1 0 13.42v2.06a9 9 0 0 0 0-17.54Z"/>\n</svg></slot>\n  </slot>\n`;var Ud=e=>{let t="off"===e.mediaVolumeLevel?Ta():ba();e.setAttribute("aria-label",t)};uo.customElements.get("media-mute-button")||uo.customElements.define("media-mute-button",class extends bo{static get observedAttributes(){return[...super.observedAttributes,Jn.MEDIA_VOLUME_LEVEL]}constructor(e={}){super({slotTemplate:Od,...e})}connectedCallback(){Ud(this),super.connectedCallback()}attributeChangedCallback(e,t,i){e===Jn.MEDIA_VOLUME_LEVEL&&Ud(this),super.attributeChangedCallback(e,t,i)}get mediaVolumeLevel(){return Ja(this,Jn.MEDIA_VOLUME_LEVEL)}set mediaVolumeLevel(e){eo(this,Jn.MEDIA_VOLUME_LEVEL,e)}handleClick(){let e="off"===this.mediaVolumeLevel?Yn.MEDIA_UNMUTE_REQUEST:Yn.MEDIA_MUTE_REQUEST;this.dispatchEvent(new uo.CustomEvent(e,{composed:!0,bubbles:!0}))}});var Nd='<svg aria-hidden="true" viewBox="0 0 28 24">\n  <path d="M24 3H4a1 1 0 0 0-1 1v16a1 1 0 0 0 1 1h20a1 1 0 0 0 1-1V4a1 1 0 0 0-1-1Zm-1 16H5V5h18v14Zm-3-8h-7v5h7v-5Z"/>\n</svg>',$d=co.createElement("template");$d.innerHTML=`\n  <style>\n  :host([${Jn.MEDIA_IS_PIP}]) slot:not([name=exit]):not([name=icon]) {\n    display: none !important;\n  }\n\n  \n  :host(:not([${Jn.MEDIA_IS_PIP}])) slot:not([name=enter]):not([name=icon]) {\n    display: none !important;\n  }\n  </style>\n\n  <slot name="icon">\n    <slot name="enter">${Nd}</slot>\n    <slot name="exit">${Nd}</slot>\n  </slot>\n`;var Fd=e=>{let t=e.mediaIsPip?Ia():Ra();e.setAttribute("aria-label",t)};uo.customElements.get("media-pip-button")||uo.customElements.define("media-pip-button",class extends bo{static get observedAttributes(){return[...super.observedAttributes,Jn.MEDIA_IS_PIP,Jn.MEDIA_PIP_UNAVAILABLE]}constructor(e={}){super({slotTemplate:$d,...e})}connectedCallback(){Fd(this),super.connectedCallback()}attributeChangedCallback(e,t,i){e===Jn.MEDIA_IS_PIP&&Fd(this),super.attributeChangedCallback(e,t,i)}get mediaPipUnavailable(){return Ja(this,Jn.MEDIA_PIP_UNAVAILABLE)}set mediaPipUnavailable(e){eo(this,Jn.MEDIA_PIP_UNAVAILABLE,e)}get mediaIsPip(){return Qa(this,Jn.MEDIA_IS_PIP)}set mediaIsPip(e){Za(this,Jn.MEDIA_IS_PIP,e)}handleClick(){let e=this.mediaIsPip?Yn.MEDIA_EXIT_PIP_REQUEST:Yn.MEDIA_ENTER_PIP_REQUEST;this.dispatchEvent(new uo.CustomEvent(e,{composed:!0,bubbles:!0}))}});var Bd=co.createElement("template");Bd.innerHTML=`\n  <style>\n  :host([${Jn.MEDIA_PAUSED}]) slot[name=pause] {\n    display: none !important;\n  }\n\n  :host(:not([${Jn.MEDIA_PAUSED}])) slot[name=play] {\n    display: none !important;\n  }\n  </style>\n\n  <slot name="icon">\n    <slot name="play"><svg aria-hidden="true" viewBox="0 0 24 24">\n  <path d="m6 21 15-9L6 3v18Z"/>\n</svg></slot>\n    <slot name="pause"><svg aria-hidden="true" viewBox="0 0 24 24">\n  <path d="M6 20h4V4H6v16Zm8-16v16h4V4h-4Z"/>\n</svg></slot>\n  </slot>\n`;var Hd=e=>{let t=e.mediaPaused?Ea():ya();e.setAttribute("aria-label",t)};uo.customElements.get("media-play-button")||uo.customElements.define("media-play-button",class extends bo{static get observedAttributes(){return[...super.observedAttributes,Jn.MEDIA_PAUSED,Jn.MEDIA_ENDED]}constructor(e={}){super({slotTemplate:Bd,...e})}connectedCallback(){Hd(this),super.connectedCallback()}attributeChangedCallback(e,t,i){e===Jn.MEDIA_PAUSED&&Hd(this),super.attributeChangedCallback(e,t,i)}get mediaPaused(){return Qa(this,Jn.MEDIA_PAUSED)}set mediaPaused(e){Za(this,Jn.MEDIA_PAUSED,e)}handleClick(){let e=this.mediaPaused?Yn.MEDIA_PLAY_REQUEST:Yn.MEDIA_PAUSE_REQUEST;this.dispatchEvent(new uo.CustomEvent(e,{composed:!0,bubbles:!0}))}});var Gd,jd=(e,t,i)=>(((e,t,i)=>{if(!t.has(e))throw TypeError("Cannot "+i)})(e,t,"read from private field"),i?i.call(e):t.get(e)),Vd="rates",Kd=[1,1.2,1.5,1.7,2],Wd=co.createElement("template");Wd.innerHTML='\n  <style>\n    :host {\n      min-width: 5ch;\n      padding: var(--media-button-padding, var(--media-control-padding, 10px 5px));\n    }\n  </style>\n  <slot name="icon"></slot>\n';Gd=new WeakMap,uo.customElements.get("media-playback-rate-button")||uo.customElements.define("media-playback-rate-button",class extends bo{constructor(e={}){super({slotTemplate:Wd,...e}),((e,t,i)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,i)})(this,Gd,new El(this,Vd,{defaultValue:Kd})),this.container=this.shadowRoot.querySelector('slot[name="icon"]'),this.container.innerHTML="1x"}static get observedAttributes(){return[...super.observedAttributes,Jn.MEDIA_PLAYBACK_RATE,Vd]}attributeChangedCallback(e,t,i){if(super.attributeChangedCallback(e,t,i),e===Vd&&(jd(this,Gd).value=i),e===Jn.MEDIA_PLAYBACK_RATE){let e=i?+i:Number.NaN,t=Number.isNaN(e)?1:e;this.container.innerHTML=`${t}x`,this.setAttribute("aria-label",ma({playbackRate:t}))}}get rates(){return jd(this,Gd)}set rates(e){e?Array.isArray(e)&&(jd(this,Gd).value=e.join(" ")):jd(this,Gd).value=""}get mediaPlaybackRate(){return za(this,Jn.MEDIA_PLAYBACK_RATE,1)}set mediaPlaybackRate(e){Xa(this,Jn.MEDIA_PLAYBACK_RATE,e)}handleClick(){var e,t;let i=Array.from(this.rates.values(),(e=>+e)).sort(((e,t)=>e-t)),r=null!=(t=null!=(e=i.find((e=>e>this.mediaPlaybackRate)))?e:i[0])?t:1,s=new uo.CustomEvent(Yn.MEDIA_PLAYBACK_RATE_REQUEST,{composed:!0,bubbles:!0,detail:r});this.dispatchEvent(s)}});var qd="placeholdersrc",Yd="src",zd=co.createElement("template");zd.innerHTML='\n  <style>\n    :host {\n      pointer-events: none;\n      display: var(--media-poster-image-display, inline-block);\n      box-sizing: border-box;\n    }\n\n    img {\n      max-width: 100%;\n      max-height: 100%;\n      min-width: 100%;\n      min-height: 100%;\n      background-repeat: no-repeat;\n      background-position: var(--media-poster-image-background-position, var(--media-object-position, center));\n      background-size: var(--media-poster-image-background-size, var(--media-object-fit, contain));\n      object-fit: var(--media-object-fit, contain);\n      object-position: var(--media-object-position, center);\n    }\n  </style>\n\n  <img part="poster img" aria-hidden="true" id="image"/>\n';var Xd=class extends uo.HTMLElement{static get observedAttributes(){return[qd,Yd]}constructor(){super(),this.shadowRoot||(this.attachShadow({mode:"open"}),this.shadowRoot.appendChild(zd.content.cloneNode(!0))),this.image=this.shadowRoot.querySelector("#image")}attributeChangedCallback(e,t,i){e===Yd&&(null==i?this.image.removeAttribute(Yd):this.image.setAttribute(Yd,i)),e===qd&&(null==i?(e=>{e.style.removeProperty("background-image")})(this.image):((e,t)=>{e.style["background-image"]=`url('${t}')`})(this.image,i))}get placeholderSrc(){return Ja(this,qd)}set placeholderSrc(e){eo(this,Yd,e)}get src(){return Ja(this,Yd)}set src(e){eo(this,Yd,e)}};uo.customElements.get("media-poster-image")||uo.customElements.define("media-poster-image",Xd);var Qd="seekoffset",Zd=co.createElement("template");Zd.innerHTML='\n  <slot name="icon"><svg aria-hidden="true" viewBox="0 0 20 24"><defs><style>.text{font-size:8px;font-family:Arial-BoldMT, Arial;font-weight:700;}</style></defs><text class="text value" transform="translate(2.18 19.87)">30</text><path d="M10 6V3L4.37 7 10 10.94V8a5.54 5.54 0 0 1 1.9 10.48v2.12A7.5 7.5 0 0 0 10 6Z"/></svg></slot>\n';uo.customElements.get("media-seek-backward-button")||uo.customElements.define("media-seek-backward-button",class extends bo{static get observedAttributes(){return[...super.observedAttributes,Jn.MEDIA_CURRENT_TIME,Qd]}constructor(e={}){super({slotTemplate:Zd,...e})}connectedCallback(){this.seekOffset=za(this,Qd,30),super.connectedCallback()}attributeChangedCallback(e,t,i){e===Qd&&(this.seekOffset=za(this,Qd,30)),super.attributeChangedCallback(e,t,i)}get seekOffset(){return za(this,Qd,30)}set seekOffset(e){Xa(this,Qd,e),this.setAttribute("aria-label",Da({seekOffset:this.seekOffset})),Ha(Ga(this,"icon"),this.seekOffset)}get mediaCurrentTime(){return za(this,Jn.MEDIA_CURRENT_TIME,0)}set mediaCurrentTime(e){Xa(this,Jn.MEDIA_CURRENT_TIME,e)}handleClick(){let e=Math.max(this.mediaCurrentTime-this.seekOffset,0),t=new uo.CustomEvent(Yn.MEDIA_SEEK_REQUEST,{composed:!0,bubbles:!0,detail:e});this.dispatchEvent(t)}});var Jd,eu=(e,t,i)=>{if(!t.has(e))throw TypeError("Cannot "+i)},tu=(e,t,i)=>(eu(e,t,"read from private field"),i?i.call(e):t.get(e));Jd=new WeakMap,uo.customElements.get("media-preview-time-display")||uo.customElements.define("media-preview-time-display",class extends od{constructor(){super(),((e,t,i)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,i)})(this,Jd,void 0),((e,t,i)=>{eu(e,t,"write to private field"),t.set(e,i)})(this,Jd,this.shadowRoot.querySelector("slot")),tu(this,Jd).textContent=Ba(0)}static get observedAttributes(){return[...super.observedAttributes,Jn.MEDIA_PREVIEW_TIME]}attributeChangedCallback(e,t,i){super.attributeChangedCallback(e,t,i),e===Jn.MEDIA_PREVIEW_TIME&&null!=i&&(tu(this,Jd).textContent=Ba(i))}get mediaPreviewTime(){return za(this,Jn.MEDIA_PREVIEW_TIME)}set mediaPreviewTime(e){Xa(this,Jn.MEDIA_PREVIEW_TIME,e)}});var iu,ru=(e,t,i)=>{if(!t.has(e))throw TypeError("Cannot "+i)},su=(e,t,i)=>(ru(e,t,"read from private field"),i?i.call(e):t.get(e)),nu=(e,t,i,r)=>(ru(e,t,"write to private field"),t.set(e,i),i),au=co.createElement("template");au.innerHTML='\n  <style>\n    :host {\n      box-sizing: border-box;\n      display: var(--media-control-display, var(--media-preview-thumbnail-display, inline-block));\n      overflow: hidden;\n    }\n\n    img {\n      display: none;\n      position: relative;\n    }\n  </style>\n  <img crossorigin loading="eager" decoding="async">\n';var ou=class extends uo.HTMLElement{constructor(){super(),((e,t,i)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,i)})(this,iu,void 0),this.shadowRoot||(this.attachShadow({mode:"open"}),this.shadowRoot.appendChild(au.content.cloneNode(!0)))}static get observedAttributes(){return[Xn,Jn.MEDIA_PREVIEW_IMAGE,Jn.MEDIA_PREVIEW_COORDS]}connectedCallback(){var e,t,i;let r=this.getAttribute(Xn);r&&(nu(this,iu,null==(e=this.getRootNode())?void 0:e.getElementById(r)),null==(i=null==(t=su(this,iu))?void 0:t.associateElement)||i.call(t,this))}disconnectedCallback(){var e,t;null==(t=null==(e=su(this,iu))?void 0:e.unassociateElement)||t.call(e,this),nu(this,iu,null)}attributeChangedCallback(e,t,i){var r,s,n,a,o;[Jn.MEDIA_PREVIEW_IMAGE,Jn.MEDIA_PREVIEW_COORDS].includes(e)&&this.update(),e===Xn&&(t&&(null==(s=null==(r=su(this,iu))?void 0:r.unassociateElement)||s.call(r,this),nu(this,iu,null)),i&&this.isConnected&&(nu(this,iu,null==(n=this.getRootNode())?void 0:n.getElementById(i)),null==(o=null==(a=su(this,iu))?void 0:a.associateElement)||o.call(a,this)))}get mediaPreviewImage(){return Ja(this,Jn.MEDIA_PREVIEW_IMAGE)}set mediaPreviewImage(e){eo(this,Jn.MEDIA_PREVIEW_IMAGE,e)}get mediaPreviewCoords(){let e=this.getAttribute(Jn.MEDIA_PREVIEW_COORDS);if(e)return e.split(/\s+/).map((e=>+e))}set mediaPreviewCoords(e){e?this.setAttribute(Jn.MEDIA_PREVIEW_COORDS,e.join(" ")):this.removeAttribute(Jn.MEDIA_PREVIEW_COORDS)}update(){let e=this.mediaPreviewCoords,t=this.mediaPreviewImage;if(!e||!t)return;let[i,r,s,n]=e,a=t.split("#")[0],o=getComputedStyle(this),{maxWidth:l,maxHeight:h,minWidth:d,minHeight:u}=o,c=Math.min(parseInt(l)/s,parseInt(h)/n),f=Math.max(parseInt(d)/s,parseInt(u)/n),p=c<1,m=p?c:f>1?f:1,{style:g}=qa(this.shadowRoot,":host"),v=qa(this.shadowRoot,"img").style,E=this.shadowRoot.querySelector("img"),y=p?"min":"max";g.setProperty(`${y}-width`,"initial","important"),g.setProperty(`${y}-height`,"initial","important"),g.width=s*m+"px",g.height=n*m+"px";let b=()=>{v.width=this.imgWidth*m+"px",v.height=this.imgHeight*m+"px",v.display="block"};E.src!==a&&(E.onload=()=>{this.imgWidth=E.naturalWidth,this.imgHeight=E.naturalHeight,b()},E.src=a,b()),b(),v.transform=`translate(-${i*m}px, -${r*m}px)`}};iu=new WeakMap,uo.customElements.get("media-preview-thumbnail")||uo.customElements.define("media-preview-thumbnail",ou);var lu,hu=(e,t,i)=>{if(!t.has(e))throw TypeError("Cannot "+i)},du=(e,t,i)=>(hu(e,t,"read from private field"),i?i.call(e):t.get(e));lu=new WeakMap,uo.customElements.get("media-preview-chapter-display")||uo.customElements.define("media-preview-chapter-display",class extends hd{constructor(){super(),((e,t,i)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,i)})(this,lu,void 0),((e,t,i)=>{hu(e,t,"write to private field"),t.set(e,i)})(this,lu,this.shadowRoot.querySelector("slot"))}static get observedAttributes(){return[...super.observedAttributes,Jn.MEDIA_PREVIEW_CHAPTER]}attributeChangedCallback(e,t,i){if(super.attributeChangedCallback(e,t,i),e===Jn.MEDIA_PREVIEW_CHAPTER&&i!==t){if(null==i)return du(this,lu).textContent="",void this.removeAttribute("aria-valuetext");du(this,lu).textContent=i,this.setAttribute("aria-valuetext",`chapter: ${i}`)}}get mediaPreviewChapter(){return Ja(this,Jn.MEDIA_PREVIEW_CHAPTER)}set mediaPreviewChapter(e){eo(this,Jn.MEDIA_PREVIEW_CHAPTER,e)}});var uu,cu,fu,pu,mu,gu,vu,Eu,yu,bu,Tu=(e,t,i)=>{if(!t.has(e))throw TypeError("Cannot "+i)},Su=(e,t,i)=>(Tu(e,t,"read from private field"),t.get(e)),Au=(e,t,i)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,i)},_u=(e,t,i,r)=>(Tu(e,t,"write to private field"),t.set(e,i),i),wu=class{constructor(e,t,i){Au(this,uu,void 0),Au(this,cu,void 0),Au(this,fu,void 0),Au(this,pu,void 0),Au(this,mu,void 0),Au(this,gu,void 0),Au(this,vu,void 0),Au(this,Eu,void 0),Au(this,yu,0),Au(this,bu,((e=performance.now())=>{_u(this,yu,requestAnimationFrame(Su(this,bu))),_u(this,pu,performance.now()-Su(this,fu));let t=1e3/this.fps;if(Su(this,pu)>t){_u(this,fu,e-Su(this,pu)%t);let i=1e3/((e-Su(this,cu))/++((e,t)=>({set _(i){_u(e,t,i)},get _(){return Su(e,t)}}))(this,mu)._),r=(e-Su(this,gu))/1e3/this.duration,s=Su(this,vu)+r*this.playbackRate;s-Su(this,uu).valueAsNumber>0?_u(this,Eu,this.playbackRate/this.duration/i):(_u(this,Eu,.995*Su(this,Eu)),s=Su(this,uu).valueAsNumber+Su(this,Eu)),this.callback(s)}})),_u(this,uu,e),this.callback=t,this.fps=i}start(){0===Su(this,yu)&&(_u(this,fu,performance.now()),_u(this,cu,Su(this,fu)),_u(this,mu,0),Su(this,bu).call(this))}stop(){0!==Su(this,yu)&&(cancelAnimationFrame(Su(this,yu)),_u(this,yu,0))}update({start:e,duration:t,playbackRate:i}){let r=e-Su(this,uu).valueAsNumber;(r>0||r<-.03)&&this.callback(e),_u(this,vu,e),_u(this,gu,performance.now()),this.duration=t,this.playbackRate=i}};uu=new WeakMap,cu=new WeakMap,fu=new WeakMap,pu=new WeakMap,mu=new WeakMap,gu=new WeakMap,vu=new WeakMap,Eu=new WeakMap,yu=new WeakMap,bu=new WeakMap;var ku,Lu,Ru,Iu,Cu,Du,xu,Mu,Pu,Ou,Uu,Nu,$u,Fu,Bu,Hu,Gu,ju,Vu,Ku,Wu,qu,Yu=(e,t,i)=>{if(!t.has(e))throw TypeError("Cannot "+i)},zu=(e,t,i)=>(Yu(e,t,"read from private field"),i?i.call(e):t.get(e)),Xu=(e,t,i)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,i)},Qu=(e,t,i,r)=>(Yu(e,t,"write to private field"),t.set(e,i),i),Zu=(e,t,i)=>(Yu(e,t,"access private method"),i),Ju=co.createElement("template");Ju.innerHTML=`\n  <style>\n    :host {\n      --media-preview-border-radius: 3px;\n      --media-box-padding-left: 10px;\n      --media-box-padding-right: 10px;\n    }\n\n    #highlight {\n      background: var(--media-time-range-buffered-color, rgb(255 255 255 / .4));\n    }\n\n    #preview-rail,\n    #current-rail {\n      \n      width: 1%;\n      position: absolute;\n      left: 0;\n      bottom: 100%;\n      pointer-events: none;\n      will-change: transform;\n    }\n\n    [part~="box"] {\n      \n      position: absolute;\n      bottom: 100%;\n      display: flex;\n      flex-direction: column;\n      align-items: center;\n      transform: translateX(-50%);\n    }\n\n    [part~="preview-box"] {\n      transition-property: var(--media-preview-transition-property, visibility, opacity);\n      transition-duration: var(--media-preview-transition-duration-out, .25s);\n      transition-delay: var(--media-preview-transition-delay-out, 0s);\n      visibility: hidden;\n      opacity: 0;\n    }\n\n    :host(:is([${Jn.MEDIA_PREVIEW_IMAGE}], [${Jn.MEDIA_PREVIEW_TIME}])[dragging]) [part~="preview-box"] {\n      transition-duration: var(--media-preview-transition-duration-in, .5s);\n      transition-delay: var(--media-preview-transition-delay-in, .25s);\n      visibility: visible;\n      opacity: 1;\n    }\n\n    @media (hover: hover) {\n      :host(:is([${Jn.MEDIA_PREVIEW_IMAGE}], [${Jn.MEDIA_PREVIEW_TIME}]):hover) [part~="preview-box"] {\n        transition-duration: var(--media-preview-transition-duration-in, .5s);\n        transition-delay: var(--media-preview-transition-delay-in, .25s);\n        visibility: visible;\n        opacity: 1;\n      }\n    }\n\n    media-preview-thumbnail,\n    ::slotted(media-preview-thumbnail) {\n      visibility: hidden;\n      \n      transition: visibility 0s .25s;\n      transition-delay: calc(var(--media-preview-transition-delay-out, 0s) + var(--media-preview-transition-duration-out, .25s));\n      background: var(--media-preview-thumbnail-background, var(--media-preview-background, var(--media-control-background, var(--media-secondary-color, rgb(20 20 30 / .7)))));\n      box-shadow: var(--media-preview-thumbnail-box-shadow, 0 0 4px rgb(0 0 0 / .2));\n      max-width: var(--media-preview-thumbnail-max-width, 180px);\n      max-height: var(--media-preview-thumbnail-max-height, 160px);\n      min-width: var(--media-preview-thumbnail-min-width, 120px);\n      min-height: var(--media-preview-thumbnail-min-height, 80px);\n      border: var(--media-preview-thumbnail-border);\n      border-radius: var(--media-preview-thumbnail-border-radius,\n        var(--media-preview-border-radius) var(--media-preview-border-radius) 0 0);\n    }\n\n    :host([${Jn.MEDIA_PREVIEW_IMAGE}][dragging]) media-preview-thumbnail,\n    :host([${Jn.MEDIA_PREVIEW_IMAGE}][dragging]) ::slotted(media-preview-thumbnail) {\n      transition-delay: var(--media-preview-transition-delay-in, .25s);\n      visibility: visible;\n    }\n\n    @media (hover: hover) {\n      :host([${Jn.MEDIA_PREVIEW_IMAGE}]:hover) media-preview-thumbnail,\n      :host([${Jn.MEDIA_PREVIEW_IMAGE}]:hover) ::slotted(media-preview-thumbnail) {\n        transition-delay: var(--media-preview-transition-delay-in, .25s);\n        visibility: visible;\n      }\n\n      :host([${Jn.MEDIA_PREVIEW_TIME}]:hover) {\n        --media-time-range-hover-display: block;\n      }\n    }\n\n    media-preview-chapter-display,\n    ::slotted(media-preview-chapter-display) {\n      display: none;\n      line-height: 1.3;\n      min-width: 0;\n      \n      transition: min-width 0s, border-radius 0s, margin 0s, padding 0s;\n      transition-delay: calc(var(--media-preview-transition-delay-out, 0s) + var(--media-preview-transition-duration-out, .25s));\n      background: var(--media-preview-chapter-background, var(--media-preview-background, var(--media-control-background, var(--media-secondary-color, rgb(20 20 30 / .7)))));\n      border-radius: var(--media-preview-chapter-border-radius,\n        var(--media-preview-border-radius) var(--media-preview-border-radius)\n        var(--media-preview-border-radius) var(--media-preview-border-radius));\n      padding: var(--media-preview-chapter-padding, 4px 10px);\n      margin: var(--media-preview-chapter-margin, 0 0 5px);\n      text-shadow: var(--media-preview-chapter-text-shadow, 0 0 4px rgb(0 0 0 / .75));\n    }\n\n    :host([${Jn.MEDIA_PREVIEW_IMAGE}]) media-preview-chapter-display,\n    :host([${Jn.MEDIA_PREVIEW_IMAGE}]) ::slotted(media-preview-chapter-display) {\n      transition-delay: var(--media-preview-transition-delay-in, .25s);\n      border-radius: var(--media-preview-chapter-border-radius, 0);\n      padding: var(--media-preview-chapter-padding, 4px 10px 0);\n      margin: var(--media-preview-chapter-margin, 0);\n      min-width: 100%;\n    }\n\n    media-preview-chapter-display[${Jn.MEDIA_PREVIEW_CHAPTER}]:not([${Jn.MEDIA_PREVIEW_CHAPTER}=""]),\n    ::slotted(media-preview-chapter-display[${Jn.MEDIA_PREVIEW_CHAPTER}]:not([${Jn.MEDIA_PREVIEW_CHAPTER}=""])) {\n      display: initial;\n    }\n\n    media-preview-time-display,\n    ::slotted(media-preview-time-display) {\n      line-height: 1.3;\n      min-width: 0;\n      \n      transition: min-width 0s, border-radius 0s;\n      transition-delay: calc(var(--media-preview-transition-delay-out, 0s) + var(--media-preview-transition-duration-out, .25s));\n      background: var(--media-preview-time-background, var(--media-preview-background, var(--media-control-background, var(--media-secondary-color, rgb(20 20 30 / .7)))));\n      border-radius: var(--media-preview-time-border-radius,\n        var(--media-preview-border-radius) var(--media-preview-border-radius)\n        var(--media-preview-border-radius) var(--media-preview-border-radius));\n      padding: var(--media-preview-time-padding, 4px 10px);\n      margin: var(--media-preview-time-margin, 0 0 10px);\n      text-shadow: var(--media-preview-time-text-shadow, 0 0 4px rgb(0 0 0 / .75));\n    }\n\n    :host([${Jn.MEDIA_PREVIEW_IMAGE}]) media-preview-time-display,\n    :host([${Jn.MEDIA_PREVIEW_IMAGE}]) ::slotted(media-preview-time-display) {\n      transition-delay: var(--media-preview-transition-delay-in, .25s);\n      border-radius: var(--media-preview-time-border-radius,\n        0 0 var(--media-preview-border-radius) var(--media-preview-border-radius));\n      min-width: 100%;\n    }\n\n    :host([${Jn.MEDIA_PREVIEW_TIME}]:hover) {\n      --media-time-range-hover-display: block;\n    }\n  </style>\n  <div id="preview-rail">\n    <slot name="preview" part="box preview-box">\n      <media-preview-thumbnail></media-preview-thumbnail>\n      <media-preview-chapter-display></media-preview-chapter-display>\n      <media-preview-time-display></media-preview-time-display>\n    </slot>\n  </div>\n  <div id="current-rail">\n    <slot name="current" part="box current-box">\n      \n    </slot>\n  </div>\n`;var ec=(e,t=e.mediaCurrentTime)=>{if(Number.isNaN(e.mediaSeekableEnd))return 0;let i=(t-e.mediaSeekableStart)/(e.mediaSeekableEnd-e.mediaSeekableStart);return Math.max(0,Math.min(i,1))},tc=(e,t=e.range.valueAsNumber)=>Number.isNaN(e.mediaSeekableEnd)?0:t*(e.mediaSeekableEnd-e.mediaSeekableStart)+e.mediaSeekableStart;ku=new WeakMap,Lu=new WeakMap,Ru=new WeakMap,Iu=new WeakMap,Cu=new WeakMap,Du=new WeakMap,xu=new WeakMap,Mu=new WeakMap,Pu=new WeakMap,Ou=new WeakSet,Uu=function(){Zu(this,Nu,$u).call(this)?zu(this,Lu).start():zu(this,Lu).stop()},Nu=new WeakSet,$u=function(){return this.isConnected&&!this.mediaPaused&&!this.mediaLoading&&!this.mediaEnded&&this.mediaDuration>0&&function(e,t=3){if(e.checkVisibility)return e.checkVisibility({checkOpacity:!0,checkVisibilityCSS:!0});let i=e;for(;i&&t>0;){let e=getComputedStyle(i);if("0"===e.opacity||"hidden"===e.visibility||"none"===e.display)return!1;i=i.parentElement,t--}return!0}(this)},Fu=new WeakMap,Bu=new WeakSet,Hu=function(e,t){var i;let r=100*t*100+"%",s=e.offsetWidth;if(!s)return r;let n=null!=(i=this.getAttribute("bounds")?Va(this,`#${this.getAttribute("bounds")}`):this.parentElement)?i:this,a=this.range.getBoundingClientRect(),o=n.getBoundingClientRect(),l=(zu(this,xu)-(a.left-o.left-s/2))/a.width*100,h=(o.right-a.left-s/2-zu(this,Mu))/a.width*100;return Number.isNaN(l)||(r=`max(${100*l}%, ${r})`),Number.isNaN(h)||(r=`min(${r}, ${100*h}%)`),r},Gu=new WeakSet,ju=function(e){let t=[...zu(this,Ru)].some((t=>e.composedPath().includes(t)));if(!this.dragging&&(t||!e.composedPath().includes(this)))return void Zu(this,Vu,Ku).call(this,null);let i=this.mediaDuration;if(!i)return;let r=this.range.getBoundingClientRect(),s=(e.clientX-r.left)/r.width;s=Math.max(0,Math.min(1,s));let n=Zu(this,Bu,Hu).call(this,zu(this,Cu),s),{style:a}=qa(this.shadowRoot,"#preview-rail");a.transform=`translateX(${n})`;let o=Math.round(zu(this,Iu))-Math.round(s*i);Math.abs(o)<1||(Qu(this,Iu,s*i),Zu(this,Vu,Ku).call(this,zu(this,Iu)))},Vu=new WeakSet,Ku=function(e){this.dispatchEvent(new uo.CustomEvent(Yn.MEDIA_PREVIEW_REQUEST,{composed:!0,bubbles:!0,detail:e}))},Wu=new WeakSet,qu=function(){zu(this,Lu).stop();let e=tc(this);this.dispatchEvent(new uo.CustomEvent(Yn.MEDIA_SEEK_REQUEST,{composed:!0,bubbles:!0,detail:e}))},uo.customElements.get("media-time-range")||uo.customElements.define("media-time-range",class extends zh{constructor(){super(),Xu(this,Ou),Xu(this,Nu),Xu(this,Bu),Xu(this,Gu),Xu(this,Vu),Xu(this,Wu),Xu(this,ku,void 0),Xu(this,Lu,void 0),Xu(this,Ru,void 0),Xu(this,Iu,void 0),Xu(this,Cu,void 0),Xu(this,Du,void 0),Xu(this,xu,void 0),Xu(this,Mu,void 0),Xu(this,Pu,void 0),Xu(this,Fu,(e=>{this.dragging||(this.range.valueAsNumber=e,this.updateBar())})),this.container.appendChild(Ju.content.cloneNode(!0)),Qu(this,Ru,this.shadowRoot.querySelectorAll('[part~="box"]')),Qu(this,Cu,this.shadowRoot.querySelector('[part~="preview-box"]')),Qu(this,Du,this.shadowRoot.querySelector('[part~="current-box"]'));let e=getComputedStyle(this);Qu(this,xu,parseInt(e.getPropertyValue("--media-box-padding-left"))),Qu(this,Mu,parseInt(e.getPropertyValue("--media-box-padding-right"))),Qu(this,Lu,new wu(this.range,zu(this,Fu),60))}static get observedAttributes(){return[...super.observedAttributes,Jn.MEDIA_PAUSED,Jn.MEDIA_DURATION,Jn.MEDIA_SEEKABLE,Jn.MEDIA_CURRENT_TIME,Jn.MEDIA_PREVIEW_IMAGE,Jn.MEDIA_PREVIEW_TIME,Jn.MEDIA_PREVIEW_CHAPTER,Jn.MEDIA_BUFFERED,Jn.MEDIA_PLAYBACK_RATE,Jn.MEDIA_LOADING,Jn.MEDIA_ENDED]}connectedCallback(){var e;super.connectedCallback(),this.range.setAttribute("aria-label",fa()),Zu(this,Ou,Uu).call(this),Qu(this,ku,this.getRootNode()),null==(e=zu(this,ku))||e.addEventListener("transitionstart",this)}disconnectedCallback(){var e;super.disconnectedCallback(),Zu(this,Ou,Uu).call(this),null==(e=zu(this,ku))||e.removeEventListener("transitionstart",this),Qu(this,ku,null)}attributeChangedCallback(e,t,i){super.attributeChangedCallback(e,t,i),t!=i&&(e===Jn.MEDIA_CURRENT_TIME||e===Jn.MEDIA_PAUSED||e===Jn.MEDIA_ENDED||e===Jn.MEDIA_LOADING||e===Jn.MEDIA_DURATION||e===Jn.MEDIA_SEEKABLE?(zu(this,Lu).update({start:ec(this),duration:this.mediaSeekableEnd-this.mediaSeekableStart,playbackRate:this.mediaPlaybackRate}),Zu(this,Ou,Uu).call(this),(e=>{let t=e.range,i=Fa(+tc(e)),r=Fa(+e.mediaSeekableEnd),s=i&&r?`${i} of ${r}`:"video not loaded, unknown time.";t.setAttribute("aria-valuetext",s)})(this)):e===Jn.MEDIA_BUFFERED&&this.updateBufferedBar(),e===Jn.MEDIA_DURATION&&(this.mediaChaptersCues=zu(this,Pu)))}get mediaChaptersCues(){return zu(this,Pu)}set mediaChaptersCues(e){var t;Qu(this,Pu,e),this.updateSegments(null==(t=zu(this,Pu))?void 0:t.map((e=>({start:ec(this,e.startTime),end:ec(this,e.endTime)}))))}get mediaPaused(){return Qa(this,Jn.MEDIA_PAUSED)}set mediaPaused(e){Za(this,Jn.MEDIA_PAUSED,e)}get mediaLoading(){return Qa(this,Jn.MEDIA_LOADING)}set mediaLoading(e){Za(this,Jn.MEDIA_LOADING,e)}get mediaDuration(){return za(this,Jn.MEDIA_DURATION)}set mediaDuration(e){Xa(this,Jn.MEDIA_DURATION,e)}get mediaCurrentTime(){return za(this,Jn.MEDIA_CURRENT_TIME)}set mediaCurrentTime(e){Xa(this,Jn.MEDIA_CURRENT_TIME,e)}get mediaPlaybackRate(){return za(this,Jn.MEDIA_PLAYBACK_RATE,1)}set mediaPlaybackRate(e){Xa(this,Jn.MEDIA_PLAYBACK_RATE,e)}get mediaBuffered(){let e=this.getAttribute(Jn.MEDIA_BUFFERED);return e?e.split(" ").map((e=>e.split(":").map((e=>+e)))):[]}set mediaBuffered(e){if(!e)return void this.removeAttribute(Jn.MEDIA_BUFFERED);let t=e.map((e=>e.join(":"))).join(" ");this.setAttribute(Jn.MEDIA_BUFFERED,t)}get mediaSeekable(){let e=this.getAttribute(Jn.MEDIA_SEEKABLE);if(e)return e.split(":").map((e=>+e))}set mediaSeekable(e){null!=e?this.setAttribute(Jn.MEDIA_SEEKABLE,e.join(":")):this.removeAttribute(Jn.MEDIA_SEEKABLE)}get mediaSeekableEnd(){var e;let[,t=this.mediaDuration]=null!=(e=this.mediaSeekable)?e:[];return t}get mediaSeekableStart(){var e;let[t=0]=null!=(e=this.mediaSeekable)?e:[];return t}get mediaPreviewImage(){return Ja(this,Jn.MEDIA_PREVIEW_IMAGE)}set mediaPreviewImage(e){eo(this,Jn.MEDIA_PREVIEW_IMAGE,e)}get mediaPreviewTime(){return za(this,Jn.MEDIA_PREVIEW_TIME)}set mediaPreviewTime(e){Xa(this,Jn.MEDIA_PREVIEW_TIME,e)}get mediaEnded(){return Qa(this,Jn.MEDIA_ENDED)}set mediaEnded(e){Za(this,Jn.MEDIA_ENDED,e)}updateBar(){super.updateBar(),this.updateBufferedBar(),this.updateCurrentBox()}updateBufferedBar(){var e;let t,i=this.mediaBuffered;if(!i.length)return;if(this.mediaEnded)t=1;else{let r=this.mediaCurrentTime,[,s=this.mediaSeekableStart]=null!=(e=i.find((([e,t])=>e<=r&&r<=t)))?e:[];t=ec(this,s)}let{style:r}=qa(this.shadowRoot,"#highlight");r.setProperty("width",100*t+"%")}updateCurrentBox(){if(!zu(this,Du).assignedElements().length)return;let e=Zu(this,Bu,Hu).call(this,zu(this,Du),this.range.valueAsNumber),{style:t}=qa(this.shadowRoot,"#current-rail");t.transform=`translateX(${e})`}handleEvent(e){switch(super.handleEvent(e),e.type){case"input":Zu(this,Wu,qu).call(this);break;case"pointermove":Zu(this,Gu,ju).call(this,e);break;case"pointerup":case"pointerleave":Zu(this,Vu,Ku).call(this,null);break;case"transitionstart":ja(e.target,this)&&setTimeout((()=>Zu(this,Ou,Uu).call(this)),0)}}});var ic,rc,sc=(e,t,i)=>{if(!t.has(e))throw TypeError("Cannot "+i)},nc=(e,t,i)=>(sc(e,t,"read from private field"),i?i.call(e):t.get(e)),ac=(e,t,i)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,i)},oc=(e,t,i,r)=>(sc(e,t,"write to private field"),t.set(e,i),i),lc="loadingdelay",hc=co.createElement("template");hc.innerHTML=`\n<style>\n:host {\n  display: var(--media-control-display, var(--media-loading-indicator-display, inline-block));\n  vertical-align: middle;\n  box-sizing: border-box;\n  --_loading-indicator-delay: var(--media-loading-indicator-transition-delay, 500ms);\n}\n\n#status {\n  color: rgba(0,0,0,0);\n  width: 0px;\n  height: 0px;\n}\n\n:host slot[name=icon] > *,\n:host ::slotted([slot=icon]) {\n  opacity: var(--media-loading-indicator-opacity, 0);\n  transition: opacity 0.15s;\n}\n\n:host([${Jn.MEDIA_LOADING}]:not([${Jn.MEDIA_PAUSED}])) slot[name=icon] > *,\n:host([${Jn.MEDIA_LOADING}]:not([${Jn.MEDIA_PAUSED}])) ::slotted([slot=icon]) {\n  opacity: var(--media-loading-indicator-opacity, 1);\n  transition: opacity 0.15s var(--_loading-indicator-delay);\n}\n\n:host #status {\n  visibility: var(--media-loading-indicator-opacity, hidden);\n  transition: visibility 0.15s;\n}\n\n:host([${Jn.MEDIA_LOADING}]:not([${Jn.MEDIA_PAUSED}])) #status {\n  visibility: var(--media-loading-indicator-opacity, visible);\n  transition: visibility 0.15s var(--_loading-indicator-delay);\n}\n\nsvg, img, ::slotted(svg), ::slotted(img) {\n  width: var(--media-loading-indicator-icon-width);\n  height: var(--media-loading-indicator-icon-height, 100px);\n  fill: var(--media-icon-color, var(--media-primary-color, rgb(238 238 238)));\n  vertical-align: middle;\n}\n</style>\n\n<slot name="icon">\n<svg aria-hidden="true" viewBox="0 0 100 100">\n  <path d="M73,50c0-12.7-10.3-23-23-23S27,37.3,27,50 M30.9,50c0-10.5,8.5-19.1,19.1-19.1S69.1,39.5,69.1,50">\n    <animateTransform\n       attributeName="transform"\n       attributeType="XML"\n       type="rotate"\n       dur="1s"\n       from="0 50 50"\n       to="360 50 50"\n       repeatCount="indefinite" />\n  </path>\n</svg>\n</slot>\n<div id="status" role="status" aria-live="polite">${va()}</div>\n`;var dc=class extends uo.HTMLElement{constructor(){if(super(),ac(this,ic,void 0),ac(this,rc,500),!this.shadowRoot){let e=this.attachShadow({mode:"open"}),t=hc.content.cloneNode(!0);e.appendChild(t)}}static get observedAttributes(){return[Xn,Jn.MEDIA_PAUSED,Jn.MEDIA_LOADING,lc]}attributeChangedCallback(e,t,i){var r,s,n,a,o;e===lc&&t!==i?this.loadingDelay=Number(i):e===Xn&&(t&&(null==(s=null==(r=nc(this,ic))?void 0:r.unassociateElement)||s.call(r,this),oc(this,ic,null)),i&&this.isConnected&&(oc(this,ic,null==(n=this.getRootNode())?void 0:n.getElementById(i)),null==(o=null==(a=nc(this,ic))?void 0:a.associateElement)||o.call(a,this)))}connectedCallback(){var e,t,i;let r=this.getAttribute(Xn);r&&(oc(this,ic,null==(e=this.getRootNode())?void 0:e.getElementById(r)),null==(i=null==(t=nc(this,ic))?void 0:t.associateElement)||i.call(t,this))}disconnectedCallback(){var e,t;null==(t=null==(e=nc(this,ic))?void 0:e.unassociateElement)||t.call(e,this),oc(this,ic,null)}get loadingDelay(){return nc(this,rc)}set loadingDelay(e){oc(this,rc,e);let{style:t}=qa(this.shadowRoot,":host");t.setProperty("--_loading-indicator-delay",`var(--media-loading-indicator-transition-delay, ${e}ms)`)}get mediaPaused(){return Qa(this,Jn.MEDIA_PAUSED)}set mediaPaused(e){Za(this,Jn.MEDIA_PAUSED,e)}get mediaLoading(){return Qa(this,Jn.MEDIA_LOADING)}set mediaLoading(e){Za(this,Jn.MEDIA_LOADING,e)}};ic=new WeakMap,rc=new WeakMap,uo.customElements.get("media-loading-indicator")||uo.customElements.define("media-loading-indicator",dc);uo.customElements.get("media-volume-range")||uo.customElements.define("media-volume-range",class extends zh{static get observedAttributes(){return[...super.observedAttributes,Jn.MEDIA_VOLUME,Jn.MEDIA_MUTED,Jn.MEDIA_VOLUME_UNAVAILABLE]}constructor(){super(),this.range.addEventListener("input",(()=>{let e=this.range.value,t=new uo.CustomEvent(Yn.MEDIA_VOLUME_REQUEST,{composed:!0,bubbles:!0,detail:e});this.dispatchEvent(t)}))}connectedCallback(){super.connectedCallback(),this.range.setAttribute("aria-label",ca())}attributeChangedCallback(e,t,i){super.attributeChangedCallback(e,t,i),(e===Jn.MEDIA_VOLUME||e===Jn.MEDIA_MUTED)&&(this.range.valueAsNumber=(e=>e.mediaMuted?0:e.mediaVolume)(this),this.range.setAttribute("aria-valuetext",(({value:e})=>`${Math.round(100*e)}%`)(this.range)),this.updateBar())}get mediaVolume(){return za(this,Jn.MEDIA_VOLUME,1)}set mediaVolume(e){Xa(this,Jn.MEDIA_VOLUME,e)}get mediaMuted(){return Qa(this,Jn.MEDIA_MUTED)}set mediaMuted(e){Za(this,Jn.MEDIA_MUTED,e)}get mediaVolumeUnavailable(){return Ja(this,Jn.MEDIA_VOLUME_UNAVAILABLE)}set mediaVolumeUnavailable(e){eo(this,Jn.MEDIA_VOLUME_UNAVAILABLE,e)}});var uc,cc,fc,pc,mc,gc,vc,Ec,yc,bc,Tc,Sc,Ac,_c,wc,kc,Lc,Rc,Ic,Cc=(e,t,i)=>{if(!t.has(e))throw TypeError("Cannot "+i)},Dc=(e,t,i)=>(Cc(e,t,"read from private field"),i?i.call(e):t.get(e)),xc=(e,t,i)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,i)},Mc=(e,t,i,r)=>(Cc(e,t,"write to private field"),t.set(e,i),i),Pc=(e,t,i)=>(Cc(e,t,"access private method"),i);function Oc(e,t,i){let r=co.createElement("media-chrome-option");r.part.add("option"),r.value=t,r.selected=i;let s=co.createElement("span");return s.textContent=e,r.append(s),r}function Uc(e,t){let i=e.querySelector(`:scope > [slot="${t}"]`);return"SLOT"==i?.nodeName&&(i=i.assignedElements({flatten:!0})[0]),i?(i=i.cloneNode(!0),i.removeAttribute("slot"),i):e.shadowRoot.querySelector(`[name="${t}"] > svg`).cloneNode(!0)}var Nc=co.createElement("template");Nc.innerHTML='\n<style>\n  :host {\n    font: var(--media-font,\n      var(--media-font-weight, normal)\n      var(--media-font-size, 15px) /\n      var(--media-text-content-height, var(--media-control-height, 24px))\n      var(--media-font-family, helvetica neue, segoe ui, roboto, arial, sans-serif));\n    color: var(--media-text-color, var(--media-primary-color, rgb(238 238 238)));\n    background: var(--media-listbox-background, var(--media-control-background, var(--media-secondary-color, rgb(20 20 30 / .8))));\n    border-radius: var(--media-listbox-border-radius);\n    display: inline-flex;\n    flex-direction: column;\n    position: relative;\n    box-sizing: border-box;\n  }\n\n  ::slotted([slot="header"]) {\n    padding: .4em 1.4em;\n    border-bottom: 1px solid rgb(255 255 255 / .25);\n  }\n\n  #container {\n    gap: var(--media-listbox-gap);\n    display: flex;\n    flex-direction: var(--media-listbox-flex-direction, column);\n    overflow: hidden auto;\n    padding-block: .5em;\n  }\n\n  media-chrome-option {\n    padding-inline: .7em 1.4em;\n  }\n\n  media-chrome-option > span {\n    margin-inline: .5ch;\n  }\n\n  [part~="indicator"] {\n    fill: var(--media-option-indicator-fill, var(--media-icon-color, var(--media-primary-color, rgb(238 238 238))));\n    height: var(--media-option-indicator-height, 1.25em);\n    vertical-align: var(--media-option-indicator-vertical-align, text-top);\n  }\n\n  [part~="select-indicator"] {\n    display: var(--media-option-select-indicator-display);\n    visibility: hidden;\n  }\n\n  [aria-selected="true"] > [part~="select-indicator"] {\n    visibility: visible;\n  }\n</style>\n<style id="layout-row" media="width:0">\n\n  ::slotted([slot="header"]) {\n    padding: .4em .5em;\n  }\n\n  #container {\n    gap: var(--media-listbox-gap, .25em);\n    flex-direction: var(--media-listbox-flex-direction, row);\n    padding-inline: .5em;\n  }\n\n  media-chrome-option {\n    padding: .3em .24em;\n  }\n\n  media-chrome-option[aria-selected="true"] {\n    background: var(--media-option-selected-background, rgb(255 255 255 / .2));\n  }\n\n  [part~="select-indicator"] {\n    display: var(--media-option-select-indicator-display, none);\n  }\n</style>\n<slot name="header"></slot>\n<slot id="container"></slot>\n<slot name="select-indicator" hidden>\n<svg aria-hidden="true" viewBox="0 1 24 24" part="select-indicator indicator">\n  <path d="m10 15.17 9.193-9.191 1.414 1.414-10.606 10.606-6.364-6.364 1.414-1.414 4.95 4.95Z"/>\n</svg></slot>\n';var $c=class extends uo.HTMLElement{constructor(e={}){super(),xc(this,gc),xc(this,bc),xc(this,Sc),xc(this,_c),xc(this,kc),xc(this,Rc),xc(this,uc,void 0),xc(this,cc,""),xc(this,fc,null),xc(this,pc,!1),xc(this,mc,(e=>{this.handleClick(e)})),xc(this,Ec,(e=>{let{key:t}=e;"Escape"!==t?"Meta"!==t?Pc(this,gc,vc).call(this,e):Mc(this,pc,!1):this.removeEventListener("keyup",Dc(this,Ec))})),xc(this,yc,(e=>{let{key:t,altKey:i}=e;i?this.removeEventListener("keyup",Dc(this,Ec)):"Meta"!==t?(this.keysUsed.includes(t)&&e.preventDefault(),Dc(this,pc)&&this.keysUsed.includes(t)?Pc(this,gc,vc).call(this,e):this.addEventListener("keyup",Dc(this,Ec),{once:!0})):Mc(this,pc,!0)})),this.shadowRoot||(this.attachShadow({mode:"open"}),this.nativeEl=Nc.content.cloneNode(!0),e.slotTemplate&&this.nativeEl.append(e.slotTemplate.content.cloneNode(!0)),this.shadowRoot.append(this.nativeEl)),this.container=this.shadowRoot.querySelector("#container"),this.container.addEventListener("slotchange",(e=>{for(let t of e.target.assignedNodes({flatten:!0}))3===t.nodeType&&""===t.textContent.trim()&&t.remove()}))}static get observedAttributes(){return["disabled","style",Xn]}static formatOptionText(e){return e}formatOptionText(e,t){return this.constructor.formatOptionText(e,t)}get options(){var e;let t=this.querySelectorAll("media-chrome-option");return t.length||(t=null==(e=this.container)?void 0:e.querySelectorAll("media-chrome-option")),Array.from(t)}get selectedOptions(){return this.options.filter((e=>e.selected))}get value(){var e,t;return null!=(t=null==(e=this.selectedOptions[0])?void 0:e.value)?t:""}set value(e){let t=this.options.find((t=>t.value===e));t&&Pc(this,_c,wc).call(this,t)}focus(){var e;null==(e=this.selectedOptions[0])||e.focus()}enable(){this.addEventListener("click",Dc(this,mc)),this.addEventListener("keydown",Dc(this,yc))}disable(){this.removeEventListener("click",Dc(this,mc)),this.removeEventListener("keyup",Dc(this,Ec))}attributeChangedCallback(e,t,i){var r,s,n,a,o;"style"===e&&i!==t?Pc(this,bc,Tc).call(this):e===Xn?(t&&(null==(s=null==(r=Dc(this,uc))?void 0:r.unassociateElement)||s.call(r,this),Mc(this,uc,null)),i&&this.isConnected&&(Mc(this,uc,null==(n=this.getRootNode())?void 0:n.getElementById(i)),null==(o=null==(a=Dc(this,uc))?void 0:a.associateElement)||o.call(a,this))):"disabled"===e&&i!==t&&(null==i?this.enable():this.disable())}connectedCallback(){var e,t,i;Pc(this,bc,Tc).call(this),this.hasAttribute("disabled")||this.enable(),this.hasAttribute("role")||this.setAttribute("role","listbox");let r=this.getAttribute(Xn);r&&(Mc(this,uc,null==(e=this.getRootNode())?void 0:e.getElementById(r)),null==(i=null==(t=Dc(this,uc))?void 0:t.associateElement)||i.call(t,this))}disconnectedCallback(){var e,t;this.disable(),null==(t=null==(e=Dc(this,uc))?void 0:e.unassociateElement)||t.call(e,this),Mc(this,uc,null)}get keysUsed(){return["Enter"," ","ArrowDown","ArrowUp","Home","End"]}handleSelection(e,t){let i=Pc(this,Sc,Ac).call(this,e);i&&Pc(this,_c,wc).call(this,i,t)}handleMovement(e){let t,{key:i}=e,r=this.options,s=Pc(this,Sc,Ac).call(this,e);switch(s||(s=r.filter((e=>"0"===e.getAttribute("tabindex")))[0]),i){case"ArrowDown":t=s.nextElementSibling,t?.hasAttribute("disabled")&&(t=t.nextElementSibling);break;case"ArrowUp":t=s.previousElementSibling,t?.hasAttribute("disabled")&&(t=t.previousElementSibling);break;case"Home":t=r[0];break;case"End":t=r[r.length-1];break;default:t=Pc(this,kc,Lc).call(this,i)}t&&(r.forEach((e=>e.setAttribute("tabindex","-1"))),t.setAttribute("tabindex","0"),t.focus())}handleClick(e){let t=Pc(this,Sc,Ac).call(this,e);!t||t.hasAttribute("disabled")||(this.options.forEach((e=>e.setAttribute("tabindex","-1"))),t.setAttribute("tabindex","0"),this.handleSelection(e,this.hasAttribute("aria-multiselectable")&&"true"===this.getAttribute("aria-multiselectable")))}};uc=new WeakMap,cc=new WeakMap,fc=new WeakMap,pc=new WeakMap,mc=new WeakMap,gc=new WeakSet,vc=function(e){let{key:t}=e;"Enter"===t||" "===t?this.handleSelection(e,this.hasAttribute("aria-multiselectable")&&"true"===this.getAttribute("aria-multiselectable")):this.handleMovement(e)},Ec=new WeakMap,yc=new WeakMap,bc=new WeakSet,Tc=function(){var e;let t=this.shadowRoot.querySelector("#layout-row"),i="row"===(null==(e=getComputedStyle(this).getPropertyValue("--media-listbox-layout"))?void 0:e.trim());t.setAttribute("media",i?"":"width:0")},Sc=new WeakSet,Ac=function(e){let t=e.composedPath(),i=t.findIndex((e=>"MEDIA-CHROME-OPTION"===e.nodeName));return t[i]},_c=new WeakSet,wc=function(e,t){let i=[...this.selectedOptions];(!this.hasAttribute("aria-multiselectable")||"true"!==this.getAttribute("aria-multiselectable"))&&this.options.forEach((e=>e.selected=!1)),e.selected=!t||!e.selected,this.selectedOptions.some(((e,t)=>e!=i[t]))&&this.dispatchEvent(new Event("change",{bubbles:!0,composed:!0}))},kc=new WeakSet,Lc=function(e){Pc(this,Rc,Ic).call(this);let t=this.options,i=t.findIndex((e=>"0"===e.getAttribute("tabindex")));Mc(this,cc,Dc(this,cc)+e);let r=Dc(this,cc).split("").every((t=>t===e)),s=t.slice(i+(r?1:0)).filter((e=>e.textContent.toLowerCase().startsWith(Dc(this,cc)))),n=t.slice(0,i-(r?1:0)).filter((e=>e.textContent.toLowerCase().startsWith(Dc(this,cc)))),a=[],o=[];return r&&(a=t.slice(i+(r?1:0)).filter((t=>t.textContent.startsWith(e))),o=t.slice(0,i-(r?1:0)).filter((t=>t.textContent.startsWith(e)))),[...s,...n,...a,...o][0]},Rc=new WeakSet,Ic=function(){clearTimeout(Dc(this,fc)),Mc(this,fc,null),Mc(this,fc,setTimeout((()=>{Mc(this,cc,""),Mc(this,fc,null)}),500))},uo.customElements.get("media-chrome-listbox")||uo.customElements.define("media-chrome-listbox",$c);var Fc,Bc,Hc,Gc,jc,Vc,Kc,Wc,qc,Yc,zc,Xc,Qc,Zc,Jc,ef,tf,rf=(e,t,i)=>{if(!t.has(e))throw TypeError("Cannot "+i)},sf=(e,t,i)=>(rf(e,t,"read from private field"),i?i.call(e):t.get(e)),nf=(e,t,i)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,i)},af=(e,t,i,r)=>(rf(e,t,"write to private field"),t.set(e,i),i),of=(e,t,i)=>(rf(e,t,"access private method"),i),lf=co.createElement("template");lf.innerHTML='\n  <style>\n  :host {\n    font: var(--media-font,\n      var(--media-font-weight, normal)\n      var(--media-font-size, 15px) /\n      var(--media-text-content-height, var(--media-control-height, 24px))\n      var(--media-font-family, helvetica neue, segoe ui, roboto, arial, sans-serif));\n    color: var(--media-text-color, var(--media-primary-color, rgb(238 238 238)));\n    display: inline-flex;\n    position: relative;\n    flex-shrink: .5;\n  }\n\n  [name=listbox]::slotted(*),\n  [part=listbox] {\n    position: absolute;\n    bottom: 100%;\n    max-height: 300px;\n    transition: var(--media-selectmenu-transition-in,\n      visibility 0s, transform .15s ease-out, opacity .15s ease-out);\n    transform: var(--media-listbox-transform-in, translateY(0) scale(1));\n    visibility: visible;\n    opacity: 1;\n  }\n\n  [name=listbox][hidden]::slotted(*),\n  [hidden] [part=listbox] {\n    transition: var(--media-selectmenu-transition-out,\n      visibility .15s ease-out, transform .15s ease-out, opacity .15s ease-out);\n    transform: var(--media-listbox-transform-out, translateY(2px) scale(.99));\n    visibility: hidden;\n    opacity: 0;\n    pointer-events: none;\n  }\n\n  slot[name=listbox][hidden] {\n    display: block;\n  }\n  </style>\n\n  <slot name="button">\n    <media-chrome-button aria-haspopup="listbox" part="button">\n      <slot name="button-content"></slot>\n    </media-chrome-button>\n  </slot>\n  <slot name="listbox" hidden>\n    <media-chrome-listbox id="listbox" part="listbox">\n      <slot></slot>\n    </media-chrome-listbox>\n  </slot>\n';var hf=class extends uo.HTMLElement{constructor(){var e;super(),nf(this,zc),nf(this,Qc),nf(this,Jc),nf(this,Fc,void 0),nf(this,Bc,void 0),nf(this,Hc,void 0),nf(this,Gc,void 0),nf(this,jc,void 0),nf(this,Vc,(e=>{let{key:t}=e;this.keysUsed.includes(t)?!e.composedPath().includes(sf(this,Bc))||"Enter"!==t&&" "!==t?"Escape"===t&&of(this,Jc,ef).call(this):of(this,zc,Xc).call(this):this.removeEventListener("keyup",sf(this,Vc))})),nf(this,Kc,(e=>{let{metaKey:t,altKey:i,key:r}=e;t||i||!this.keysUsed.includes(r)?this.removeEventListener("keyup",sf(this,Vc)):(e.preventDefault(),this.addEventListener("keyup",sf(this,Vc),{once:!0}))})),nf(this,Wc,(e=>{e.composedPath().includes(this)||of(this,Jc,ef).call(this)})),nf(this,qc,(e=>{e.composedPath().includes(sf(this,Bc))&&of(this,zc,Xc).call(this)})),nf(this,Yc,(()=>{of(this,Jc,ef).call(this)})),nf(this,tf,(()=>{if(0===sf(this,Gc).offsetWidth)return;let e=sf(this,Gc).offsetWidth,t=sf(this,Bc).getBoundingClientRect();if(this.hasAttribute("mediacontroller")||sf(this,Bc).hasAttribute("mediacontroller")||sf(this,Gc).hasAttribute("mediacontroller"))return sf(this,Gc).style.zIndex="1",sf(this,Gc).style.bottom="unset",sf(this,Gc).style.right=null,sf(this,Gc).style.left="0",void(sf(this,Gc).style.top=`${t.height}px`);let i=df(this).getBoundingClientRect(),r=t.x+e,s=Math.max(t.right-r,t.right-i.right);sf(this,Gc).style.left=null,sf(this,Gc).style.right=`${s}px`,sf(this,Gc).style.maxHeight=i.height-t.height+"px"})),this.shadowRoot||(this.attachShadow({mode:"open"}),this.shadowRoot.appendChild(lf.content.cloneNode(!0))),null==(e=this.init)||e.call(this),af(this,Bc,this.shadowRoot.querySelector("[part=button]")),af(this,Gc,this.shadowRoot.querySelector("[part=listbox]")),af(this,Hc,this.shadowRoot.querySelector("slot[name=button]")),sf(this,Hc).addEventListener("slotchange",(()=>{let e=sf(this,Hc).assignedElements()[0];e&&(af(this,Bc,e),sf(this,Bc).preventClick=!0,this.hasAttribute("disabled")||sf(this,Bc).hasAttribute("disabled")?this.disable():(this.enable(),sf(this,Bc).setAttribute("aria-haspopup","listbox")))})),af(this,jc,this.shadowRoot.querySelector("slot[name=listbox]")),sf(this,jc).addEventListener("slotchange",(()=>{af(this,Gc,sf(this,jc).assignedElements()[0]||sf(this,Gc))}))}static get observedAttributes(){return["disabled",Xn]}enable(){sf(this,Bc).toggleAttribute("disabled",!1),this.addEventListener("change",sf(this,Yc)),this.addEventListener("keydown",sf(this,Kc)),this.addEventListener("click",sf(this,qc)),co.addEventListener("click",sf(this,Wc))}disable(){sf(this,Bc).toggleAttribute("disabled",!0),this.removeEventListener("change",sf(this,Yc)),this.removeEventListener("keydown",sf(this,Kc)),this.removeEventListener("keyup",sf(this,Vc)),this.removeEventListener("click",sf(this,qc)),co.removeEventListener("click",sf(this,Wc))}attributeChangedCallback(e,t,i){var r,s,n,a,o;e===Xn?(t&&(null==(s=null==(r=sf(this,Fc))?void 0:r.unassociateElement)||s.call(r,this),af(this,Fc,null),sf(this,Gc).removeAttribute(Xn)),i&&this.isConnected&&(af(this,Fc,null==(n=this.getRootNode())?void 0:n.getElementById(i)),null==(o=null==(a=sf(this,Fc))?void 0:a.associateElement)||o.call(a,this),sf(this,Gc).setAttribute(Xn,i))):"disabled"===e&&i!==t&&(null==i?this.enable():this.disable())}connectedCallback(){var e,t,i;let{style:r}=qa(this.shadowRoot,":host");r.setProperty("display",`var(--media-control-display, var(--${this.localName}-display, inline-flex))`);let s=this.getAttribute(Xn);s&&(af(this,Fc,null==(e=this.getRootNode())?void 0:e.getElementById(s)),null==(i=null==(t=sf(this,Fc))?void 0:t.associateElement)||i.call(t,this),sf(this,Gc).setAttribute(Xn,s)),this.hasAttribute("disabled")||this.enable(),sf(this,jc).hidden||Oo(df(this),sf(this,tf))}disconnectedCallback(){var e,t;Uo(df(this),sf(this,tf)),this.disable(),null==(t=null==(e=sf(this,Fc))?void 0:e.unassociateElement)||t.call(e,this),af(this,Fc,null),sf(this,Gc).removeAttribute(Xn)}get keysUsed(){return["Enter","Escape"," ","ArrowUp","ArrowDown","f","c","k","m"]}};function df(e){var t;return null!=(t=e.getAttribute("bounds")?Va(e,`#${e.getAttribute("bounds")}`):function(e){var t;let i=e.getAttribute(Xn);return i?null==(t=e.getRootNode())?void 0:t.getElementById(i):Va(e,"media-controller")}(e)||e.parentElement)?t:e}Fc=new WeakMap,Bc=new WeakMap,Hc=new WeakMap,Gc=new WeakMap,jc=new WeakMap,Vc=new WeakMap,Kc=new WeakMap,Wc=new WeakMap,qc=new WeakMap,Yc=new WeakMap,zc=new WeakSet,Xc=function(){sf(this,jc).hidden?of(this,Qc,Zc).call(this):of(this,Jc,ef).call(this)},Qc=new WeakSet,Zc=function(){sf(this,jc).hidden&&(sf(this,jc).hidden=!1,sf(this,Bc).setAttribute("aria-expanded","true"),sf(this,tf).call(this),sf(this,Gc).focus(),Oo(df(this),sf(this,tf)))},Jc=new WeakSet,ef=function(){if(sf(this,jc).hidden)return;Uo(df(this),sf(this,tf));let e=Ka();sf(this,jc).hidden=!0,sf(this,Bc).setAttribute("aria-expanded","false"),ja(sf(this,Gc),e)&&sf(this,Bc).focus()},tf=new WeakMap,uo.customElements.get("media-chrome-selectmenu")||uo.customElements.define("media-chrome-selectmenu",hf);var uf,cf,ff,pf,mf=(e,t,i)=>{if(!t.has(e))throw TypeError("Cannot "+i)},gf=(e,t,i)=>(mf(e,t,"read from private field"),t.get(e)),vf=(e,t,i)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,i)},Ef=(e,t,i,r)=>(mf(e,t,"write to private field"),t.set(e,i),i),yf=(e,t,i)=>(mf(e,t,"access private method"),i),bf=co.createElement("template");bf.innerHTML='\n<style>\n  :host {\n    cursor: pointer;\n    display: block;\n    line-height: revert;\n    white-space: nowrap;\n    white-space-collapse: collapse;\n    text-wrap: nowrap;\n    padding: .4em .5em;\n    transition: var(--media-option-transition);\n    outline: var(--media-option-outline, 0);\n    outline-offset: var(--media-option-outline-offset, -1px);\n  }\n\n  :host(:focus-visible) {\n    box-shadow: var(--media-option-focus-shadow, inset 0 0 0 2px rgb(27 127 204 / .9));\n    outline: var(--media-option-hover-outline, 0);\n    outline-offset: var(--media-option-hover-outline-offset,  var(--media-option-outline-offset, -1px));\n  }\n\n  :host(:hover) {\n    cursor: pointer;\n    background: var(--media-option-hover-background, rgb(82 82 122 / .8));\n    outline: var(--media-option-hover-outline);\n    outline-offset: var(--media-option-hover-outline-offset,  var(--media-option-outline-offset, -1px));\n  }\n\n  :host([aria-selected="true"]) {\n    background: var(--media-option-selected-background);\n  }\n\n  :host([disabled]) {\n    pointer-events: none;\n    color: rgba(255, 255, 255, .3);\n  }\n</style>\n<slot></slot>\n';var Tf="value",Sf="selected",Af="disabled",_f=class extends uo.HTMLElement{constructor(){super(),vf(this,ff),vf(this,uf,!1),vf(this,cf,void 0),this.shadowRoot||(this.attachShadow({mode:"open"}),this.shadowRoot.appendChild(bf.content.cloneNode(!0)))}static get observedAttributes(){return[Af,Sf,Tf]}get value(){var e;return null!=(e=this.getAttribute(Tf))?e:this.text}set value(e){this.setAttribute(Tf,e)}get text(){var e;return(null!=(e=this.textContent)?e:"").trim()}get selected(){return"true"===this.getAttribute("aria-selected")}set selected(e){Ef(this,uf,!0),this.setAttribute("aria-selected",e?"true":"false"),e?this.part.add("option-selected"):this.part.remove("option-selected")}enable(){this.hasAttribute("tabindex")||this.setAttribute("tabindex",-1),this.hasAttribute("aria-selected")||this.setAttribute("aria-selected","false")}disable(){this.removeAttribute("tabindex")}attributeChangedCallback(e,t,i){e!==Sf||gf(this,uf)?e===Af&&i!==t&&(null==i?this.enable():this.disable()):this.setAttribute("aria-selected",null!=i?"true":"false")}connectedCallback(){this.hasAttribute(Af)||this.enable(),this.setAttribute("role","option"),Ef(this,cf,wf(this,this.parentNode)),yf(this,ff,pf).call(this)}disconnectedCallback(){this.disable(),yf(this,ff,pf).call(this),Ef(this,cf,null)}handleClick(){}};function wf(e,t){if(!e)return null;let{host:i}=e.getRootNode();return!t&&i?wf(e,i):t?.options?t:wf(t,t?.parentNode)}uf=new WeakMap,cf=new WeakMap,ff=new WeakSet,pf=function(){var e;let t=null==(e=gf(this,cf))?void 0:e.options;if(!t)return;let i=t.filter((e=>"true"===e.getAttribute("aria-selected"))).pop();i||(i=t[0]),"true"!==gf(this,cf).getAttribute("aria-multiselectable")&&t.forEach((e=>{e.setAttribute("tabindex","-1"),e.setAttribute("aria-selected","false")})),i?.setAttribute("tabindex","0"),i?.setAttribute("aria-selected","true")},uo.customElements.get("media-chrome-option")||uo.customElements.define("media-chrome-option",_f);var kf,Lf,Rf,If,Cf,Df=(e,t,i)=>{if(!t.has(e))throw TypeError("Cannot "+i)},xf=(e,t,i)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,i)},Mf=(e,t,i)=>(Df(e,t,"access private method"),i),Pf=co.createElement("template");Pf.innerHTML='\n  <slot name="captions-indicator" hidden>\n<svg aria-hidden="true" viewBox="0 0 26 24" part="captions-indicator indicator">\n  <path d="M22.83 5.68a2.58 2.58 0 0 0-2.3-2.5c-3.62-.24-11.44-.24-15.06 0a2.58 2.58 0 0 0-2.3 2.5c-.23 4.21-.23 8.43 0 12.64a2.58 2.58 0 0 0 2.3 2.5c3.62.24 11.44.24 15.06 0a2.58 2.58 0 0 0 2.3-2.5c.23-4.21.23-8.43 0-12.64Zm-11.39 9.45a3.07 3.07 0 0 1-1.91.57 3.06 3.06 0 0 1-2.34-1 3.75 3.75 0 0 1-.92-2.67 3.92 3.92 0 0 1 .92-2.77 3.18 3.18 0 0 1 2.43-1 2.94 2.94 0 0 1 2.13.78c.364.359.62.813.74 1.31l-1.43.35a1.49 1.49 0 0 0-1.51-1.17 1.61 1.61 0 0 0-1.29.58 2.79 2.79 0 0 0-.5 1.89 3 3 0 0 0 .49 1.93 1.61 1.61 0 0 0 1.27.58 1.48 1.48 0 0 0 1-.37 2.1 2.1 0 0 0 .59-1.14l1.4.44a3.23 3.23 0 0 1-1.07 1.69Zm7.22 0a3.07 3.07 0 0 1-1.91.57 3.06 3.06 0 0 1-2.34-1 3.75 3.75 0 0 1-.92-2.67 3.88 3.88 0 0 1 .93-2.77 3.14 3.14 0 0 1 2.42-1 3 3 0 0 1 2.16.82 2.8 2.8 0 0 1 .73 1.31l-1.43.35a1.49 1.49 0 0 0-1.51-1.21 1.61 1.61 0 0 0-1.29.58A2.79 2.79 0 0 0 15 12a3 3 0 0 0 .49 1.93 1.61 1.61 0 0 0 1.27.58 1.44 1.44 0 0 0 1-.37 2.1 2.1 0 0 0 .6-1.15l1.4.44a3.17 3.17 0 0 1-1.1 1.7Z"/>\n</svg></slot>\n';kf=new WeakMap,Lf=new WeakSet,Rf=function(){var e;if(((e,t)=>(Df(e,t,"read from private field"),t.get(e)))(this,kf)===JSON.stringify(this.mediaSubtitlesList))return;((e,t,i)=>{Df(e,t,"write to private field"),t.set(e,i)})(this,kf,JSON.stringify(this.mediaSubtitlesList));let t=this.shadowRoot.querySelector("#container");t.textContent="";let i=!this.value,r=Oc(this.formatOptionText("Off"),"off",i);r.prepend(Uc(this,"select-indicator")),t.append(r);let s=this.mediaSubtitlesList;for(let i of s){let r=Oc(this.formatOptionText(i.label,i),Sl(i),this.value==Sl(i));r.prepend(Uc(this,"select-indicator")),"captions"===(null!=(e=i.kind)?e:"subs")&&r.append(Uc(this,"captions-indicator")),t.append(r)}},If=new WeakSet,Cf=function(){let e=this.mediaSubtitlesShowing,t=this.getAttribute(Jn.MEDIA_SUBTITLES_SHOWING),i=this.value!==t;if(e?.length&&i&&this.dispatchEvent(new uo.CustomEvent(Yn.MEDIA_DISABLE_SUBTITLES_REQUEST,{composed:!0,bubbles:!0,detail:e})),!this.value||!i)return;let r=new uo.CustomEvent(Yn.MEDIA_SHOW_SUBTITLES_REQUEST,{composed:!0,bubbles:!0,detail:this.value});this.dispatchEvent(r)};var Of=(e,t)=>{let i=e.getAttribute(t);return i?bl(i):[]},Uf=(e,t,i)=>{if(!i?.length)return void e.removeAttribute(t);let r=Al(i);e.getAttribute(t)!==r&&e.setAttribute(t,r)};uo.customElements.get("media-captions-listbox")||uo.customElements.define("media-captions-listbox",class extends $c{constructor(){super({slotTemplate:Pf}),xf(this,Lf),xf(this,If),xf(this,kf,void 0)}static get observedAttributes(){return[...super.observedAttributes,"aria-multiselectable",Jn.MEDIA_SUBTITLES_LIST,Jn.MEDIA_SUBTITLES_SHOWING]}attributeChangedCallback(e,t,i){super.attributeChangedCallback(e,t,i),e===Jn.MEDIA_SUBTITLES_LIST&&t!==i?Mf(this,Lf,Rf).call(this):e===Jn.MEDIA_SUBTITLES_SHOWING&&t!==i?this.value=i:"aria-multiselectable"===e&&(this.removeAttribute("aria-multiselectable"),console.warn("Captions List doesn't currently support multiple selections. You can enable multiple items via the media.textTracks API."))}connectedCallback(){super.connectedCallback(),this.addEventListener("change",Mf(this,If,Cf))}disconnectedCallback(){super.disconnectedCallback(),this.removeEventListener("change",Mf(this,If,Cf))}get mediaSubtitlesList(){return Of(this,Jn.MEDIA_SUBTITLES_LIST)}set mediaSubtitlesList(e){Uf(this,Jn.MEDIA_SUBTITLES_LIST,e)}get mediaSubtitlesShowing(){return Of(this,Jn.MEDIA_SUBTITLES_SHOWING)}set mediaSubtitlesShowing(e){Uf(this,Jn.MEDIA_SUBTITLES_SHOWING,e)}});uo.customElements.get("media-captions-selectmenu")||uo.customElements.define("media-captions-selectmenu",class extends hf{init(){let e=co.createElement("media-captions-button");e.part.add("button"),e.preventClick=!0;let t=co.createElement("media-captions-listbox");t.part.add("listbox"),t.setAttribute("exportparts","option, option-selected, indicator");let i=this.shadowRoot.querySelector("slot[name=button]"),r=this.shadowRoot.querySelector("slot[name=listbox]");i.textContent="",r.textContent="",i.append(e),r.append(t)}});var Nf=yt(un(),1);var $f={exports:{}};!function(e){!function(){var t=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,i=/^(?=([^\/?#]*))\1([^]*)$/,r=/(?:\/|^)\.(?=\/)/g,s=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,n={buildAbsoluteURL:function(e,t,r){if(r=r||{},e=e.trim(),!(t=t.trim())){if(!r.alwaysNormalize)return e;var s=n.parseURL(e);if(!s)throw new Error("Error trying to parse base URL.");return s.path=n.normalizePath(s.path),n.buildURLFromParts(s)}var a=n.parseURL(t);if(!a)throw new Error("Error trying to parse relative URL.");if(a.scheme)return r.alwaysNormalize?(a.path=n.normalizePath(a.path),n.buildURLFromParts(a)):t;var o=n.parseURL(e);if(!o)throw new Error("Error trying to parse base URL.");if(!o.netLoc&&o.path&&"/"!==o.path[0]){var l=i.exec(o.path);o.netLoc=l[1],o.path=l[2]}o.netLoc&&!o.path&&(o.path="/");var h={scheme:o.scheme,netLoc:a.netLoc,path:null,params:a.params,query:a.query,fragment:a.fragment};if(!a.netLoc&&(h.netLoc=o.netLoc,"/"!==a.path[0]))if(a.path){var d=o.path,u=d.substring(0,d.lastIndexOf("/")+1)+a.path;h.path=n.normalizePath(u)}else h.path=o.path,a.params||(h.params=o.params,a.query||(h.query=o.query));return null===h.path&&(h.path=r.alwaysNormalize?n.normalizePath(a.path):a.path),n.buildURLFromParts(h)},parseURL:function(e){var i=t.exec(e);return i?{scheme:i[1]||"",netLoc:i[2]||"",path:i[3]||"",params:i[4]||"",query:i[5]||"",fragment:i[6]||""}:null},normalizePath:function(e){for(e=e.split("").reverse().join("").replace(r,"");e.length!==(e=e.replace(s,"")).length;);return e.split("").reverse().join("")},buildURLFromParts:function(e){return e.scheme+e.netLoc+e.path+e.params+e.query+e.fragment}};e.exports=n}()}($f);var Ff=$f.exports;function Bf(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,r)}return i}function Hf(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?Bf(Object(i),!0).forEach((function(t){jf(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):Bf(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}function Gf(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var i=e[Symbol.toPrimitive];if(void 0!==i){var r=i.call(e,t);if("object"!=typeof r)return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==typeof t?t:String(t)}function jf(e,t,i){return(t=Gf(t))in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}function Vf(){return Vf=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var i=arguments[t];for(var r in i)Object.prototype.hasOwnProperty.call(i,r)&&(e[r]=i[r])}return e},Vf.apply(this,arguments)}var Kf=Number.isFinite||function(e){return"number"==typeof e&&isFinite(e)},Wf=Number.isSafeInteger||function(e){return"number"==typeof e&&Math.abs(e)<=qf},qf=Number.MAX_SAFE_INTEGER||9007199254740991,Yf=function(e){return e.MEDIA_ATTACHING="hlsMediaAttaching",e.MEDIA_ATTACHED="hlsMediaAttached",e.MEDIA_DETACHING="hlsMediaDetaching",e.MEDIA_DETACHED="hlsMediaDetached",e.BUFFER_RESET="hlsBufferReset",e.BUFFER_CODECS="hlsBufferCodecs",e.BUFFER_CREATED="hlsBufferCreated",e.BUFFER_APPENDING="hlsBufferAppending",e.BUFFER_APPENDED="hlsBufferAppended",e.BUFFER_EOS="hlsBufferEos",e.BUFFER_FLUSHING="hlsBufferFlushing",e.BUFFER_FLUSHED="hlsBufferFlushed",e.MANIFEST_LOADING="hlsManifestLoading",e.MANIFEST_LOADED="hlsManifestLoaded",e.MANIFEST_PARSED="hlsManifestParsed",e.LEVEL_SWITCHING="hlsLevelSwitching",e.LEVEL_SWITCHED="hlsLevelSwitched",e.LEVEL_LOADING="hlsLevelLoading",e.LEVEL_LOADED="hlsLevelLoaded",e.LEVEL_UPDATED="hlsLevelUpdated",e.LEVEL_PTS_UPDATED="hlsLevelPtsUpdated",e.LEVELS_UPDATED="hlsLevelsUpdated",e.AUDIO_TRACKS_UPDATED="hlsAudioTracksUpdated",e.AUDIO_TRACK_SWITCHING="hlsAudioTrackSwitching",e.AUDIO_TRACK_SWITCHED="hlsAudioTrackSwitched",e.AUDIO_TRACK_LOADING="hlsAudioTrackLoading",e.AUDIO_TRACK_LOADED="hlsAudioTrackLoaded",e.SUBTITLE_TRACKS_UPDATED="hlsSubtitleTracksUpdated",e.SUBTITLE_TRACKS_CLEARED="hlsSubtitleTracksCleared",e.SUBTITLE_TRACK_SWITCH="hlsSubtitleTrackSwitch",e.SUBTITLE_TRACK_LOADING="hlsSubtitleTrackLoading",e.SUBTITLE_TRACK_LOADED="hlsSubtitleTrackLoaded",e.SUBTITLE_FRAG_PROCESSED="hlsSubtitleFragProcessed",e.CUES_PARSED="hlsCuesParsed",e.NON_NATIVE_TEXT_TRACKS_FOUND="hlsNonNativeTextTracksFound",e.INIT_PTS_FOUND="hlsInitPtsFound",e.FRAG_LOADING="hlsFragLoading",e.FRAG_LOAD_EMERGENCY_ABORTED="hlsFragLoadEmergencyAborted",e.FRAG_LOADED="hlsFragLoaded",e.FRAG_DECRYPTED="hlsFragDecrypted",e.FRAG_PARSING_INIT_SEGMENT="hlsFragParsingInitSegment",e.FRAG_PARSING_USERDATA="hlsFragParsingUserdata",e.FRAG_PARSING_METADATA="hlsFragParsingMetadata",e.FRAG_PARSED="hlsFragParsed",e.FRAG_BUFFERED="hlsFragBuffered",e.FRAG_CHANGED="hlsFragChanged",e.FPS_DROP="hlsFpsDrop",e.FPS_DROP_LEVEL_CAPPING="hlsFpsDropLevelCapping",e.MAX_AUTO_LEVEL_UPDATED="hlsMaxAutoLevelUpdated",e.ERROR="hlsError",e.DESTROYING="hlsDestroying",e.KEY_LOADING="hlsKeyLoading",e.KEY_LOADED="hlsKeyLoaded",e.LIVE_BACK_BUFFER_REACHED="hlsLiveBackBufferReached",e.BACK_BUFFER_REACHED="hlsBackBufferReached",e.STEERING_MANIFEST_LOADED="hlsSteeringManifestLoaded",e}({}),zf=function(e){return e.NETWORK_ERROR="networkError",e.MEDIA_ERROR="mediaError",e.KEY_SYSTEM_ERROR="keySystemError",e.MUX_ERROR="muxError",e.OTHER_ERROR="otherError",e}({}),Xf=function(e){return e.KEY_SYSTEM_NO_KEYS="keySystemNoKeys",e.KEY_SYSTEM_NO_ACCESS="keySystemNoAccess",e.KEY_SYSTEM_NO_SESSION="keySystemNoSession",e.KEY_SYSTEM_NO_CONFIGURED_LICENSE="keySystemNoConfiguredLicense",e.KEY_SYSTEM_LICENSE_REQUEST_FAILED="keySystemLicenseRequestFailed",e.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED="keySystemServerCertificateRequestFailed",e.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED="keySystemServerCertificateUpdateFailed",e.KEY_SYSTEM_SESSION_UPDATE_FAILED="keySystemSessionUpdateFailed",e.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED="keySystemStatusOutputRestricted",e.KEY_SYSTEM_STATUS_INTERNAL_ERROR="keySystemStatusInternalError",e.MANIFEST_LOAD_ERROR="manifestLoadError",e.MANIFEST_LOAD_TIMEOUT="manifestLoadTimeOut",e.MANIFEST_PARSING_ERROR="manifestParsingError",e.MANIFEST_INCOMPATIBLE_CODECS_ERROR="manifestIncompatibleCodecsError",e.LEVEL_EMPTY_ERROR="levelEmptyError",e.LEVEL_LOAD_ERROR="levelLoadError",e.LEVEL_LOAD_TIMEOUT="levelLoadTimeOut",e.LEVEL_PARSING_ERROR="levelParsingError",e.LEVEL_SWITCH_ERROR="levelSwitchError",e.AUDIO_TRACK_LOAD_ERROR="audioTrackLoadError",e.AUDIO_TRACK_LOAD_TIMEOUT="audioTrackLoadTimeOut",e.SUBTITLE_LOAD_ERROR="subtitleTrackLoadError",e.SUBTITLE_TRACK_LOAD_TIMEOUT="subtitleTrackLoadTimeOut",e.FRAG_LOAD_ERROR="fragLoadError",e.FRAG_LOAD_TIMEOUT="fragLoadTimeOut",e.FRAG_DECRYPT_ERROR="fragDecryptError",e.FRAG_PARSING_ERROR="fragParsingError",e.FRAG_GAP="fragGap",e.REMUX_ALLOC_ERROR="remuxAllocError",e.KEY_LOAD_ERROR="keyLoadError",e.KEY_LOAD_TIMEOUT="keyLoadTimeOut",e.BUFFER_ADD_CODEC_ERROR="bufferAddCodecError",e.BUFFER_INCOMPATIBLE_CODECS_ERROR="bufferIncompatibleCodecsError",e.BUFFER_APPEND_ERROR="bufferAppendError",e.BUFFER_APPENDING_ERROR="bufferAppendingError",e.BUFFER_STALLED_ERROR="bufferStalledError",e.BUFFER_FULL_ERROR="bufferFullError",e.BUFFER_SEEK_OVER_HOLE="bufferSeekOverHole",e.BUFFER_NUDGE_ON_STALL="bufferNudgeOnStall",e.INTERNAL_EXCEPTION="internalException",e.INTERNAL_ABORTED="aborted",e.UNKNOWN="unknown",e}({}),Qf=function(){},Zf={trace:Qf,debug:Qf,log:Qf,warn:Qf,info:Qf,error:Qf},Jf=Zf;function ep(e,...t){t.forEach((function(t){Jf[t]=e[t]?e[t].bind(e):function(e){let t=self.console[e];return t?t.bind(self.console,`[${e}] >`):Qf}(t)}))}var tp=Jf,ip=/^(\d+)x(\d+)$/,rp=/(.+?)=(".*?"|.*?)(?:,|$)/g,sp=class e{constructor(t){"string"==typeof t&&(t=e.parseAttrList(t)),Vf(this,t)}get clientAttrs(){return Object.keys(this).filter((e=>"X-"===e.substring(0,2)))}decimalInteger(e){let t=parseInt(this[e],10);return t>Number.MAX_SAFE_INTEGER?1/0:t}hexadecimalInteger(e){if(this[e]){let t=(this[e]||"0x").slice(2);t=(1&t.length?"0":"")+t;let i=new Uint8Array(t.length/2);for(let e=0;e<t.length/2;e++)i[e]=parseInt(t.slice(2*e,2*e+2),16);return i}return null}hexadecimalIntegerAsNumber(e){let t=parseInt(this[e],16);return t>Number.MAX_SAFE_INTEGER?1/0:t}decimalFloatingPoint(e){return parseFloat(this[e])}optionalFloat(e,t){let i=this[e];return i?parseFloat(i):t}enumeratedString(e){return this[e]}bool(e){return"YES"===this[e]}decimalResolution(e){let t=ip.exec(this[e]);if(null!==t)return{width:parseInt(t[1],10),height:parseInt(t[2],10)}}static parseAttrList(e){let t,i={};for(rp.lastIndex=0;null!==(t=rp.exec(e));){let e=t[2];0===e.indexOf('"')&&e.lastIndexOf('"')===e.length-1&&(e=e.slice(1,-1)),i[t[1].trim()]=e}return i}};function np(e){return"ID"!==e&&"CLASS"!==e&&"START-DATE"!==e&&"DURATION"!==e&&"END-DATE"!==e&&"END-ON-NEXT"!==e}function ap(e){return"SCTE35-OUT"===e||"SCTE35-IN"===e}var op=class{constructor(e,t){if(this.attr=void 0,this._startDate=void 0,this._endDate=void 0,this._badValueForSameId=void 0,t){let i=t.attr;for(let t in i)if(Object.prototype.hasOwnProperty.call(e,t)&&e[t]!==i[t]){tp.warn(`DATERANGE tag attribute: "${t}" does not match for tags with ID: "${e.ID}"`),this._badValueForSameId=t;break}e=Vf(new sp({}),i,e)}if(this.attr=e,this._startDate=new Date(e["START-DATE"]),"END-DATE"in this.attr){let e=new Date(this.attr["END-DATE"]);Kf(e.getTime())&&(this._endDate=e)}}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;let e=this.duration;return null!==e?new Date(this._startDate.getTime()+1e3*e):null}get duration(){if("DURATION"in this.attr){let e=this.attr.decimalFloatingPoint("DURATION");if(Kf(e))return e}else if(this._endDate)return(this._endDate.getTime()-this._startDate.getTime())/1e3;return null}get plannedDuration(){return"PLANNED-DURATION"in this.attr?this.attr.decimalFloatingPoint("PLANNED-DURATION"):null}get endOnNext(){return this.attr.bool("END-ON-NEXT")}get isValid(){return!!this.id&&!this._badValueForSameId&&Kf(this.startDate.getTime())&&(null===this.duration||this.duration>=0)&&(!this.endOnNext||!!this.class)}},lp=class{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}}},hp="audio",dp="video",up="audiovideo",cp=class{constructor(e){this._byteRange=null,this._url=null,this.baseurl=void 0,this.relurl=void 0,this.elementaryStreams={[hp]:null,[dp]:null,[up]:null},this.baseurl=e}setByteRange(e,t){let i,r=e.split("@",2);i=1===r.length?t?.byteRangeEndOffset||0:parseInt(r[1]),this._byteRange=[i,parseInt(r[0])+i]}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=Ff.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""}set url(e){this._url=e}},fp=class extends cp{constructor(e,t){super(t),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 lp,this.data=void 0,this.bitrateTest=!1,this.title=null,this.initSegment=null,this.endList=void 0,this.gap=void 0,this.urlId=0,this.type=e}get decryptdata(){let{levelkeys:e}=this;if(!e&&!this._decryptdata)return null;if(!this._decryptdata&&this.levelkeys&&!this.levelkeys.NONE){let e=this.levelkeys.identity;if(e)this._decryptdata=e.getDecryptData(this.sn);else{let e=Object.keys(this.levelkeys);if(1===e.length)return this._decryptdata=this.levelkeys[e[0]].getDecryptData(this.sn)}}return this._decryptdata}get end(){return this.start+this.duration}get endProgramDateTime(){if(null===this.programDateTime||!Kf(this.programDateTime))return null;let e=Kf(this.duration)?this.duration:0;return this.programDateTime+1e3*e}get encrypted(){var e;if(null!=(e=this._decryptdata)&&e.encrypted)return!0;if(this.levelkeys){let e=Object.keys(this.levelkeys),t=e.length;if(t>1||1===t&&this.levelkeys[e[0]].encrypted)return!0}return!1}setKeyFormat(e){if(this.levelkeys){let t=this.levelkeys[e];t&&!this._decryptdata&&(this._decryptdata=t.getDecryptData(this.sn))}}abortRequests(){var e,t;null==(e=this.loader)||e.abort(),null==(t=this.keyLoader)||t.abort()}setElementaryStreamInfo(e,t,i,r,s,n=!1){let{elementaryStreams:a}=this,o=a[e];o?(o.startPTS=Math.min(o.startPTS,t),o.endPTS=Math.max(o.endPTS,i),o.startDTS=Math.min(o.startDTS,r),o.endDTS=Math.max(o.endDTS,s)):a[e]={startPTS:t,endPTS:i,startDTS:r,endDTS:s,partial:n}}clearElementaryStreamInfo(){let{elementaryStreams:e}=this;e[hp]=null,e[dp]=null,e[up]=null}},pp=class extends cp{constructor(e,t,i,r,s){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 lp,this.duration=e.decimalFloatingPoint("DURATION"),this.gap=e.bool("GAP"),this.independent=e.bool("INDEPENDENT"),this.relurl=e.enumeratedString("URI"),this.fragment=t,this.index=r;let n=e.enumeratedString("BYTERANGE");n&&this.setByteRange(n,s),s&&(this.fragOffset=s.fragOffset+s.duration)}get start(){return this.fragment.start+this.fragOffset}get end(){return this.start+this.duration}get loaded(){let{elementaryStreams:e}=this;return!!(e.audio||e.video||e.audiovideo)}},mp=class{constructor(e){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=e}reloaded(e){if(!e)return this.advanced=!0,void(this.updated=!0);let t=this.lastPartSn-e.lastPartSn,i=this.lastPartIndex-e.lastPartIndex;this.updated=this.endSN!==e.endSN||!!i||!!t||!this.live,this.advanced=this.endSN>e.endSN||t>0||0===t&&i>0,this.updated||this.advanced?this.misses=Math.floor(.6*e.misses):this.misses=e.misses+1,this.availabilityDelay=e.availabilityDelay}get hasProgramDateTime(){return!!this.fragments.length&&Kf(this.fragments[this.fragments.length-1].programDateTime)}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||10}get drift(){let e=this.driftEndTime-this.driftStartTime;return e>0?1e3*(this.driftEnd-this.driftStart)/e:1}get edge(){return this.partEnd||this.fragmentEnd}get partEnd(){var e;return null!=(e=this.partList)&&e.length?this.partList[this.partList.length-1].end:this.fragmentEnd}get fragmentEnd(){var e;return null!=(e=this.fragments)&&e.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 e;return null!=(e=this.partList)&&e.length?this.partList[this.partList.length-1].index:-1}get lastPartSn(){var e;return null!=(e=this.partList)&&e.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}};function gp(e){return Uint8Array.from(atob(e),(e=>e.charCodeAt(0)))}function vp(e){let t=e.split(":"),i=null;if("data"===t[0]&&2===t.length){let e=t[1].split(";"),r=e[e.length-1].split(",");if(2===r.length){let t="base64"===r[0],s=r[1];t?(e.splice(-1,1),i=gp(s)):i=function(e){let t=Ep(e).subarray(0,16),i=new Uint8Array(16);return i.set(t,16-t.length),i}(s)}}return i}function Ep(e){return Uint8Array.from(unescape(encodeURIComponent(e)),(e=>e.charCodeAt(0)))}var yp=typeof self<"u"?self:void 0,bp={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},Tp="org.w3.clearkey",Sp="com.apple.streamingkeydelivery",Ap="com.microsoft.playready",_p="urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed";function wp(e){switch(e){case Sp:return bp.FAIRPLAY;case Ap:return bp.PLAYREADY;case _p:return bp.WIDEVINE;case Tp:return bp.CLEARKEY}}var kp="1077efecc0b24d02ace33c1e52e2fb4b",Lp="e2719d58a985b3c9781ab030af78d30e",Rp="9a04f07998404286ab92e65be0885f95",Ip="edef8ba979d64acea3c827dcd51d21ed";function Cp(e){return e===Ip?bp.WIDEVINE:e===Rp?bp.PLAYREADY:e===kp||e===Lp?bp.CLEARKEY:void 0}function Dp(e){switch(e){case bp.FAIRPLAY:return Sp;case bp.PLAYREADY:return Ap;case bp.WIDEVINE:return _p;case bp.CLEARKEY:return Tp}}function xp(e){let{drmSystems:t,widevineLicenseUrl:i}=e,r=t?[bp.FAIRPLAY,bp.WIDEVINE,bp.PLAYREADY,bp.CLEARKEY].filter((e=>!!t[e])):[];return!r[bp.WIDEVINE]&&i&&r.push(bp.WIDEVINE),r}var Mp=function(e){return null!=yp&&null!=(e=yp.navigator)&&e.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null}();function Pp(e,t,i){return Uint8Array.prototype.slice?e.slice(t,i):new Uint8Array(Array.prototype.slice.call(e,t,i))}var Op,Up=(e,t)=>t+10<=e.length&&73===e[t]&&68===e[t+1]&&51===e[t+2]&&e[t+3]<255&&e[t+4]<255&&e[t+6]<128&&e[t+7]<128&&e[t+8]<128&&e[t+9]<128,Np=(e,t)=>t+10<=e.length&&51===e[t]&&68===e[t+1]&&73===e[t+2]&&e[t+3]<255&&e[t+4]<255&&e[t+6]<128&&e[t+7]<128&&e[t+8]<128&&e[t+9]<128,$p=(e,t)=>{let i=t,r=0;for(;Up(e,t);){r+=10,r+=Fp(e,t+6),Np(e,t+10)&&(r+=10),t+=r}if(r>0)return e.subarray(i,i+r)},Fp=(e,t)=>{let i=0;return i=(127&e[t])<<21,i|=(127&e[t+1])<<14,i|=(127&e[t+2])<<7,i|=127&e[t+3],i},Bp=(e,t)=>Up(e,t)&&Fp(e,t+6)+10<=e.length-t,Hp=e=>{let t=Vp(e);for(let e=0;e<t.length;e++){let i=t[e];if(Gp(i))return zp(i)}},Gp=e=>e&&"PRIV"===e.key&&"com.apple.streaming.transportStreamTimestamp"===e.info,jp=e=>{let t=String.fromCharCode(e[0],e[1],e[2],e[3]),i=Fp(e,4);return{type:t,size:i,data:e.subarray(10,10+i)}},Vp=e=>{let t=0,i=[];for(;Up(e,t);){let r=Fp(e,t+6);t+=10;let s=t+r;for(;t+8<s;){let r=jp(e.subarray(t)),s=Kp(r);s&&i.push(s),t+=r.size+10}Np(e,t)&&(t+=10)}return i},Kp=e=>"PRIV"===e.type?Wp(e):"W"===e.type[0]?Yp(e):qp(e),Wp=e=>{if(e.size<2)return;let t=Xp(e.data,!0),i=new Uint8Array(e.data.subarray(t.length+1));return{key:e.type,info:t,data:i.buffer}},qp=e=>{if(e.size<2)return;if("TXXX"===e.type){let t=1,i=Xp(e.data.subarray(t),!0);t+=i.length+1;let r=Xp(e.data.subarray(t));return{key:e.type,info:i,data:r}}let t=Xp(e.data.subarray(1));return{key:e.type,data:t}},Yp=e=>{if("WXXX"===e.type){if(e.size<2)return;let t=1,i=Xp(e.data.subarray(t),!0);t+=i.length+1;let r=Xp(e.data.subarray(t));return{key:e.type,info:i,data:r}}let t=Xp(e.data);return{key:e.type,data:t}},zp=e=>{if(8===e.data.byteLength){let t=new Uint8Array(e.data),i=1&t[3],r=(t[4]<<23)+(t[5]<<15)+(t[6]<<7)+t[7];return r/=45,i&&(r+=47721858.84),Math.round(r)}},Xp=(e,t=!1)=>{let i=function(){if(!navigator.userAgent.includes("PlayStation 4"))return!Op&&typeof self.TextDecoder<"u"&&(Op=new self.TextDecoder("utf-8")),Op}();if(i){let r=i.decode(e);if(t){let e=r.indexOf("\0");return-1!==e?r.substring(0,e):r}return r.replace(/\0/g,"")}let r,s,n,a=e.length,o="",l=0;for(;l<a;){if(r=e[l++],0===r&&t)return o;if(0!==r&&3!==r)switch(r>>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:o+=String.fromCharCode(r);break;case 12:case 13:s=e[l++],o+=String.fromCharCode((31&r)<<6|63&s);break;case 14:s=e[l++],n=e[l++],o+=String.fromCharCode((15&r)<<12|(63&s)<<6|63&n)}}return o};var Qp=function(e){let t="";for(let i=0;i<e.length;i++){let r=e[i].toString(16);r.length<2&&(r="0"+r),t+=r}return t},Zp=Math.pow(2,32)-1,Jp=[].push,em={video:1,audio:2,id3:3,text:4};function tm(e){return String.fromCharCode.apply(null,e)}function im(e,t){let i=e[t]<<8|e[t+1];return i<0?65536+i:i}function rm(e,t){let i=nm(e,t);return i<0?4294967296+i:i}function sm(e,t){let i=rm(e,t);return i*=Math.pow(2,32),i+=rm(e,t+4),i}function nm(e,t){return e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3]}function am(e,t,i){e[t]=i>>24,e[t+1]=i>>16&255,e[t+2]=i>>8&255,e[t+3]=255&i}function om(e,t){let i=[];if(!t.length)return i;let r=e.byteLength;for(let s=0;s<r;){let n=rm(e,s),a=n>1?s+n:r;if(tm(e.subarray(s+4,s+8))===t[0])if(1===t.length)i.push(e.subarray(s+8,a));else{let r=om(e.subarray(s+8,a),t.slice(1));r.length&&Jp.apply(i,r)}s=a}return i}function lm(e){let t=[],i=e[0],r=8,s=rm(e,r);r+=4;let n=0,a=0;0===i?(n=rm(e,r),a=rm(e,r+4),r+=8):(n=sm(e,r),a=sm(e,r+8),r+=16),r+=2;let o=e.length+a,l=im(e,r);r+=2;for(let i=0;i<l;i++){let i=r,n=rm(e,i);i+=4;let a=2147483647&n;if((2147483648&n)>>>31==1)return tp.warn("SIDX has hierarchical references (not supported)"),null;let l=rm(e,i);i+=4,t.push({referenceSize:a,subsegmentDuration:l,info:{duration:l/s,start:o,end:o+a-1}}),o+=a,i+=4,r=i}return{earliestPresentationTime:n,timescale:s,version:i,referencesCount:l,references:t}}function hm(e){let t=[],i=om(e,["moov","trak"]);for(let e=0;e<i.length;e++){let r=i[e],s=om(r,["tkhd"])[0];if(s){let e=s[0],i=rm(s,0===e?12:20),n=om(r,["mdia","mdhd"])[0];if(n){e=n[0];let s=rm(n,0===e?12:20),a=om(r,["mdia","hdlr"])[0];if(a){let e=tm(a.subarray(8,12)),n={soun:hp,vide:dp}[e];if(n){let e=dm(om(r,["mdia","minf","stbl","stsd"])[0]);t[i]={timescale:s,type:n},t[n]=Hf({timescale:s,id:i},e)}}}}}return om(e,["moov","mvex","trex"]).forEach((e=>{let i=rm(e,4),r=t[i];r&&(r.default={duration:rm(e,12),flags:rm(e,20)})})),t}function dm(e){let t=e.subarray(8),i=t.subarray(86),r=tm(t.subarray(4,8)),s=r,n="enca"===r||"encv"===r;if(n){let e=om(t,[r])[0].subarray("enca"===r?28:78);om(e,["sinf"]).forEach((e=>{let t=om(e,["schm"])[0];if(t){let i=tm(t.subarray(4,8));if("cbcs"===i||"cenc"===i){let t=om(e,["frma"])[0];t&&(s=tm(t))}}}))}switch(s){case"avc1":case"avc2":case"avc3":case"avc4":{let e=om(i,["avcC"])[0];s+="."+cm(e[1])+cm(e[2])+cm(e[3]);break}case"mp4a":{let e=om(t,[r])[0],i=om(e.subarray(28),["esds"])[0];if(i&&i.length>12){let e=4;if(3!==i[e++])break;e=um(i,e),e+=2;let t=i[e++];if(128&t&&(e+=2),64&t&&(e+=i[e++]),4!==i[e++])break;e=um(i,e);let r=i[e++];if(64!==r)break;if(s+="."+cm(r),e+=12,5!==i[e++])break;e=um(i,e);let n=i[e++],a=(248&n)>>3;31===a&&(a+=1+((7&n)<<3)+((224&i[e])>>5)),s+="."+a}break}case"hvc1":case"hev1":{let e=om(i,["hvcC"])[0],t=e[1],r=["","A","B","C"][t>>6],n=31&t,a=rm(e,2),o=(32&t)>>5?"H":"L",l=e[12],h=e.subarray(6,12);s+="."+r+n,s+="."+a.toString(16).toUpperCase(),s+="."+o+l;let d="";for(let e=h.length;e--;){let t=h[e];(t||d)&&(d="."+t.toString(16).toUpperCase()+d)}s+=d;break}case"dvh1":case"dvhe":{let e=om(i,["dvcC"])[0],t=e[2]>>1&127,r=e[2]<<5&32|e[3]>>3&31;s+="."+fm(t)+"."+fm(r);break}case"vp09":{let e=om(i,["vpcC"])[0],t=e[4],r=e[5],n=e[6]>>4&15;s+="."+fm(t)+"."+fm(r)+"."+fm(n);break}case"av01":{let e=om(i,["av1C"])[0],t=e[1]>>>5,r=31&e[1],n=e[2]>>>7?"H":"M",a=(64&e[2])>>6,o=(32&e[2])>>5,l=2===t&&a?o?12:10:a?10:8,h=(16&e[2])>>4,d=(8&e[2])>>3,u=(4&e[2])>>2,c=3&e[2];s+="."+t+"."+fm(r)+n+"."+fm(l)+"."+h+"."+d+u+c+"."+fm(1)+"."+fm(1)+"."+fm(1)+".0";break}}return{codec:s,encrypted:n}}function um(e,t){let i=t+5;for(;128&e[t++]&&t<i;);return t}function cm(e){return("0"+e.toString(16).toUpperCase()).slice(-2)}function fm(e){return(e<10?"0":"")+e}function pm(e){let t=om(e,["schm"])[0];if(t){let i=tm(t.subarray(4,8));if("cbcs"===i||"cenc"===i)return om(e,["schi","tenc"])[0]}return null}function mm(e){let t=rm(e,0),i=8;1&t&&(i+=4),4&t&&(i+=4);let r=0,s=rm(e,4);for(let n=0;n<s;n++){if(256&t){r+=rm(e,i),i+=4}512&t&&(i+=4),1024&t&&(i+=4),2048&t&&(i+=4)}return r}function gm(e,t){let i=new Uint8Array(e.length+t.length);return i.set(e),i.set(t,e.length),i}function vm(e,t){let i=[],r=t.samples,s=t.timescale,n=t.id,a=!1;return om(r,["moof"]).map((o=>{let l=o.byteOffset-8;om(o,["traf"]).map((o=>{let h=om(o,["tfdt"]).map((e=>{let t=e[0],i=rm(e,4);return 1===t&&(i*=Math.pow(2,32),i+=rm(e,8)),i/s}))[0];return void 0!==h&&(e=h),om(o,["tfhd"]).map((h=>{let d=rm(h,4),u=16777215&rm(h,0),c=0,f=!!(16&u),p=0,m=!!(32&u),g=8;d===n&&(!!(1&u)&&(g+=8),!!(2&u)&&(g+=4),!!(8&u)&&(c=rm(h,g),g+=4),f&&(p=rm(h,g),g+=4),m&&(g+=4),"video"===t.type&&(a=function(e){if(!e)return!1;let t=e.indexOf("."),i=t<0?e:e.substring(0,t);return"hvc1"===i||"hev1"===i||"dvh1"===i||"dvhe"===i}(t.codec)),om(o,["trun"]).map((n=>{let o=n[0],h=16777215&rm(n,0),d=!!(1&h),u=0,f=!!(4&h),m=!!(256&h),g=0,v=!!(512&h),E=0,y=!!(1024&h),b=!!(2048&h),T=0,S=rm(n,4),A=8;d&&(u=rm(n,A),A+=4),f&&(A+=4);let _=u+l;for(let l=0;l<S;l++){if(m?(g=rm(n,A),A+=4):g=c,v?(E=rm(n,A),A+=4):E=p,y&&(A+=4),b&&(T=0===o?rm(n,A):nm(n,A),A+=4),t.type===dp){let t=0;for(;t<E;){let n=rm(r,_);if(_+=4,Em(a,r[_])){ym(r.subarray(_,_+n),a?2:1,e+T/s,i)}_+=n,t+=n+4}}e+=g/s}})))}))}))})),i}function Em(e,t){if(e){let e=t>>1&63;return 39===e||40===e}return 6==(31&t)}function ym(e,t,i,r){let s=bm(e),n=0;n+=t;let a=0,o=0,l=0;for(;n<s.length;){a=0;do{if(n>=s.length)break;l=s[n++],a+=l}while(255===l);o=0;do{if(n>=s.length)break;l=s[n++],o+=l}while(255===l);let e=s.length-n,t=n;if(o<e)n+=o;else if(o>e){tp.error(`Malformed SEI payload. ${o} is too small, only ${e} bytes left to parse.`);break}if(4===a){if(181===s[t++]){let e=im(s,t);if(t+=2,49===e){let e=rm(s,t);if(t+=4,1195456820===e){let e=s[t++];if(3===e){let n=s[t++],o=64&n,l=o?2+3*(31&n):0,h=new Uint8Array(l);if(o){h[0]=n;for(let e=1;e<l;e++)h[e]=s[t++]}r.push({type:e,payloadType:a,pts:i,bytes:h})}}}}}else if(5===a&&o>16){let e=[];for(let i=0;i<16;i++){let r=s[t++].toString(16);e.push(1==r.length?"0"+r:r),(3===i||5===i||7===i||9===i)&&e.push("-")}let n=o-16,l=new Uint8Array(n);for(let e=0;e<n;e++)l[e]=s[t++];r.push({payloadType:a,pts:i,uuid:e.join(""),userData:Xp(l),userDataBytes:l})}}}function bm(e){let t=e.byteLength,i=[],r=1;for(;r<t-2;)0===e[r]&&0===e[r+1]&&3===e[r+2]?(i.push(r+2),r+=2):r++;if(0===i.length)return e;let s=t-i.length,n=new Uint8Array(s),a=0;for(r=0;r<s;a++,r++)a===i[0]&&(a++,i.shift()),n[r]=e[a];return n}function Tm(e,t,i){if(16!==e.byteLength)throw new RangeError("Invalid system id");let r,s,n;r=0,s=new Uint8Array,n=new Uint8Array;let a=new Uint8Array(4);return i&&i.byteLength>0&&new DataView(a.buffer).setUint32(0,i.byteLength,!1),function(e,...t){let i=t.length,r=8,s=i;for(;s--;)r+=t[s].byteLength;let n=new Uint8Array(r);for(n[0]=r>>24&255,n[1]=r>>16&255,n[2]=r>>8&255,n[3]=255&r,n.set(e,4),s=0,r=8;s<i;s++)n.set(t[s],r),r+=t[s].byteLength;return n}([112,115,115,104],new Uint8Array([0,0,0,0]),e,n,s,a,i||new Uint8Array)}function Sm(e){let t=e.getUint32(0),i=e.byteOffset,r=e.byteLength;if(r<t)return{offset:i,size:r};if(1886614376!==e.getUint32(4))return{offset:i,size:t};let s=e.getUint32(8)>>>24;if(0!==s&&1!==s)return{offset:i,size:t};let n=e.buffer,a=Qp(new Uint8Array(n,i+12,16)),o=e.getUint32(28),l=null,h=null;if(0===s){if(t-32<o||o<22)return{offset:i,size:t};h=new Uint8Array(n,i+32,o)}else if(1===s){if(!o||r<i+32+16*o+16)return{offset:i,size:t};l=[];for(let e=0;e<o;e++)l.push(new Uint8Array(n,i+32+16*e,16))}return{version:s,systemId:a,kids:l,data:h,offset:i,size:t}}var Am={},_m=class e{static clearKeyUriToKeyIdMap(){Am={}}constructor(e,t,i,r=[1],s=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=e,this.uri=t,this.keyFormat=i,this.keyFormatVersions=r,this.iv=s,this.encrypted=!!e&&"NONE"!==e,this.isCommonEncryption=this.encrypted&&"AES-128"!==e}isSupported(){if(this.method){if("AES-128"===this.method||"NONE"===this.method)return!0;if("identity"===this.keyFormat)return"SAMPLE-AES"===this.method;switch(this.keyFormat){case Sp:case _p:case Ap:case Tp:return-1!==["ISO-23001-7","SAMPLE-AES","SAMPLE-AES-CENC","SAMPLE-AES-CTR"].indexOf(this.method)}}return!1}getDecryptData(t){if(!this.encrypted||!this.uri)return null;if("AES-128"===this.method&&this.uri&&!this.iv){"number"!=typeof t&&("AES-128"===this.method&&!this.iv&&tp.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),t=0);let i=function(e){let t=new Uint8Array(16);for(let i=12;i<16;i++)t[i]=e>>8*(15-i)&255;return t}(t);return new e(this.method,this.uri,"identity",this.keyFormatVersions,i)}let i=vp(this.uri);if(i)switch(this.keyFormat){case _p:this.pssh=i,i.length>=22&&(this.keyId=i.subarray(i.length-22,i.length-6));break;case Ap:{let e=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=Tm(e,0,i);let t=new Uint16Array(i.buffer,i.byteOffset,i.byteLength/2),r=String.fromCharCode.apply(null,Array.from(t)),s=r.substring(r.indexOf("<"),r.length),n=(new DOMParser).parseFromString(s,"text/xml").getElementsByTagName("KID")[0];if(n){let e=n.childNodes[0]?n.childNodes[0].nodeValue:n.getAttribute("VALUE");if(e){let t=gp(e).subarray(0,16);(function(e){let t=function(e,t,i){let r=e[t];e[t]=e[i],e[i]=r};t(e,0,3),t(e,1,2),t(e,4,5),t(e,6,7)})(t),this.keyId=t}}break}default:{let e=i.subarray(0,16);if(16!==e.length){let t=new Uint8Array(16);t.set(e,16-e.length),e=t}this.keyId=e;break}}if(!this.keyId||16!==this.keyId.byteLength){let e=Am[this.uri];if(!e){let t=Object.keys(Am).length%Number.MAX_SAFE_INTEGER;e=new Uint8Array(16),new DataView(e.buffer,12,4).setUint32(0,t),Am[this.uri]=e}this.keyId=e}return this}};var wm=/\{\$([a-zA-Z0-9-_]+)\}/g;function km(e){return wm.test(e)}function Lm(e,t,i){if(null!==e.variableList||e.hasVariableRefs)for(let r=i.length;r--;){let s=i[r],n=t[s];n&&(t[s]=Rm(e,n))}}function Rm(e,t){if(null!==e.variableList||e.hasVariableRefs){let i=e.variableList;return t.replace(wm,(t=>{let r=t.substring(2,t.length-1),s=i?.[r];return void 0===s?(e.playlistParsingError||(e.playlistParsingError=new Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${r}"`)),t):s}))}return t}function Im(e,t,i){let r,s,n=e.variableList;if(n||(e.variableList=n={}),"QUERYPARAM"in t){r=t.QUERYPARAM;try{let e=new self.URL(i).searchParams;if(!e.has(r))throw new Error(`"${r}" does not match any query parameter in URI: "${i}"`);s=e.get(r)}catch(t){e.playlistParsingError||(e.playlistParsingError=new Error(`EXT-X-DEFINE QUERYPARAM: ${t.message}`))}}else r=t.NAME,s=t.VALUE;r in n?e.playlistParsingError||(e.playlistParsingError=new Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${r}"`)):n[r]=s||""}function Cm(e,t,i){let r=t.IMPORT;if(i&&r in i){let t=e.variableList;t||(e.variableList=t={}),t[r]=i[r]}else e.playlistParsingError||(e.playlistParsingError=new Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${r}"`))}function Dm(e=!0){return typeof self>"u"?void 0:(e||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}var xm={audio:{a3ds:1,"ac-3":.95,"ac-4":1,alac:.9,alaw:1,dra1:1,"dts+":1,"dts-":1,dtsc:1,dtse:1,dtsh:1,"ec-3":.9,enca:1,fLaC:.9,flac:.9,FLAC:.9,g719:1,g726:1,m4ae:1,mha1:1,mha2:1,mhm1:1,mhm2:1,mlpa:1,mp4a:1,"raw ":1,Opus:1,opus:1,samr:1,sawb:1,sawp:1,sevc:1,sqcp:1,ssmv:1,twos:1,ulaw:1},video:{avc1:1,avc2:1,avc3:1,avc4:1,avcp:1,av01:.8,drac:1,dva1:1,dvav:1,dvh1:.7,dvhe:.7,encv:1,hev1:.75,hvc1:.75,mjp2:1,mp4v:1,mvc1:1,mvc2:1,mvc3:1,mvc4:1,resv:1,rv60:1,s263:1,svc1:1,svc2:1,"vc-1":1,vp08:1,vp09:.9},text:{stpp:1,wvtt:1}};function Mm(e,t,i=!0){return!e.split(",").some((e=>!Pm(e,t,i)))}function Pm(e,t,i=!0){var r;let s=Dm(i);return null!=(r=s?.isTypeSupported(Om(e,t)))&&r}function Om(e,t){return`${t}/mp4;codecs="${e}"`}function Um(e){if(e){let t=e.substring(0,4);return xm.video[t]}return 2}function Nm(e){return e.split(",").reduce(((e,t)=>{let i=xm.video[t];return i?(2*i+e)/(e?3:2):(xm.audio[t]+e)/(e?2:1)}),0)}var $m={};var Fm=/flac|opus/i;function Bm(e,t=!0){return e.replace(Fm,(e=>function(e,t=!0){if($m[e])return $m[e];let i={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"]}[e];for(let r=0;r<i.length;r++)if(Pm(i[r],"audio",t))return $m[e]=i[r],i[r];return e}(e.toLowerCase(),t)))}function Hm(e,t){return e&&"mp4a"!==e?e:t&&t.split(",")[0]}var Gm=/#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,jm=/#EXT-X-MEDIA:(.*)/g,Vm=/^#EXT(?:INF|-X-TARGETDURATION):/m,Km=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#EXT-X-BYTERANGE:*(.+)/.source,/#EXT-X-PROGRAM-DATE-TIME:(.+)/.source,/#.*/.source].join("|"),"g"),Wm=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|INDEPENDENT-SEGMENTS)/.source,/(#)([^:]*):(.*)/.source,/(#)(.*)(?:.*)\r?\n?/.source].join("|")),qm=class e{static findGroup(e,t){for(let i=0;i<e.length;i++){let r=e[i];if(r.id===t)return r}}static resolve(e,t){return Ff.buildAbsoluteURL(t,e,{alwaysNormalize:!0})}static isMediaPlaylist(e){return Vm.test(e)}static parseMasterPlaylist(t,i){let r,s={contentSteering:null,levels:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:km(t)},n=[];for(Gm.lastIndex=0;null!=(r=Gm.exec(t));)if(r[1]){var a;let t=new sp(r[1]);Lm(s,t,["CODECS","SUPPLEMENTAL-CODECS","ALLOWED-CPC","PATHWAY-ID","STABLE-VARIANT-ID","AUDIO","VIDEO","SUBTITLES","CLOSED-CAPTIONS","NAME"]);let o=Rm(s,r[2]),l={attrs:t,bitrate:t.decimalInteger("BANDWIDTH")||t.decimalInteger("AVERAGE-BANDWIDTH"),name:t.NAME,url:e.resolve(o,i)},h=t.decimalResolution("RESOLUTION");h&&(l.width=h.width,l.height=h.height),Xm(t.CODECS,l),null!=(a=l.unknownCodecs)&&a.length||n.push(l),s.levels.push(l)}else if(r[3]){let t=r[3],n=r[4];switch(t){case"SESSION-DATA":{let e=new sp(n);Lm(s,e,["DATA-ID","LANGUAGE","VALUE","URI"]);let t=e["DATA-ID"];t&&(null===s.sessionData&&(s.sessionData={}),s.sessionData[t]=e);break}case"SESSION-KEY":{let e=Ym(n,i,s);e.encrypted&&e.isSupported()?(null===s.sessionKeys&&(s.sessionKeys=[]),s.sessionKeys.push(e)):tp.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${n}"`);break}case"DEFINE":{let e=new sp(n);Lm(s,e,["NAME","VALUE","QUERYPARAM"]),Im(s,e,i)}break;case"CONTENT-STEERING":{let t=new sp(n);Lm(s,t,["SERVER-URI","PATHWAY-ID"]),s.contentSteering={uri:e.resolve(t["SERVER-URI"],i),pathwayId:t["PATHWAY-ID"]||"."};break}case"START":s.startTimeOffset=zm(n)}}let o=n.length>0&&n.length<s.levels.length;return s.levels=o?n:s.levels,0===s.levels.length&&(s.playlistParsingError=new Error("no levels found in manifest")),s}static parseMasterPlaylistMedia(t,i,r){let s,n={},a=r.levels,o={AUDIO:a.map((e=>({id:e.attrs.AUDIO,audioCodec:e.audioCodec}))),SUBTITLES:a.map((e=>({id:e.attrs.SUBTITLES,textCodec:e.textCodec}))),"CLOSED-CAPTIONS":[]},l=0;for(jm.lastIndex=0;null!==(s=jm.exec(t));){let t=new sp(s[1]),a=t.TYPE;if(a){let s=o[a],h=n[a]||[];n[a]=h,Lm(r,t,["URI","GROUP-ID","LANGUAGE","ASSOC-LANGUAGE","STABLE-RENDITION-ID","NAME","INSTREAM-ID","CHARACTERISTICS","CHANNELS"]);let d=t.LANGUAGE,u=t["ASSOC-LANGUAGE"],c=t.CHANNELS,f=t.CHARACTERISTICS,p=t["INSTREAM-ID"],m={attrs:t,bitrate:0,id:l++,groupId:t["GROUP-ID"]||"",name:t.NAME||d||"",type:a,default:t.bool("DEFAULT"),autoselect:t.bool("AUTOSELECT"),forced:t.bool("FORCED"),lang:d,url:t.URI?e.resolve(t.URI,i):""};if(u&&(m.assocLang=u),c&&(m.channels=c),f&&(m.characteristics=f),p&&(m.instreamId=p),null!=s&&s.length){let t=e.findGroup(s,m.groupId)||s[0];Qm(m,t,"audioCodec"),Qm(m,t,"textCodec")}h.push(m)}}return n}static parseLevelPlaylist(e,t,i,r,s,n){let a,o,l,h=new mp(t),d=h.fragments,u=null,c=0,f=0,p=0,m=0,g=null,v=new fp(r,t),E=-1,y=!1,b=null;for(Km.lastIndex=0,h.m3u8=e,h.hasVariableRefs=km(e);null!==(a=Km.exec(e));){y&&(y=!1,v=new fp(r,t),v.start=p,v.sn=c,v.cc=m,v.level=i,u&&(v.initSegment=u,v.rawProgramDateTime=u.rawProgramDateTime,u.rawProgramDateTime=null,b&&(v.setByteRange(b),b=null)));let e=a[1];if(e){v.duration=parseFloat(e);let t=(" "+a[2]).slice(1);v.title=t||null,v.tagList.push(t?["INF",e,t]:["INF",e])}else if(a[3]){if(Kf(v.duration)){v.start=p,l&&eg(v,l,h),v.sn=c,v.level=i,v.cc=m,d.push(v);let e=(" "+a[3]).slice(1);v.relurl=Rm(h,e),Zm(v,g),g=v,p+=v.duration,c++,f=0,y=!0}}else if(a[4]){let e=(" "+a[4]).slice(1);g?v.setByteRange(e,g):v.setByteRange(e)}else if(a[5])v.rawProgramDateTime=(" "+a[5]).slice(1),v.tagList.push(["PROGRAM-DATE-TIME",v.rawProgramDateTime]),-1===E&&(E=d.length);else{if(a=a[0].match(Wm),!a){tp.warn("No matches on slow regex match for level playlist!");continue}for(o=1;o<a.length&&!(typeof a[o]<"u");o++);let e=(" "+a[o]).slice(1),s=(" "+a[o+1]).slice(1),p=a[o+2]?(" "+a[o+2]).slice(1):"";switch(e){case"PLAYLIST-TYPE":h.type=s.toUpperCase();break;case"MEDIA-SEQUENCE":c=h.startSN=parseInt(s);break;case"SKIP":{let e=new sp(s);Lm(h,e,["RECENTLY-REMOVED-DATERANGES"]);let t=e.decimalInteger("SKIPPED-SEGMENTS");if(Kf(t)){h.skippedSegments=t;for(let e=t;e--;)d.unshift(null);c+=t}let i=e.enumeratedString("RECENTLY-REMOVED-DATERANGES");i&&(h.recentlyRemovedDateranges=i.split("\t"));break}case"TARGETDURATION":h.targetduration=Math.max(parseInt(s),1);break;case"VERSION":h.version=parseInt(s);break;case"INDEPENDENT-SEGMENTS":case"EXTM3U":break;case"ENDLIST":h.live=!1;break;case"#":(s||p)&&v.tagList.push(p?[s,p]:[s]);break;case"DISCONTINUITY":m++,v.tagList.push(["DIS"]);break;case"GAP":v.gap=!0,v.tagList.push([e]);break;case"BITRATE":v.tagList.push([e,s]);break;case"DATERANGE":{let e=new sp(s);Lm(h,e,["ID","CLASS","START-DATE","END-DATE","SCTE35-CMD","SCTE35-OUT","SCTE35-IN"]),Lm(h,e,e.clientAttrs);let t=new op(e,h.dateRanges[e.ID]);t.isValid||h.skippedSegments?h.dateRanges[t.id]=t:tp.warn(`Ignoring invalid DATERANGE tag: "${s}"`),v.tagList.push(["EXT-X-DATERANGE",s]);break}case"DEFINE":{let e=new sp(s);Lm(h,e,["NAME","VALUE","IMPORT","QUERYPARAM"]),"IMPORT"in e?Cm(h,e,n):Im(h,e,t)}break;case"DISCONTINUITY-SEQUENCE":m=parseInt(s);break;case"KEY":{let e=Ym(s,t,h);if(e.isSupported()){if("NONE"===e.method){l=void 0;break}l||(l={}),l[e.keyFormat]&&(l=Vf({},l)),l[e.keyFormat]=e}else tp.warn(`[Keys] Ignoring invalid EXT-X-KEY tag: "${s}"`);break}case"START":h.startTimeOffset=zm(s);break;case"MAP":{let e=new sp(s);if(Lm(h,e,["BYTERANGE","URI"]),v.duration){let s=new fp(r,t);Jm(s,e,i,l),u=s,v.initSegment=u,u.rawProgramDateTime&&!v.rawProgramDateTime&&(v.rawProgramDateTime=u.rawProgramDateTime)}else{let t=v.byteRangeEndOffset;if(t){let e=v.byteRangeStartOffset;b=`${t-e}@${e}`}else b=null;Jm(v,e,i,l),u=v,y=!0}break}case"SERVER-CONTROL":{let e=new sp(s);h.canBlockReload=e.bool("CAN-BLOCK-RELOAD"),h.canSkipUntil=e.optionalFloat("CAN-SKIP-UNTIL",0),h.canSkipDateRanges=h.canSkipUntil>0&&e.bool("CAN-SKIP-DATERANGES"),h.partHoldBack=e.optionalFloat("PART-HOLD-BACK",0),h.holdBack=e.optionalFloat("HOLD-BACK",0);break}case"PART-INF":{let e=new sp(s);h.partTarget=e.decimalFloatingPoint("PART-TARGET");break}case"PART":{let e=h.partList;e||(e=h.partList=[]);let i=f>0?e[e.length-1]:void 0,r=f++,n=new sp(s);Lm(h,n,["BYTERANGE","URI"]);let a=new pp(n,v,t,r,i);e.push(a),v.duration+=a.duration;break}case"PRELOAD-HINT":{let e=new sp(s);Lm(h,e,["URI"]),h.preloadHint=e;break}case"RENDITION-REPORT":{let e=new sp(s);Lm(h,e,["URI"]),h.renditionReports=h.renditionReports||[],h.renditionReports.push(e);break}default:tp.warn(`line parsed but not handled: ${a}`)}}}g&&!g.relurl?(d.pop(),p-=g.duration,h.partList&&(h.fragmentHint=g)):h.partList&&(Zm(v,g),v.cc=m,h.fragmentHint=v,l&&eg(v,l,h));let T=d.length,S=d[0],A=d[T-1];if(p+=h.skippedSegments*h.targetduration,p>0&&T&&A){h.averagetargetduration=p/T;let e=A.sn;h.endSN="initSegment"!==e?e:0,h.live||(A.endList=!0),S&&(h.startCC=S.cc)}else h.endSN=0,h.startCC=0;return h.fragmentHint&&(p+=h.fragmentHint.duration),h.totalduration=p,h.endCC=m,E>0&&function(e,t){let i=e[t];for(let r=t;r--;){let t=e[r];if(!t)return;t.programDateTime=i.programDateTime-1e3*t.duration,i=t}}(d,E),h}};function Ym(e,t,i){var r,s;let n=new sp(e);Lm(i,n,["KEYFORMAT","KEYFORMATVERSIONS","URI","IV","URI"]);let a=null!=(r=n.METHOD)?r:"",o=n.URI,l=n.hexadecimalInteger("IV"),h=n.KEYFORMATVERSIONS,d=null!=(s=n.KEYFORMAT)?s:"identity";o&&n.IV&&!l&&tp.error(`Invalid IV: ${n.IV}`);let u=o?qm.resolve(o,t):"",c=(h||"1").split("/").map(Number).filter(Number.isFinite);return new _m(a,u,d,c,l)}function zm(e){let t=new sp(e).decimalFloatingPoint("TIME-OFFSET");return Kf(t)?t:null}function Xm(e,t){let i=(e||"").split(/[ ,]+/).filter((e=>e));["video","audio","text"].forEach((e=>{let r=i.filter((t=>function(e,t){let i=xm[t];return!!i&&!!i[e.slice(0,4)]}(t,e)));r.length&&(t[`${e}Codec`]=r.join(","),i=i.filter((e=>-1===r.indexOf(e))))})),t.unknownCodecs=i}function Qm(e,t,i){let r=t[i];r&&(e[i]=r)}function Zm(e,t){e.rawProgramDateTime?e.programDateTime=Date.parse(e.rawProgramDateTime):null!=t&&t.programDateTime&&(e.programDateTime=t.endProgramDateTime),Kf(e.programDateTime)||(e.programDateTime=null,e.rawProgramDateTime=null)}function Jm(e,t,i,r){e.relurl=t.URI,t.BYTERANGE&&e.setByteRange(t.BYTERANGE),e.level=i,e.sn="initSegment",r&&(e.levelkeys=r),e.initSegment=null}function eg(e,t,i){e.levelkeys=t;let{encryptedFragments:r}=i;(!r.length||r[r.length-1].levelkeys!==t)&&Object.keys(t).some((e=>t[e].isCommonEncryption))&&r.push(e)}var tg="manifest",ig="level",rg="audioTrack",sg="subtitleTrack",ng="main",ag="audio",og="subtitle";function lg(e){let{type:t}=e;switch(t){case rg:return ag;case sg:return og;default:return ng}}function hg(e,t){let i=e.url;return(void 0===i||0===i.indexOf("data:"))&&(i=t.url),i}var dg=class{constructor(e){this.hls=void 0,this.loaders=Object.create(null),this.variableList=null,this.hls=e,this.registerListeners()}startLoad(e){}stopLoad(){this.destroyInternalLoaders()}registerListeners(){let{hls:e}=this;e.on(Yf.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Yf.LEVEL_LOADING,this.onLevelLoading,this),e.on(Yf.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.on(Yf.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this)}unregisterListeners(){let{hls:e}=this;e.off(Yf.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Yf.LEVEL_LOADING,this.onLevelLoading,this),e.off(Yf.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.off(Yf.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this)}createInternalLoader(e){let t=this.hls.config,i=t.pLoader,r=t.loader,s=new(i||r)(t);return this.loaders[e.type]=s,s}getInternalLoader(e){return this.loaders[e.type]}resetInternalLoader(e){this.loaders[e]&&delete this.loaders[e]}destroyInternalLoaders(){for(let e in this.loaders){let t=this.loaders[e];t&&t.destroy(),this.resetInternalLoader(e)}}destroy(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders()}onManifestLoading(e,t){let{url:i}=t;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:tg,url:i,deliveryDirectives:null})}onLevelLoading(e,t){let{id:i,level:r,pathwayId:s,url:n,deliveryDirectives:a}=t;this.load({id:i,level:r,pathwayId:s,responseType:"text",type:ig,url:n,deliveryDirectives:a})}onAudioTrackLoading(e,t){let{id:i,groupId:r,url:s,deliveryDirectives:n}=t;this.load({id:i,groupId:r,level:null,responseType:"text",type:rg,url:s,deliveryDirectives:n})}onSubtitleTrackLoading(e,t){let{id:i,groupId:r,url:s,deliveryDirectives:n}=t;this.load({id:i,groupId:r,level:null,responseType:"text",type:sg,url:s,deliveryDirectives:n})}load(e){var t;let i,r=this.hls.config,s=this.getInternalLoader(e);if(s){let t=s.context;if(t&&t.url===e.url&&t.level===e.level)return void tp.trace("[playlist-loader]: playlist request ongoing");tp.log(`[playlist-loader]: aborting previous loader for type: ${e.type}`),s.abort()}if(i=e.type===tg?r.manifestLoadPolicy.default:Vf({},r.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),s=this.createInternalLoader(e),Kf(null==(t=e.deliveryDirectives)?void 0:t.part)){let t;if(e.type===ig&&null!==e.level?t=this.hls.levels[e.level].details:e.type===rg&&null!==e.id?t=this.hls.audioTracks[e.id].details:e.type===sg&&null!==e.id&&(t=this.hls.subtitleTracks[e.id].details),t){let e=t.partTarget,r=t.targetduration;if(e&&r){let t=1e3*Math.max(3*e,.8*r);i=Vf({},i,{maxTimeToFirstByteMs:Math.min(t,i.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(t,i.maxTimeToFirstByteMs)})}}}let n=i.errorRetry||i.timeoutRetry||{},a={loadPolicy:i,timeout:i.maxLoadTimeMs,maxRetry:n.maxNumRetry||0,retryDelay:n.retryDelayMs||0,maxRetryDelay:n.maxRetryDelayMs||0},o={onSuccess:(e,t,i,r)=>{let s=this.getInternalLoader(i);this.resetInternalLoader(i.type);let n=e.data;0===n.indexOf("#EXTM3U")?(t.parsing.start=performance.now(),qm.isMediaPlaylist(n)?this.handleTrackOrLevelPlaylist(e,t,i,r||null,s):this.handleMasterPlaylist(e,t,i,r)):this.handleManifestParsingError(e,i,new Error("no EXTM3U delimiter"),r||null,t)},onError:(e,t,i,r)=>{this.handleNetworkError(t,i,!1,e,r)},onTimeout:(e,t,i)=>{this.handleNetworkError(t,i,!0,void 0,e)}};s.load(e,a,o)}handleMasterPlaylist(e,t,i,r){let s=this.hls,n=e.data,a=hg(e,i),o=qm.parseMasterPlaylist(n,a);if(o.playlistParsingError)return void this.handleManifestParsingError(e,i,o.playlistParsingError,r,t);let{contentSteering:l,levels:h,sessionData:d,sessionKeys:u,startTimeOffset:c,variableList:f}=o;this.variableList=f;let{AUDIO:p=[],SUBTITLES:m,"CLOSED-CAPTIONS":g}=qm.parseMasterPlaylistMedia(n,a,o);p.length&&!p.some((e=>!e.url))&&h[0].audioCodec&&!h[0].attrs.AUDIO&&(tp.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),p.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new sp({}),bitrate:0,url:""})),s.trigger(Yf.MANIFEST_LOADED,{levels:h,audioTracks:p,subtitles:m,captions:g,contentSteering:l,url:a,stats:t,networkDetails:r,sessionData:d,sessionKeys:u,startTimeOffset:c,variableList:f})}handleTrackOrLevelPlaylist(e,t,i,r,s){let n=this.hls,{id:a,level:o,type:l}=i,h=hg(e,i),d=Kf(o)?o:Kf(a)?a:0,u=lg(i),c=qm.parseLevelPlaylist(e.data,h,d,u,0,this.variableList);if(l===tg){let e={attrs:new sp({}),bitrate:0,details:c,name:"",url:h};n.trigger(Yf.MANIFEST_LOADED,{levels:[e],audioTracks:[],url:h,stats:t,networkDetails:r,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}t.parsing.end=performance.now(),i.levelDetails=c,this.handlePlaylistLoaded(c,e,t,i,r,s)}handleManifestParsingError(e,t,i,r,s){this.hls.trigger(Yf.ERROR,{type:zf.NETWORK_ERROR,details:Xf.MANIFEST_PARSING_ERROR,fatal:t.type===tg,url:e.url,err:i,error:i,reason:i.message,response:e,context:t,networkDetails:r,stats:s})}handleNetworkError(e,t,i=!1,r,s){let n=`A network ${i?"timeout":"error"+(r?" (status "+r.code+")":"")} occurred while loading ${e.type}`;e.type===ig?n+=`: ${e.level} id: ${e.id}`:(e.type===rg||e.type===sg)&&(n+=` id: ${e.id} group-id: "${e.groupId}"`);let a=new Error(n);tp.warn(`[playlist-loader]: ${n}`);let o=Xf.UNKNOWN,l=!1,h=this.getInternalLoader(e);switch(e.type){case tg:o=i?Xf.MANIFEST_LOAD_TIMEOUT:Xf.MANIFEST_LOAD_ERROR,l=!0;break;case ig:o=i?Xf.LEVEL_LOAD_TIMEOUT:Xf.LEVEL_LOAD_ERROR,l=!1;break;case rg:o=i?Xf.AUDIO_TRACK_LOAD_TIMEOUT:Xf.AUDIO_TRACK_LOAD_ERROR,l=!1;break;case sg:o=i?Xf.SUBTITLE_TRACK_LOAD_TIMEOUT:Xf.SUBTITLE_LOAD_ERROR,l=!1}h&&this.resetInternalLoader(e.type);let d={type:zf.NETWORK_ERROR,details:o,fatal:l,url:e.url,loader:h,context:e,error:a,networkDetails:t,stats:s};if(r){let i=t?.url||e.url;d.response=Hf({url:i,data:void 0},r)}this.hls.trigger(Yf.ERROR,d)}handlePlaylistLoaded(e,t,i,r,s,n){let a=this.hls,{type:o,level:l,id:h,groupId:d,deliveryDirectives:u}=r,c=hg(t,r),f=lg(r),p="number"==typeof r.level&&f===ng?l:void 0;if(!e.fragments.length){let e=new Error("No Segments found in Playlist");return void a.trigger(Yf.ERROR,{type:zf.NETWORK_ERROR,details:Xf.LEVEL_EMPTY_ERROR,fatal:!1,url:c,error:e,reason:e.message,response:t,context:r,level:p,parent:f,networkDetails:s,stats:i})}e.targetduration||(e.playlistParsingError=new Error("Missing Target Duration"));let m=e.playlistParsingError;if(m)a.trigger(Yf.ERROR,{type:zf.NETWORK_ERROR,details:Xf.LEVEL_PARSING_ERROR,fatal:!1,url:c,error:m,reason:m.message,response:t,context:r,level:p,parent:f,networkDetails:s,stats:i});else switch(e.live&&n&&(n.getCacheAge&&(e.ageHeader=n.getCacheAge()||0),(!n.getCacheAge||isNaN(e.ageHeader))&&(e.ageHeader=0)),o){case tg:case ig:a.trigger(Yf.LEVEL_LOADED,{details:e,level:p||0,id:h||0,stats:i,networkDetails:s,deliveryDirectives:u});break;case rg:a.trigger(Yf.AUDIO_TRACK_LOADED,{details:e,id:h||0,groupId:d||"",stats:i,networkDetails:s,deliveryDirectives:u});break;case sg:a.trigger(Yf.SUBTITLE_TRACK_LOADED,{details:e,id:h||0,groupId:d||"",stats:i,networkDetails:s,deliveryDirectives:u})}}};function ug(e,t){let i;try{i=new Event("addtrack")}catch{i=document.createEvent("Event"),i.initEvent("addtrack",!1,!1)}i.track=e,t.dispatchEvent(i)}function cg(e,t){let i=e.mode;if("disabled"===i&&(e.mode="hidden"),e.cues&&!e.cues.getCueById(t.id))try{if(e.addCue(t),!e.cues.getCueById(t.id))throw new Error(`addCue is failed for: ${t}`)}catch(i){tp.debug(`[texttrack-utils]: ${i}`);try{let i=new self.TextTrackCue(t.startTime,t.endTime,t.text);i.id=t.id,e.addCue(i)}catch(e){tp.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${e}`)}}"disabled"===i&&(e.mode=i)}function fg(e){let t=e.mode;if("disabled"===t&&(e.mode="hidden"),e.cues)for(let t=e.cues.length;t--;)e.removeCue(e.cues[t]);"disabled"===t&&(e.mode=t)}function pg(e,t,i,r){let s=e.mode;if("disabled"===s&&(e.mode="hidden"),e.cues&&e.cues.length>0){let s=function(e,t,i){let r=[],s=function(e,t){if(t<e[0].startTime)return 0;let i=e.length-1;if(t>e[i].endTime)return-1;let r=0,s=i;for(;r<=s;){let n=Math.floor((s+r)/2);if(t<e[n].startTime)s=n-1;else{if(!(t>e[n].startTime&&r<i))return n;r=n+1}}return e[r].startTime-t<t-e[s].startTime?r:s}(e,t);if(s>-1)for(let n=s,a=e.length;n<a;n++){let s=e[n];if(s.startTime>=t&&s.endTime<=i)r.push(s);else if(s.startTime>i)return r}return r}(e.cues,t,i);for(let t=0;t<s.length;t++)(!r||r(s[t]))&&e.removeCue(s[t])}"disabled"===s&&(e.mode=s)}function mg(e){let t=[];for(let i=0;i<e.length;i++){let r=e[i];("subtitles"===r.kind||"captions"===r.kind)&&r.label&&t.push(e[i])}return t}var gg="org.id3",vg="com.apple.quicktime.HLS",Eg="https://aomedia.org/emsg/ID3";function yg(){if(!(typeof self>"u"))return self.VTTCue||self.TextTrackCue}function bg(e,t,i,r,s){let n=new e(t,i,"");try{n.value=r,s&&(n.type=s)}catch{n=new e(t,i,JSON.stringify(s?Hf({type:s},r):r))}return n}var Tg=(()=>{let e=yg();try{e&&new e(0,Number.POSITIVE_INFINITY,"")}catch{return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();function Sg(e,t){return e.getTime()/1e3-t}function Ag(e){return Uint8Array.from(e.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer}var _g=class{constructor(e){this.hls=void 0,this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=e,this._registerListeners()}destroy(){this._unregisterListeners(),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=null}_registerListeners(){let{hls:e}=this;e.on(Yf.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(Yf.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(Yf.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Yf.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.on(Yf.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(Yf.LEVEL_UPDATED,this.onLevelUpdated,this)}_unregisterListeners(){let{hls:e}=this;e.off(Yf.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(Yf.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(Yf.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Yf.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.off(Yf.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(Yf.LEVEL_UPDATED,this.onLevelUpdated,this)}onMediaAttached(e,t){this.media=t.media}onMediaDetaching(){this.id3Track&&(fg(this.id3Track),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={})}onManifestLoading(){this.dateRangeCuesAppended={}}createTrack(e){let t=this.getID3Track(e.textTracks);return t.mode="hidden",t}getID3Track(e){if(this.media){for(let t=0;t<e.length;t++){let i=e[t];if("metadata"===i.kind&&"id3"===i.label)return ug(i,this.media),i}return this.media.addTextTrack("metadata","id3")}}onFragParsingMetadata(e,t){if(!this.media)return;let{hls:{config:{enableEmsgMetadataCues:i,enableID3MetadataCues:r}}}=this;if(!i&&!r)return;let{samples:s}=t;this.id3Track||(this.id3Track=this.createTrack(this.media));let n=yg();if(n)for(let e=0;e<s.length;e++){let t=s[e].type;if(t===Eg&&!i||!r)continue;let a=Vp(s[e].data);if(a){let i=s[e].pts,r=i+s[e].duration;r>Tg&&(r=Tg),r-i<=0&&(r=i+.25);for(let e=0;e<a.length;e++){let s=a[e];if(!Gp(s)){this.updateId3CueEnds(i,t);let e=bg(n,i,r,s,t);e&&this.id3Track.addCue(e)}}}}}updateId3CueEnds(e,t){var i;let r=null==(i=this.id3Track)?void 0:i.cues;if(r)for(let i=r.length;i--;){let s=r[i];s.type===t&&s.startTime<e&&s.endTime===Tg&&(s.endTime=e)}}onBufferFlushing(e,{startOffset:t,endOffset:i,type:r}){let{id3Track:s,hls:n}=this;if(!n)return;let{config:{enableEmsgMetadataCues:a,enableID3MetadataCues:o}}=n;if(s&&(a||o)){let e;e="audio"===r?e=>e.type===gg&&o:"video"===r?e=>e.type===Eg&&a:e=>e.type===gg&&o||e.type===Eg&&a,pg(s,t,i,e)}}onLevelUpdated(e,{details:t}){if(!this.media||!t.hasProgramDateTime||!this.hls.config.enableDateRangeMetadataCues)return;let{dateRangeCuesAppended:i,id3Track:r}=this,{dateRanges:s}=t,n=Object.keys(s);if(r){let e=Object.keys(i).filter((e=>!n.includes(e)));for(let t=e.length;t--;){let s=e[t];Object.keys(i[s].cues).forEach((e=>{r.removeCue(i[s].cues[e])})),delete i[s]}}let a=t.fragments[t.fragments.length-1];if(0===n.length||!Kf(a?.programDateTime))return;this.id3Track||(this.id3Track=this.createTrack(this.media));let o=a.programDateTime/1e3-a.start,l=yg();for(let e=0;e<n.length;e++){let t=n[e],r=s[t],a=Sg(r.startDate,o),h=i[t],d=h?.cues||{},u=h?.durationKnown||!1,c=Tg,f=r.endDate;if(f)c=Sg(f,o),u=!0;else if(r.endOnNext&&!u){let e=n.reduce(((e,t)=>{if(t!==r.id){let i=s[t];if(i.class===r.class&&i.startDate>r.startDate&&(!e||r.startDate<e.startDate))return i}return e}),null);e&&(c=Sg(e.startDate,o),u=!0)}let p=Object.keys(r.attr);for(let e=0;e<p.length;e++){let i=p[e];if(!np(i))continue;let s=d[i];if(s)u&&!h.durationKnown&&(s.endTime=c);else if(l){let e=r.attr[i];ap(i)&&(e=Ag(e));let s=bg(l,a,c,{key:i,data:e},vg);s&&(s.id=t,this.id3Track.addCue(s),d[i]=s)}}i[t]={cues:d,dateRange:r,durationKnown:u}}}},wg=class{constructor(e){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=e,this.config=e.config,this.registerListeners()}get latency(){return this._latency||0}get maxLatency(){let{config:e,levelDetails:t}=this;return void 0!==e.liveMaxLatencyDuration?e.liveMaxLatencyDuration:t?e.liveMaxLatencyDurationCount*t.targetduration:0}get targetLatency(){let{levelDetails:e}=this;if(null===e)return null;let{holdBack:t,partHoldBack:i,targetduration:r}=e,{liveSyncDuration:s,liveSyncDurationCount:n,lowLatencyMode:a}=this.config,o=this.hls.userConfig,l=a&&i||t;(o.liveSyncDuration||o.liveSyncDurationCount||0===l)&&(l=void 0!==s?s:n*r);let h=r;return l+Math.min(1*this.stallCount,h)}get liveSyncPosition(){let e=this.estimateLiveEdge(),t=this.targetLatency,i=this.levelDetails;if(null===e||null===t||null===i)return null;let r=i.edge,s=e-t-this.edgeStalled,n=r-i.totalduration,a=r-(this.config.lowLatencyMode&&i.partTarget||i.targetduration);return Math.min(Math.max(n,s),a)}get drift(){let{levelDetails:e}=this;return null===e?1:e.drift}get edgeStalled(){let{levelDetails:e}=this;if(null===e)return 0;let t=3*(this.config.lowLatencyMode&&e.partTarget||e.targetduration);return Math.max(e.age-t,0)}get forwardBufferLength(){let{media:e,levelDetails:t}=this;if(!e||!t)return 0;let i=e.buffered.length;return(i?e.buffered.end(i-1):t.edge)-this.currentTime}destroy(){this.unregisterListeners(),this.onMediaDetaching(),this.levelDetails=null,this.hls=this.timeupdateHandler=null}registerListeners(){this.hls.on(Yf.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(Yf.MEDIA_DETACHING,this.onMediaDetaching,this),this.hls.on(Yf.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(Yf.LEVEL_UPDATED,this.onLevelUpdated,this),this.hls.on(Yf.ERROR,this.onError,this)}unregisterListeners(){this.hls.off(Yf.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(Yf.MEDIA_DETACHING,this.onMediaDetaching,this),this.hls.off(Yf.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(Yf.LEVEL_UPDATED,this.onLevelUpdated,this),this.hls.off(Yf.ERROR,this.onError,this)}onMediaAttached(e,t){this.media=t.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(e,{details:t}){this.levelDetails=t,t.advanced&&this.timeupdate(),!t.live&&this.media&&this.media.removeEventListener("timeupdate",this.timeupdateHandler)}onError(e,t){var i;t.details===Xf.BUFFER_STALLED_ERROR&&(this.stallCount++,null!=(i=this.levelDetails)&&i.live&&tp.warn("[playback-rate-controller]: Stall detected, adjusting target latency"))}timeupdate(){let{media:e,levelDetails:t}=this;if(!e||!t)return;this.currentTime=e.currentTime;let i=this.computeLatency();if(null===i)return;this._latency=i;let{lowLatencyMode:r,maxLiveSyncPlaybackRate:s}=this.config;if(!r||1===s||!t.live)return;let n=this.targetLatency;if(null===n)return;let a=i-n;if(a<Math.min(this.maxLatency,n+t.targetduration)&&a>.05&&this.forwardBufferLength>1){let t=Math.min(2,Math.max(1,s)),i=Math.round(2/(1+Math.exp(-.75*a-this.edgeStalled))*20)/20;e.playbackRate=Math.min(t,Math.max(1,i))}else 1!==e.playbackRate&&0!==e.playbackRate&&(e.playbackRate=1)}estimateLiveEdge(){let{levelDetails:e}=this;return null===e?null:e.edge+e.age}computeLatency(){let e=this.estimateLiveEdge();return null===e?null:e-this.currentTime}},kg=["NONE","TYPE-0","TYPE-1",null];var Lg=["SDR","PQ","HLG"];var Rg="",Ig="YES",Cg="v2";function Dg(e){let{canSkipUntil:t,canSkipDateRanges:i,age:r}=e;return t&&r<t/2?i?Cg:Ig:Rg}var xg=class{constructor(e,t,i){this.msn=void 0,this.part=void 0,this.skip=void 0,this.msn=e,this.part=t,this.skip=i}addDirectives(e){let t=new self.URL(e);return void 0!==this.msn&&t.searchParams.set("_HLS_msn",this.msn.toString()),void 0!==this.part&&t.searchParams.set("_HLS_part",this.part.toString()),this.skip&&t.searchParams.set("_HLS_skip",this.skip),t.href}},Mg=class{constructor(e){this._attrs=void 0,this.audioCodec=void 0,this.bitrate=void 0,this.codecSet=void 0,this.url=void 0,this.frameRate=void 0,this.height=void 0,this.id=void 0,this.name=void 0,this.videoCodec=void 0,this.width=void 0,this.details=void 0,this.fragmentError=0,this.loadError=0,this.loaded=void 0,this.realBitrate=0,this.supportedPromise=void 0,this.supportedResult=void 0,this._avgBitrate=0,this._audioGroups=void 0,this._subtitleGroups=void 0,this._urlId=0,this.url=[e.url],this._attrs=[e.attrs],this.bitrate=e.bitrate,e.details&&(this.details=e.details),this.id=e.id||0,this.name=e.name,this.width=e.width||0,this.height=e.height||0,this.frameRate=e.attrs.optionalFloat("FRAME-RATE",0),this._avgBitrate=e.attrs.decimalInteger("AVERAGE-BANDWIDTH"),this.audioCodec=e.audioCodec,this.videoCodec=e.videoCodec,this.codecSet=[e.videoCodec,e.audioCodec].filter((e=>!!e)).map((e=>e.substring(0,4))).join(","),this.addGroupId("audio",e.attrs.AUDIO),this.addGroupId("text",e.attrs.SUBTITLES)}get maxBitrate(){return Math.max(this.realBitrate,this.bitrate)}get averageBitrate(){return this._avgBitrate||this.realBitrate||this.bitrate}get attrs(){return this._attrs[0]}get codecs(){return this.attrs.CODECS||""}get pathwayId(){return this.attrs["PATHWAY-ID"]||"."}get videoRange(){return this.attrs["VIDEO-RANGE"]||"SDR"}get score(){return this.attrs.optionalFloat("SCORE",0)}get uri(){return this.url[0]||""}hasAudioGroup(e){return Pg(this._audioGroups,e)}hasSubtitleGroup(e){return Pg(this._subtitleGroups,e)}get audioGroups(){return this._audioGroups}get subtitleGroups(){return this._subtitleGroups}addGroupId(e,t){if(t)if("audio"===e){let e=this._audioGroups;e||(e=this._audioGroups=[]),-1===e.indexOf(t)&&e.push(t)}else if("text"===e){let e=this._subtitleGroups;e||(e=this._subtitleGroups=[]),-1===e.indexOf(t)&&e.push(t)}}get urlId(){return 0}set urlId(e){}get audioGroupIds(){return this.audioGroups?[this.audioGroupId]:void 0}get textGroupIds(){return this.subtitleGroups?[this.textGroupId]:void 0}get audioGroupId(){var e;return null==(e=this.audioGroups)?void 0:e[0]}get textGroupId(){var e;return null==(e=this.subtitleGroups)?void 0:e[0]}addFallback(){}};function Pg(e,t){return!(!t||!e)&&-1!==e.indexOf(t)}function Og(e,t){let i=t.startPTS;if(Kf(i)){let r,s=0;t.sn>e.sn?(s=i-e.start,r=e):(s=e.start-i,r=t),r.duration!==s&&(r.duration=s)}else t.sn>e.sn?e.cc===t.cc&&e.minEndPTS?t.start=e.start+(e.minEndPTS-e.start):t.start=e.start+e.duration:t.start=Math.max(e.start-t.duration,0)}function Ug(e,t,i,r,s,n){r-i<=0&&(tp.warn("Fragment should have a positive duration",t),r=i+t.duration,n=s+t.duration);let a=i,o=r,l=t.startPTS,h=t.endPTS;if(Kf(l)){let e=Math.abs(l-i);Kf(t.deltaPTS)?t.deltaPTS=Math.max(e,t.deltaPTS):t.deltaPTS=e,a=Math.max(i,l),i=Math.min(i,l),s=Math.min(s,t.startDTS),o=Math.min(r,h),r=Math.max(r,h),n=Math.max(n,t.endDTS)}let d=i-t.start;0!==t.start&&(t.start=i),t.duration=r-t.start,t.startPTS=i,t.maxStartPTS=a,t.startDTS=s,t.endPTS=r,t.minEndPTS=o,t.endDTS=n;let u=t.sn;if(!e||u<e.startSN||u>e.endSN)return 0;let c,f=u-e.startSN,p=e.fragments;for(p[f]=t,c=f;c>0;c--)Og(p[c],p[c-1]);for(c=f;c<p.length-1;c++)Og(p[c],p[c+1]);return e.fragmentHint&&Og(p[p.length-1],e.fragmentHint),e.PTSKnown=e.alignedSliding=!0,d}function Ng(e,t){let i=null,r=e.fragments;for(let e=r.length-1;e>=0;e--){let t=r[e].initSegment;if(t){i=t;break}}e.fragmentHint&&delete e.fragmentHint.endPTS;let s,n=0;if(function(e,t,i){let r=t.skippedSegments,s=Math.max(e.startSN,t.startSN)-t.startSN,n=(e.fragmentHint?1:0)+(r?t.endSN:Math.min(e.endSN,t.endSN))-t.startSN,a=t.startSN-e.startSN,o=t.fragmentHint?t.fragments.concat(t.fragmentHint):t.fragments,l=e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments;for(let e=s;e<=n;e++){let s=l[a+e],n=o[e];r&&!n&&e<r&&(n=t.fragments[e]=s),s&&n&&i(s,n)}}(e,t,((e,r)=>{e.relurl&&(n=e.cc-r.cc),Kf(e.startPTS)&&Kf(e.endPTS)&&(r.start=r.startPTS=e.startPTS,r.startDTS=e.startDTS,r.maxStartPTS=e.maxStartPTS,r.endPTS=e.endPTS,r.endDTS=e.endDTS,r.minEndPTS=e.minEndPTS,r.duration=e.endPTS-e.startPTS,r.duration&&(s=r),t.PTSKnown=t.alignedSliding=!0),r.elementaryStreams=e.elementaryStreams,r.loader=e.loader,r.stats=e.stats,e.initSegment&&(r.initSegment=e.initSegment,i=e.initSegment)})),i&&(t.fragmentHint?t.fragments.concat(t.fragmentHint):t.fragments).forEach((e=>{var t;e&&(!e.initSegment||e.initSegment.relurl===(null==(t=i)?void 0:t.relurl))&&(e.initSegment=i)})),t.skippedSegments)if(t.deltaUpdateFailed=t.fragments.some((e=>!e)),t.deltaUpdateFailed){tp.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let e=t.skippedSegments;e--;)t.fragments.shift();t.startSN=t.fragments[0].sn,t.startCC=t.fragments[0].cc}else t.canSkipDateRanges&&(t.dateRanges=function(e,t,i){let r=Vf({},e);return i&&i.forEach((e=>{delete r[e]})),Object.keys(t).forEach((e=>{let i=new op(t[e].attr,r[e]);i.isValid?r[e]=i:tp.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${JSON.stringify(t[e].attr)}"`)})),r}(e.dateRanges,t.dateRanges,t.recentlyRemovedDateranges));let a=t.fragments;if(n){tp.warn("discontinuity sliding from playlist, take drift into account");for(let e=0;e<a.length;e++)a[e].cc+=n}t.skippedSegments&&(t.startCC=t.fragments[0].cc),function(e,t,i){if(e&&t){let r=0;for(let s=0,n=e.length;s<=n;s++){let n=e[s],a=t[s+r];n&&a&&n.index===a.index&&n.fragment.sn===a.fragment.sn?i(n,a):r--}}}(e.partList,t.partList,((e,t)=>{t.elementaryStreams=e.elementaryStreams,t.stats=e.stats})),s?Ug(t,s,s.startPTS,s.endPTS,s.startDTS,s.endDTS):$g(e,t),a.length&&(t.totalduration=t.edge-a[0].start),t.driftStartTime=e.driftStartTime,t.driftStart=e.driftStart;let o=t.advancedDateTime;if(t.advanced&&o){let e=t.edge;t.driftStart||(t.driftStartTime=o,t.driftStart=e),t.driftEndTime=o,t.driftEnd=e}else t.driftEndTime=e.driftEndTime,t.driftEnd=e.driftEnd,t.advancedDateTime=e.advancedDateTime}function $g(e,t){let i=t.startSN+t.skippedSegments-e.startSN,r=e.fragments;i<0||i>=r.length||Fg(t,r[i].start)}function Fg(e,t){if(t){let i=e.fragments;for(let r=e.skippedSegments;r<i.length;r++)i[r].start+=t;e.fragmentHint&&(e.fragmentHint.start+=t)}}function Bg(e,t,i){var r;return null!=e&&e.details?Hg(null==(r=e.details)?void 0:r.partList,t,i):null}function Hg(e,t,i){if(e)for(let r=e.length;r--;){let s=e[r];if(s.index===i&&s.fragment.sn===t)return s}return null}function Gg(e){e.forEach(((e,t)=>{let{details:i}=e;null!=i&&i.fragments&&i.fragments.forEach((e=>{e.level=t}))}))}function jg(e){switch(e.details){case Xf.FRAG_LOAD_TIMEOUT:case Xf.KEY_LOAD_TIMEOUT:case Xf.LEVEL_LOAD_TIMEOUT:case Xf.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function Vg(e,t){let i=jg(t);return e.default[(i?"timeout":"error")+"Retry"]}function Kg(e,t){let i="linear"===e.backoff?1:Math.pow(2,t);return Math.min(i*e.retryDelayMs,e.maxRetryDelayMs)}function Wg(e){return Hf(Hf({},e),{errorRetry:null,timeoutRetry:null})}function qg(e,t,i,r){if(!e)return!1;let s=r?.code,n=t<e.maxNumRetry&&(function(e){return 0===e&&!1===navigator.onLine||!!e&&(e<400||e>499)}(s)||!!i);return e.shouldRetry?e.shouldRetry(e,t,i,r,n):n}var Yg=function(e,t){let i=0,r=e.length-1,s=null,n=null;for(;i<=r;){s=(i+r)/2|0,n=e[s];let a=t(n);if(a>0)i=s+1;else{if(!(a<0))return n;r=s-1}}return null};function zg(e,t,i=0,r=0,s=.005){let n=null;if(e){n=t[e.sn-t[0].sn+1]||null;let r=e.endDTS-i;r>0&&r<15e-7&&(i+=15e-7)}else 0===i&&0===t[0].start&&(n=t[0]);if(n&&((!e||e.level===n.level)&&0===Xg(i,r,n)||function(e,t,i){if(t&&0===t.start&&t.level<e.level&&(t.endPTS||0)>0){let r=t.tagList.reduce(((e,t)=>("INF"===t[0]&&(e+=parseFloat(t[1])),e)),i);return e.start<=r}return!1}(n,e,Math.min(s,r))))return n;let a=Yg(t,Xg.bind(null,i,r));return!a||a===e&&n?n:a}function Xg(e=0,t=0,i){if(i.start<=e&&i.start+i.duration>e)return 0;let r=Math.min(t,i.duration+(i.deltaPTS?i.deltaPTS:0));return i.start+i.duration-r<=e?1:i.start-r>e&&i.start?-1:0}function Qg(e,t,i){let r=1e3*Math.min(t,i.duration+(i.deltaPTS?i.deltaPTS:0));return(i.endProgramDateTime||0)-r>e}var Zg=0,Jg=2,ev=3,tv=5,iv=0,rv=1,sv=2,nv=class{constructor(e,t){this.hls=void 0,this.timer=-1,this.requestScheduled=-1,this.canLoad=!1,this.log=void 0,this.warn=void 0,this.log=tp.log.bind(tp,`${t}:`),this.warn=tp.warn.bind(tp,`${t}:`),this.hls=e}destroy(){this.clearTimer(),this.hls=this.log=this.warn=null}clearTimer(){-1!==this.timer&&(self.clearTimeout(this.timer),this.timer=-1)}startLoad(){this.canLoad=!0,this.requestScheduled=-1,this.loadPlaylist()}stopLoad(){this.canLoad=!1,this.clearTimer()}switchParams(e,t,i){let r=t?.renditionReports;if(r){let s=-1;for(let i=0;i<r.length;i++){let n,a=r[i];try{n=new self.URL(a.URI,t.url).href}catch(e){tp.warn(`Could not construct new URL for Rendition Report: ${e}`),n=a.URI||""}if(n===e){s=i;break}n===e.substring(0,n.length)&&(s=i)}if(-1!==s){let e=r[s],n=parseInt(e["LAST-MSN"])||t?.lastPartSn,a=parseInt(e["LAST-PART"])||t?.lastPartIndex;if(this.hls.config.lowLatencyMode){let e=Math.min(t.age-t.partTarget,t.targetduration);a>=0&&e>t.partTarget&&(a+=1)}let o=i&&Dg(i);return new xg(n,a>=0?a:void 0,o)}}}loadPlaylist(e){-1===this.requestScheduled&&(this.requestScheduled=self.performance.now())}shouldLoadPlaylist(e){return this.canLoad&&!!e&&!!e.url&&(!e.details||e.details.live)}shouldReloadPlaylist(e){return-1===this.timer&&-1===this.requestScheduled&&this.shouldLoadPlaylist(e)}playlistLoaded(e,t,i){let{details:r,stats:s}=t,n=self.performance.now(),a=s.loading.first?Math.max(0,n-s.loading.first):0;if(r.advancedDateTime=Date.now()-a,r.live||null!=i&&i.live){if(r.reloaded(i),i&&this.log(`live playlist ${e} ${r.advanced?"REFRESHED "+r.lastPartSn+"-"+r.lastPartIndex:r.updated?"UPDATED":"MISSED"}`),i&&r.fragments.length>0&&Ng(i,r),!this.canLoad||!r.live)return;let a,o,l;if(r.canBlockReload&&r.endSN&&r.advanced){let e=this.hls.config.lowLatencyMode,s=r.lastPartSn,n=r.endSN,h=r.lastPartIndex,d=s===n;-1!==h?(o=d?n+1:s,l=d?e?0:h:h+1):o=n+1;let u=r.age,c=u+r.ageHeader,f=Math.min(c-r.partTarget,1.5*r.targetduration);if(f>0){if(i&&f>i.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${i.tuneInGoal} to: ${f} with playlist age: ${r.age}`),f=0;else{let e=Math.floor(f/r.targetduration);if(o+=e,void 0!==l){l+=Math.round(f%r.targetduration/r.partTarget)}this.log(`CDN Tune-in age: ${r.ageHeader}s last advanced ${u.toFixed(2)}s goal: ${f} skip sn ${e} to part ${l}`)}r.tuneInGoal=f}if(a=this.getDeliveryDirectives(r,t.deliveryDirectives,o,l),e||!d)return void this.loadPlaylist(a)}else(r.canBlockReload||r.canSkipUntil)&&(a=this.getDeliveryDirectives(r,t.deliveryDirectives,o,l));let h=this.hls.mainForwardBufferInfo,d=h?h.end-h.len:0,u=function(e,t=1/0){let i=1e3*e.targetduration;if(e.updated){let r=e.fragments;if(r.length&&4*i>t){let e=1e3*r[r.length-1].duration;e<i&&(i=e)}}else i/=2;return Math.round(i)}(r,1e3*(r.edge-d));r.updated&&n>this.requestScheduled+u&&(this.requestScheduled=s.loading.start),void 0!==o&&r.canBlockReload?this.requestScheduled=s.loading.first+u-(1e3*r.partTarget||1e3):-1===this.requestScheduled||this.requestScheduled+u<n?this.requestScheduled=n:this.requestScheduled-n<=0&&(this.requestScheduled+=u);let c=this.requestScheduled-n;c=Math.max(0,c),this.log(`reload live playlist ${e} in ${Math.round(c)} ms`),this.timer=self.setTimeout((()=>this.loadPlaylist(a)),c)}else this.clearTimer()}getDeliveryDirectives(e,t,i,r){let s=Dg(e);return null!=t&&t.skip&&e.deltaUpdateFailed&&(i=t.msn,r=t.part,s=Rg),new xg(i,r,s)}checkRetry(e){let t=e.details,i=jg(e),r=e.errorAction,{action:s,retryCount:n=0,retryConfig:a}=r||{},o=!!r&&!!a&&(s===tv||!r.resolved&&s===Jg);if(o){var l;if(this.requestScheduled=-1,n>=a.maxNumRetry)return!1;if(i&&null!=(l=e.context)&&l.deliveryDirectives)this.warn(`Retrying playlist loading ${n+1}/${a.maxNumRetry} after "${t}" without delivery-directives`),this.loadPlaylist();else{let e=Kg(a,n);this.timer=self.setTimeout((()=>this.loadPlaylist()),e),this.warn(`Retrying playlist loading ${n+1}/${a.maxNumRetry} after "${t}" in ${e}ms`)}e.levelRetry=!0,r.resolved=!0}return o}},av=class{constructor(e,t=0,i=0){this.halfLife=void 0,this.alpha_=void 0,this.estimate_=void 0,this.totalWeight_=void 0,this.halfLife=e,this.alpha_=e?Math.exp(Math.log(.5)/e):0,this.estimate_=t,this.totalWeight_=i}sample(e,t){let i=Math.pow(this.alpha_,e);this.estimate_=t*(1-i)+i*this.estimate_,this.totalWeight_+=e}getTotalWeight(){return this.totalWeight_}getEstimate(){if(this.alpha_){let e=1-Math.pow(this.alpha_,this.totalWeight_);if(e)return this.estimate_/e}return this.estimate_}},ov=class{constructor(e,t,i,r=100){this.defaultEstimate_=void 0,this.minWeight_=void 0,this.minDelayMs_=void 0,this.slow_=void 0,this.fast_=void 0,this.defaultTTFB_=void 0,this.ttfb_=void 0,this.defaultEstimate_=i,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new av(e),this.fast_=new av(t),this.defaultTTFB_=r,this.ttfb_=new av(e)}update(e,t){let{slow_:i,fast_:r,ttfb_:s}=this;i.halfLife!==e&&(this.slow_=new av(e,i.getEstimate(),i.getTotalWeight())),r.halfLife!==t&&(this.fast_=new av(t,r.getEstimate(),r.getTotalWeight())),s.halfLife!==e&&(this.ttfb_=new av(e,s.getEstimate(),s.getTotalWeight()))}sample(e,t){let i=(e=Math.max(e,this.minDelayMs_))/1e3,r=8*t/i;this.fast_.sample(i,r),this.slow_.sample(i,r)}sampleTTFB(e){let t=e/1e3,i=Math.sqrt(2)*Math.exp(-Math.pow(t,2)/2);this.ttfb_.sample(i,Math.max(e,5))}canEstimate(){return this.fast_.getTotalWeight()>=this.minWeight_}getEstimate(){return this.canEstimate()?Math.min(this.fast_.getEstimate(),this.slow_.getEstimate()):this.defaultEstimate_}getEstimateTTFB(){return this.ttfb_.getTotalWeight()>=this.minWeight_?this.ttfb_.getEstimate():this.defaultTTFB_}destroy(){}},lv={supported:!0,configurations:[],decodingInfoResults:[{supported:!0,powerEfficient:!0,smooth:!0}]},hv={};function dv(e,t,i,r,s,n){let a=e.audioCodec?e.audioGroups:null,o=n?.audioCodec,l=n?.channels,h=l?parseInt(l):o?1/0:2,d=null;if(null!=a&&a.length)try{d=1===a.length&&a[0]?t.groups[a[0]].channels:a.reduce(((e,i)=>{if(i){let r=t.groups[i];if(!r)throw new Error(`Audio track group ${i} not found`);Object.keys(r.channels).forEach((t=>{e[t]=(e[t]||0)+r.channels[t]}))}return e}),{2:0})}catch{return!0}return void 0!==e.videoCodec&&(e.width>1920&&e.height>1088||e.height>1920&&e.width>1088||e.frameRate>Math.max(r,30)||"SDR"!==e.videoRange&&e.videoRange!==i||e.bitrate>Math.max(s,8e6))||!!d&&Kf(h)&&Object.keys(d).some((e=>parseInt(e)>h))}function uv(e,t,i){let r=e.videoCodec,s=e.audioCodec;if(!r||!s||!i)return Promise.resolve(lv);let n={width:e.width,height:e.height,bitrate:Math.ceil(Math.max(.9*e.bitrate,e.averageBitrate)),framerate:e.frameRate||30},a=e.videoRange;"SDR"!==a&&(n.transferFunction=a.toLowerCase());let o=r.split(",").map((e=>({type:"media-source",video:Hf(Hf({},n),{},{contentType:Om(e,"video")})})));return s&&e.audioGroups&&e.audioGroups.forEach((e=>{var i;e&&(null==(i=t.groups[e])||i.tracks.forEach((t=>{if(t.groupId===e){let e=t.channels||"",i=parseFloat(e);Kf(i)&&i>2&&o.push.apply(o,s.split(",").map((e=>({type:"media-source",audio:{contentType:Om(e,"audio"),channels:""+i}}))))}})))})),Promise.all(o.map((e=>{let t=function(e){let{audio:t,video:i}=e,r=i||t;if(r){let e=r.contentType.split('"')[1];if(i)return`r${i.height}x${i.width}f${Math.ceil(i.framerate)}${i.transferFunction||"sd"}_${e}_${Math.ceil(i.bitrate/1e5)}`;if(t)return`c${t.channels}${t.spatialRendering?"s":"n"}_${e}`}return""}(e);return hv[t]||(hv[t]=i.decodingInfo(e))}))).then((e=>({supported:!e.some((e=>!e.supported)),configurations:o,decodingInfoResults:e}))).catch((e=>({supported:!1,configurations:o,decodingInfoResults:[],error:e})))}function cv(e,t){let i=!1,r=[];return e&&(i="SDR"!==e,r=[e]),t&&(r=t.allowedVideoRanges||Lg.slice(0),i=void 0!==t.preferHDR?t.preferHDR:function(){if("function"==typeof matchMedia){let e=matchMedia("(dynamic-range: high)"),t=matchMedia("bad query");if(e.media!==t.media)return!0===e.matches}return!1}(),r=i?r.filter((e=>"SDR"!==e)):["SDR"]),{preferHDR:i,allowedVideoRanges:r}}function fv(e,t){tp.log(`[abr] start candidates with "${e}" ignored because ${t}`)}function pv(e,t,i){if("attrs"in e){let i=t.indexOf(e);if(-1!==i)return i}for(let r=0;r<t.length;r++){if(mv(e,t[r],i))return r}return-1}function mv(e,t,i){let{groupId:r,name:s,lang:n,assocLang:a,characteristics:o,default:l}=e,h=e.forced;return(void 0===r||t.groupId===r)&&(void 0===s||t.name===s)&&(void 0===n||t.lang===n)&&(void 0===n||t.assocLang===a)&&(void 0===l||t.default===l)&&(void 0===h||t.forced===h)&&(void 0===o||function(e,t=""){let i=e.split(","),r=t.split(",");return i.length===r.length&&!i.some((e=>-1===r.indexOf(e)))}(o,t.characteristics))&&(void 0===i||i(e,t))}function gv(e,t){let{audioCodec:i,channels:r}=e;return!(void 0!==i&&(t.audioCodec||"").substring(0,4)!==i.substring(0,4)||void 0!==r&&r!==(t.channels||"2"))}function vv(e,t,i){for(let r=t;r;r--)if(i(e[r]))return r;for(let r=t+1;r<e.length;r++)if(i(e[r]))return r;return-1}var Ev=class{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(e){return!this._tickInterval&&(this._tickCallCount=0,this._tickInterval=self.setInterval(this._boundTick,e),!0)}clearInterval(){return!!this._tickInterval&&(self.clearInterval(this._tickInterval),this._tickInterval=null,!0)}clearNextTick(){return!!this._tickTimer&&(self.clearTimeout(this._tickTimer),this._tickTimer=null,!0)}tick(){this._tickCallCount++,1===this._tickCallCount&&(this.doTick(),this._tickCallCount>1&&this.tickImmediate(),this._tickCallCount=0)}tickImmediate(){this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0)}doTick(){}},yv="NOT_LOADED",bv="APPENDING",Tv="PARTIAL",Sv="OK",Av=class{constructor(e){this.activePartLists=Object.create(null),this.endListFragments=Object.create(null),this.fragments=Object.create(null),this.timeRanges=Object.create(null),this.bufferPadding=.2,this.hls=void 0,this.hasGaps=!1,this.hls=e,this._registerListeners()}_registerListeners(){let{hls:e}=this;e.on(Yf.BUFFER_APPENDED,this.onBufferAppended,this),e.on(Yf.FRAG_BUFFERED,this.onFragBuffered,this),e.on(Yf.FRAG_LOADED,this.onFragLoaded,this)}_unregisterListeners(){let{hls:e}=this;e.off(Yf.BUFFER_APPENDED,this.onBufferAppended,this),e.off(Yf.FRAG_BUFFERED,this.onFragBuffered,this),e.off(Yf.FRAG_LOADED,this.onFragLoaded,this)}destroy(){this._unregisterListeners(),this.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null}getAppendedFrag(e,t){let i=this.activePartLists[t];if(i)for(let t=i.length;t--;){let r=i[t];if(!r)break;let s=r.end;if(r.start<=e&&null!==s&&e<=s)return r}return this.getBufferedFrag(e,t)}getBufferedFrag(e,t){let{fragments:i}=this,r=Object.keys(i);for(let s=r.length;s--;){let n=i[r[s]];if(n?.body.type===t&&n.buffered){let t=n.body;if(t.start<=e&&e<=t.end)return t}}return null}detectEvictedFragments(e,t,i,r){this.timeRanges&&(this.timeRanges[e]=t);let s=r?.fragment.sn||-1;Object.keys(this.fragments).forEach((r=>{let n=this.fragments[r];if(!n||s>=n.body.sn)return;if(!n.buffered&&!n.loaded)return void(n.body.type===i&&this.removeFragment(n.body));let a=n.range[e];a&&a.time.some((e=>{let i=!this.isTimeBuffered(e.startPTS,e.endPTS,t);return i&&this.removeFragment(n.body),i}))}))}detectPartialFragments(e){let t=this.timeRanges,{frag:i,part:r}=e;if(!t||"initSegment"===i.sn)return;let s=wv(i),n=this.fragments[s];if(!n||n.buffered&&i.gap)return;let a=!i.relurl;Object.keys(t).forEach((e=>{let s=i.elementaryStreams[e];if(!s)return;let o=t[e],l=a||!0===s.partial;n.range[e]=this.getBufferedTimes(i,r,l,o)})),n.loaded=null,Object.keys(n.range).length?(n.buffered=!0,(n.body.endList=i.endList||n.body.endList)&&(this.endListFragments[n.body.type]=n),_v(n)||this.removeParts(i.sn-1,i.type)):this.removeFragment(n.body)}removeParts(e,t){let i=this.activePartLists[t];i&&(this.activePartLists[t]=i.filter((t=>t.fragment.sn>=e)))}fragBuffered(e,t){let i=wv(e),r=this.fragments[i];!r&&t&&(r=this.fragments[i]={body:e,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},e.gap&&(this.hasGaps=!0)),r&&(r.loaded=null,r.buffered=!0)}getBufferedTimes(e,t,i,r){let s={time:[],partial:i},n=e.start,a=e.end,o=e.minEndPTS||a,l=e.maxStartPTS||n;for(let e=0;e<r.length;e++){let t=r.start(e)-this.bufferPadding,i=r.end(e)+this.bufferPadding;if(l>=t&&o<=i){s.time.push({startPTS:Math.max(n,r.start(e)),endPTS:Math.min(a,r.end(e))});break}if(n<i&&a>t){let t=Math.max(n,r.start(e)),i=Math.min(a,r.end(e));i>t&&(s.partial=!0,s.time.push({startPTS:t,endPTS:i}))}else if(a<=t)break}return s}getPartialFragment(e){let t,i,r,s=null,n=0,{bufferPadding:a,fragments:o}=this;return Object.keys(o).forEach((l=>{let h=o[l];h&&_v(h)&&(i=h.body.start-a,r=h.body.end+a,e>=i&&e<=r&&(t=Math.min(e-i,r-e),n<=t&&(s=h.body,n=t)))})),s}isEndListAppended(e){let t=this.endListFragments[e];return void 0!==t&&(t.buffered||_v(t))}getState(e){let t=wv(e),i=this.fragments[t];return i?i.buffered?_v(i)?Tv:Sv:bv:yv}isTimeBuffered(e,t,i){let r,s;for(let n=0;n<i.length;n++){if(r=i.start(n)-this.bufferPadding,s=i.end(n)+this.bufferPadding,e>=r&&t<=s)return!0;if(t<=r)return!1}return!1}onFragLoaded(e,t){let{frag:i,part:r}=t;if("initSegment"===i.sn||i.bitrateTest)return;let s=r?null:t,n=wv(i);this.fragments[n]={body:i,appendedPTS:null,loaded:s,buffered:!1,range:Object.create(null)}}onBufferAppended(e,t){let{frag:i,part:r,timeRanges:s}=t;if("initSegment"===i.sn)return;let n=i.type;if(r){let e=this.activePartLists[n];e||(this.activePartLists[n]=e=[]),e.push(r)}this.timeRanges=s,Object.keys(s).forEach((e=>{let t=s[e];this.detectEvictedFragments(e,t,n,r)}))}onFragBuffered(e,t){this.detectPartialFragments(t)}hasFragment(e){let t=wv(e);return!!this.fragments[t]}hasParts(e){var t;return!(null==(t=this.activePartLists[e])||!t.length)}removeFragmentsInRange(e,t,i,r,s){r&&!this.hasGaps||Object.keys(this.fragments).forEach((n=>{let a=this.fragments[n];if(!a)return;let o=a.body;o.type!==i||r&&!o.gap||o.start<t&&o.end>e&&(a.buffered||s)&&this.removeFragment(o)}))}removeFragment(e){let t=wv(e);e.stats.loaded=0,e.clearElementaryStreamInfo();let i=this.activePartLists[e.type];if(i){let t=e.sn;this.activePartLists[e.type]=i.filter((e=>e.fragment.sn!==t))}delete this.fragments[t],e.endList&&delete this.endListFragments[e.type]}removeAllFragments(){this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=!1}};function _v(e){var t,i,r;return e.buffered&&(e.body.gap||(null==(t=e.range.video)?void 0:t.partial)||(null==(i=e.range.audio)?void 0:i.partial)||(null==(r=e.range.audiovideo)?void 0:r.partial))}function wv(e){return`${e.type}_${e.level}_${e.sn}`}var kv={length:0,start:()=>0,end:()=>0},Lv=class e{static isBuffered(t,i){try{if(t){let r=e.getBuffered(t);for(let e=0;e<r.length;e++)if(i>=r.start(e)&&i<=r.end(e))return!0}}catch{}return!1}static bufferInfo(t,i,r){try{if(t){let s,n=e.getBuffered(t),a=[];for(s=0;s<n.length;s++)a.push({start:n.start(s),end:n.end(s)});return this.bufferedInfo(a,i,r)}}catch{}return{len:0,start:i,end:i,nextStart:void 0}}static bufferedInfo(e,t,i){t=Math.max(0,t),e.sort((function(e,t){return e.start-t.start||t.end-e.end}));let r=[];if(i)for(let t=0;t<e.length;t++){let s=r.length;if(s){let n=r[s-1].end;e[t].start-n<i?e[t].end>n&&(r[s-1].end=e[t].end):r.push(e[t])}else r.push(e[t])}else r=e;let s,n=0,a=t,o=t;for(let e=0;e<r.length;e++){let l=r[e].start,h=r[e].end;if(t+i>=l&&t<h)a=l,o=h,n=o-t;else if(t+i<l){s=l;break}}return{len:n,start:a||0,end:o||0,nextStart:s}}static getBuffered(e){try{return e.buffered}catch(e){return tp.log("failed to get media.buffered",e),kv}}},Rv=class{constructor(e,t,i,r=0,s=-1,n=!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={start:0,executeStart:0,executeEnd:0,end:0},this.buffering={audio:{start:0,executeStart:0,executeEnd:0,end:0},video:{start:0,executeStart:0,executeEnd:0,end:0},audiovideo:{start:0,executeStart:0,executeEnd:0,end:0}},this.level=e,this.sn=t,this.id=i,this.size=r,this.part=s,this.partial=n}};function Iv(e,t){for(let r=0,s=e.length;r<s;r++){var i;if((null==(i=e[r])?void 0:i.cc)===t)return e[r]}return null}function Cv(e,t){if(e){let i=e.start+t;e.start=e.startPTS=i,e.endPTS=i+e.duration}}function Dv(e,t){let i=t.fragments;for(let t=0,r=i.length;t<r;t++)Cv(i[t],e);t.fragmentHint&&Cv(t.fragmentHint,e),t.alignedSliding=!0}function xv(e,t,i){t&&(function(e,t,i){if(function(e,t,i){return!(!t||!(i.endCC>i.startCC||e&&e.cc<i.startCC))}(e,i,t)){let e=function(e,t){let i=e.fragments,r=t.fragments;if(!r.length||!i.length)return void tp.log("No fragments to align");let s=Iv(i,r[0].cc);if(s&&(!s||s.startPTS))return s;tp.log("No frag in previous level to align on")}(i,t);e&&Kf(e.start)&&(tp.log(`Adjusting PTS using last level due to CC increase within current level ${t.url}`),Dv(e.start,t))}}(e,i,t),!i.alignedSliding&&t&&Mv(i,t),!i.alignedSliding&&t&&!i.skippedSegments&&$g(t,i))}function Mv(e,t){if(!e.hasProgramDateTime||!t.hasProgramDateTime)return;let i=e.fragments,r=t.fragments;if(!i.length||!r.length)return;let s,n,a=Math.min(t.endCC,e.endCC);t.startCC<a&&e.startCC<a&&(s=Iv(r,a),n=Iv(i,a)),(!s||!n)&&(s=r[Math.floor(r.length/2)],n=Iv(i,s.cc)||i[Math.floor(i.length/2)]);let o=s.programDateTime,l=n.programDateTime;o&&l&&Dv((l-o)/1e3-(n.start-s.start),e)}var Pv=Math.pow(2,17),Ov=class{constructor(e){this.config=void 0,this.loader=null,this.partLoadTimeout=-1,this.config=e}destroy(){this.loader&&(this.loader.destroy(),this.loader=null)}abort(){this.loader&&this.loader.abort()}load(e,t){let i=e.url;if(!i)return Promise.reject(new $v({type:zf.NETWORK_ERROR,details:Xf.FRAG_LOAD_ERROR,fatal:!1,frag:e,error:new Error("Fragment does not have a "+(i?"part list":"url")),networkDetails:null}));this.abort();let r=this.config,s=r.fLoader,n=r.loader;return new Promise(((a,o)=>{if(this.loader&&this.loader.destroy(),e.gap){if(e.tagList.some((e=>"GAP"===e[0])))return void o(Nv(e));e.gap=!1}let l=this.loader=e.loader=s?new s(r):new n(r),h=Uv(e),d=Wg(r.fragLoadPolicy.default),u={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:"initSegment"===e.sn?1/0:Pv};e.stats=l.stats,l.load(h,u,{onSuccess:(t,i,r,s)=>{this.resetLoader(e,l);let n=t.data;r.resetIV&&e.decryptdata&&(e.decryptdata.iv=new Uint8Array(n.slice(0,16)),n=n.slice(16)),a({frag:e,part:null,payload:n,networkDetails:s})},onError:(t,r,s,n)=>{this.resetLoader(e,l),o(new $v({type:zf.NETWORK_ERROR,details:Xf.FRAG_LOAD_ERROR,fatal:!1,frag:e,response:Hf({url:i,data:void 0},t),error:new Error(`HTTP Error ${t.code} ${t.text}`),networkDetails:s,stats:n}))},onAbort:(t,i,r)=>{this.resetLoader(e,l),o(new $v({type:zf.NETWORK_ERROR,details:Xf.INTERNAL_ABORTED,fatal:!1,frag:e,error:new Error("Aborted"),networkDetails:r,stats:t}))},onTimeout:(t,i,r)=>{this.resetLoader(e,l),o(new $v({type:zf.NETWORK_ERROR,details:Xf.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,error:new Error(`Timeout after ${u.timeout}ms`),networkDetails:r,stats:t}))},onProgress:(i,r,s,n)=>{t&&t({frag:e,part:null,payload:s,networkDetails:n})}})}))}loadPart(e,t,i){this.abort();let r=this.config,s=r.fLoader,n=r.loader;return new Promise(((a,o)=>{if(this.loader&&this.loader.destroy(),e.gap||t.gap)return void o(Nv(e,t));let l=this.loader=e.loader=s?new s(r):new n(r),h=Uv(e,t),d=Wg(r.fragLoadPolicy.default),u={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:Pv};t.stats=l.stats,l.load(h,u,{onSuccess:(r,s,n,o)=>{this.resetLoader(e,l),this.updateStatsFromPart(e,t);let h={frag:e,part:t,payload:r.data,networkDetails:o};i(h),a(h)},onError:(i,r,s,n)=>{this.resetLoader(e,l),o(new $v({type:zf.NETWORK_ERROR,details:Xf.FRAG_LOAD_ERROR,fatal:!1,frag:e,part:t,response:Hf({url:h.url,data:void 0},i),error:new Error(`HTTP Error ${i.code} ${i.text}`),networkDetails:s,stats:n}))},onAbort:(i,r,s)=>{e.stats.aborted=t.stats.aborted,this.resetLoader(e,l),o(new $v({type:zf.NETWORK_ERROR,details:Xf.INTERNAL_ABORTED,fatal:!1,frag:e,part:t,error:new Error("Aborted"),networkDetails:s,stats:i}))},onTimeout:(i,r,s)=>{this.resetLoader(e,l),o(new $v({type:zf.NETWORK_ERROR,details:Xf.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,part:t,error:new Error(`Timeout after ${u.timeout}ms`),networkDetails:s,stats:i}))}})}))}updateStatsFromPart(e,t){let i=e.stats,r=t.stats,s=r.total;if(i.loaded+=r.loaded,s){let r=Math.round(e.duration/t.duration),n=Math.min(Math.round(i.loaded/s),r),a=(r-n)*Math.round(i.loaded/n);i.total=i.loaded+a}else i.total=Math.max(i.loaded,i.total);let n=i.loading,a=r.loading;n.start?n.first+=a.first-a.start:(n.start=a.start,n.first=a.first),n.end=a.end}resetLoader(e,t){e.loader=null,this.loader===t&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),t.destroy()}};function Uv(e,t=null){let i=t||e,r={frag:e,part:t,responseType:"arraybuffer",url:i.url,headers:{},rangeStart:0,rangeEnd:0},s=i.byteRangeStartOffset,n=i.byteRangeEndOffset;if(Kf(s)&&Kf(n)){var a;let t=s,i=n;if("initSegment"===e.sn&&"AES-128"===(null==(a=e.decryptdata)?void 0:a.method)){let e=n-s;e%16&&(i=n+(16-e%16)),0!==s&&(r.resetIV=!0,t=s-16)}r.rangeStart=t,r.rangeEnd=i}return r}function Nv(e,t){let i=new Error(`GAP ${e.gap?"tag":"attribute"} found`),r={type:zf.MEDIA_ERROR,details:Xf.FRAG_GAP,fatal:!1,frag:e,error:i,networkDetails:null};return t&&(r.part=t),(t||e).stats.aborted=!0,new $v(r)}var $v=class extends Error{constructor(e){super(e.error.message),this.data=void 0,this.data=e}},Fv=class{constructor(e,t){this.subtle=void 0,this.aesIV=void 0,this.subtle=e,this.aesIV=t}decrypt(e,t){return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},t,e)}},Bv=class{constructor(e,t){this.subtle=void 0,this.key=void 0,this.subtle=e,this.key=t}expandKey(){return this.subtle.importKey("raw",this.key,{name:"AES-CBC"},!1,["encrypt","decrypt"])}};var Hv=class{constructor(){this.rcon=[0,1,2,4,8,16,32,64,128,27,54],this.subMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.invSubMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.sBox=new Uint32Array(256),this.invSBox=new Uint32Array(256),this.key=new Uint32Array(0),this.ksRows=0,this.keySize=0,this.keySchedule=void 0,this.invKeySchedule=void 0,this.initTable()}uint8ArrayToUint32Array_(e){let t=new DataView(e),i=new Uint32Array(4);for(let e=0;e<4;e++)i[e]=t.getUint32(4*e);return i}initTable(){let e=this.sBox,t=this.invSBox,i=this.subMix,r=i[0],s=i[1],n=i[2],a=i[3],o=this.invSubMix,l=o[0],h=o[1],d=o[2],u=o[3],c=new Uint32Array(256),f=0,p=0,m=0;for(m=0;m<256;m++)c[m]=m<128?m<<1:m<<1^283;for(m=0;m<256;m++){let i=p^p<<1^p<<2^p<<3^p<<4;i=i>>>8^255&i^99,e[f]=i,t[i]=f;let o=c[f],m=c[o],g=c[m],v=257*c[i]^16843008*i;r[f]=v<<24|v>>>8,s[f]=v<<16|v>>>16,n[f]=v<<8|v>>>24,a[f]=v,v=16843009*g^65537*m^257*o^16843008*f,l[i]=v<<24|v>>>8,h[i]=v<<16|v>>>16,d[i]=v<<8|v>>>24,u[i]=v,f?(f=o^c[c[c[g^o]]],p^=c[c[p]]):f=p=1}}expandKey(e){let t=this.uint8ArrayToUint32Array_(e),i=!0,r=0;for(;r<t.length&&i;)i=t[r]===this.key[r],r++;if(i)return;this.key=t;let s=this.keySize=t.length;if(4!==s&&6!==s&&8!==s)throw new Error("Invalid aes key size="+s);let n,a,o,l,h=this.ksRows=4*(s+6+1),d=this.keySchedule=new Uint32Array(h),u=this.invKeySchedule=new Uint32Array(h),c=this.sBox,f=this.rcon,p=this.invSubMix,m=p[0],g=p[1],v=p[2],E=p[3];for(n=0;n<h;n++)n<s?o=d[n]=t[n]:(l=o,n%s==0?(l=l<<8|l>>>24,l=c[l>>>24]<<24|c[l>>>16&255]<<16|c[l>>>8&255]<<8|c[255&l],l^=f[n/s|0]<<24):s>6&&n%s==4&&(l=c[l>>>24]<<24|c[l>>>16&255]<<16|c[l>>>8&255]<<8|c[255&l]),d[n]=o=(d[n-s]^l)>>>0);for(a=0;a<h;a++)n=h-a,l=3&a?d[n]:d[n-4],u[a]=a<4||n<=4?l:m[c[l>>>24]]^g[c[l>>>16&255]]^v[c[l>>>8&255]]^E[c[255&l]],u[a]=u[a]>>>0}networkToHostOrderSwap(e){return e<<24|(65280&e)<<8|(16711680&e)>>8|e>>>24}decrypt(e,t,i){let r,s,n,a,o,l,h,d,u,c,f,p,m,g,v=this.keySize+6,E=this.invKeySchedule,y=this.invSBox,b=this.invSubMix,T=b[0],S=b[1],A=b[2],_=b[3],w=this.uint8ArrayToUint32Array_(i),k=w[0],L=w[1],R=w[2],I=w[3],C=new Int32Array(e),D=new Int32Array(C.length),x=this.networkToHostOrderSwap;for(;t<C.length;){for(u=x(C[t]),c=x(C[t+1]),f=x(C[t+2]),p=x(C[t+3]),o=u^E[0],l=p^E[1],h=f^E[2],d=c^E[3],m=4,g=1;g<v;g++)r=T[o>>>24]^S[l>>16&255]^A[h>>8&255]^_[255&d]^E[m],s=T[l>>>24]^S[h>>16&255]^A[d>>8&255]^_[255&o]^E[m+1],n=T[h>>>24]^S[d>>16&255]^A[o>>8&255]^_[255&l]^E[m+2],a=T[d>>>24]^S[o>>16&255]^A[l>>8&255]^_[255&h]^E[m+3],o=r,l=s,h=n,d=a,m+=4;r=y[o>>>24]<<24^y[l>>16&255]<<16^y[h>>8&255]<<8^y[255&d]^E[m],s=y[l>>>24]<<24^y[h>>16&255]<<16^y[d>>8&255]<<8^y[255&o]^E[m+1],n=y[h>>>24]<<24^y[d>>16&255]<<16^y[o>>8&255]<<8^y[255&l]^E[m+2],a=y[d>>>24]<<24^y[o>>16&255]<<16^y[l>>8&255]<<8^y[255&h]^E[m+3],D[t]=x(r^k),D[t+1]=x(a^L),D[t+2]=x(n^R),D[t+3]=x(s^I),k=u,L=c,R=f,I=p,t+=4}return D.buffer}},Gv=class{constructor(e,{removePKCS7Padding:t=!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=e.enableSoftwareAES,this.removePKCS7Padding=t,t)try{let e=self.crypto;e&&(this.subtle=e.subtle||e.webkitSubtle)}catch{}this.useSoftware=!this.subtle}destroy(){this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null}isSync(){return this.useSoftware}flush(){let{currentResult:e,remainderData:t}=this;if(!e||t)return this.reset(),null;let i=new Uint8Array(e);return this.reset(),this.removePKCS7Padding?function(e){let t=e.byteLength,i=t&&new DataView(e.buffer).getUint8(t-1);return i?Pp(e,0,t-i):e}(i):i}reset(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&(this.softwareDecrypter=null)}decrypt(e,t,i){return this.useSoftware?new Promise(((r,s)=>{this.softwareDecrypt(new Uint8Array(e),t,i);let n=this.flush();n?r(n.buffer):s(new Error("[softwareDecrypt] Failed to decrypt data"))})):this.webCryptoDecrypt(new Uint8Array(e),t,i)}softwareDecrypt(e,t,i){let{currentIV:r,currentResult:s,remainderData:n}=this;this.logOnce("JS AES decrypt"),n&&(e=gm(n,e),this.remainderData=null);let a=this.getValidChunk(e);if(!a.length)return null;r&&(i=r);let o=this.softwareDecrypter;o||(o=this.softwareDecrypter=new Hv),o.expandKey(t);let l=s;return this.currentResult=o.decrypt(a.buffer,0,i),this.currentIV=Pp(a,-16).buffer,l||null}webCryptoDecrypt(e,t,i){if(this.key!==t||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(e,t,i));this.key=t,this.fastAesKey=new Bv(this.subtle,t)}return this.fastAesKey.expandKey().then((t=>this.subtle?(this.logOnce("WebCrypto AES decrypt"),new Fv(this.subtle,new Uint8Array(i)).decrypt(e.buffer,t)):Promise.reject(new Error("web crypto not initialized")))).catch((r=>(tp.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${r.name}: ${r.message}`),this.onWebCryptoError(e,t,i))))}onWebCryptoError(e,t,i){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(e,t,i);let r=this.flush();if(r)return r.buffer;throw new Error("WebCrypto and softwareDecrypt: failed to decrypt data")}getValidChunk(e){let t=e,i=e.length-e.length%16;return i!==e.length&&(t=Pp(e,0,i),this.remainderData=Pp(e,i)),t}logOnce(e){this.logEnabled&&(tp.log(`[decrypter]: ${e}`),this.logEnabled=!1)}},jv=function(e){let t="",i=e.length;for(let r=0;r<i;r++)t+=`[${e.start(r).toFixed(3)}-${e.end(r).toFixed(3)}]`;return t},Vv="STOPPED",Kv="IDLE",Wv="KEY_LOADING",qv="FRAG_LOADING",Yv="FRAG_LOADING_WAITING_RETRY",zv="WAITING_TRACK",Xv="PARSING",Qv="PARSED",Zv="ENDED",Jv="ERROR",eE="WAITING_INIT_PTS",tE="WAITING_LEVEL",iE=class extends Ev{constructor(e,t,i,r,s){super(),this.hls=void 0,this.fragPrevious=null,this.fragCurrent=null,this.fragmentTracker=void 0,this.transmuxer=null,this._state=Vv,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=s,this.logPrefix=r,this.log=tp.log.bind(tp,`${r}:`),this.warn=tp.warn.bind(tp,`${r}:`),this.hls=e,this.fragmentLoader=new Ov(e.config),this.keyLoader=i,this.fragmentTracker=t,this.config=e.config,this.decrypter=new Gv(e.config),e.on(Yf.MANIFEST_LOADED,this.onManifestLoaded,this)}doTick(){this.onTickEnd()}onTickEnd(){}startLoad(e){}stopLoad(){this.fragmentLoader.abort(),this.keyLoader.abort(this.playlistType);let e=this.fragCurrent;null!=e&&e.loader&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.resetTransmuxer(),this.fragCurrent=null,this.fragPrevious=null,this.clearInterval(),this.clearNextTick(),this.state=Vv}_streamEnded(e,t){if(t.live||e.nextStart||!e.end||!this.media)return!1;let i=t.partList;if(null!=i&&i.length){let e=i[i.length-1];return Lv.isBuffered(this.media,e.start+e.duration/2)}let r=t.fragments[t.fragments.length-1].type;return this.fragmentTracker.isEndListAppended(r)}getLevelDetails(){var e;if(this.levels&&null!==this.levelLastLoaded)return null==(e=this.levelLastLoaded)?void 0:e.details}onMediaAttached(e,t){let i=this.media=this.mediaBuffer=t.media;this.onvseeking=this.onMediaSeeking.bind(this),this.onvended=this.onMediaEnded.bind(this),i.addEventListener("seeking",this.onvseeking),i.addEventListener("ended",this.onvended);let r=this.config;this.levels&&r.autoStartLoad&&this.state===Vv&&this.startLoad(r.startPosition)}onMediaDetaching(){let e=this.media;null!=e&&e.ended&&(this.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0),e&&this.onvseeking&&this.onvended&&(e.removeEventListener("seeking",this.onvseeking),e.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(){let{config:e,fragCurrent:t,media:i,mediaBuffer:r,state:s}=this,n=i?i.currentTime:0,a=Lv.bufferInfo(r||i,n,e.maxBufferHole);if(this.log(`media seeking to ${Kf(n)?n.toFixed(3):n}, state: ${s}`),this.state===Zv)this.resetLoadingState();else if(t){let i=e.maxFragLookUpTolerance,r=t.start-i,s=t.start+t.duration+i;if(!a.len||s<a.start||r>a.end){let e=n>s;(n<r||e)&&(e&&t.loader&&(this.log("seeking outside of buffer while fragment load in progress, cancel fragment load"),t.abortRequests(),this.resetLoadingState()),this.fragPrevious=null)}}i&&(this.fragmentTracker.removeFragmentsInRange(n,1/0,this.playlistType,!0),this.lastCurrentTime=n),!this.loadedmetadata&&!a.len&&(this.nextLoadPosition=this.startPosition=n),this.tickImmediate()}onMediaEnded(){this.startPosition=this.lastCurrentTime=0}onManifestLoaded(e,t){this.startTimeOffset=t.startTimeOffset,this.initPTS=[]}onHandlerDestroying(){this.hls.off(Yf.MANIFEST_LOADED,this.onManifestLoaded,this),this.stopLoad(),super.onHandlerDestroying(),this.hls=null}onHandlerDestroyed(){this.state=Vv,this.fragmentLoader&&this.fragmentLoader.destroy(),this.keyLoader&&this.keyLoader.destroy(),this.decrypter&&this.decrypter.destroy(),this.hls=this.log=this.warn=this.decrypter=this.keyLoader=this.fragmentLoader=this.fragmentTracker=null,super.onHandlerDestroyed()}loadFragment(e,t,i){this._loadFragForPlayback(e,t,i)}_loadFragForPlayback(e,t,i){this._doFragLoad(e,t,i,(t=>{if(this.fragContextChanged(e))return this.warn(`Fragment ${e.sn}${t.part?" p: "+t.part.index:""} of level ${e.level} was dropped during download.`),void this.fragmentTracker.removeFragment(e);e.stats.chunkCount++,this._handleFragmentLoadProgress(t)})).then((t=>{if(!t)return;let i=this.state;this.fragContextChanged(e)?(i===qv||!this.fragCurrent&&i===Xv)&&(this.fragmentTracker.removeFragment(e),this.state=Kv):("payload"in t&&(this.log(`Loaded fragment ${e.sn} of level ${e.level}`),this.hls.trigger(Yf.FRAG_LOADED,t)),this._handleFragmentLoadComplete(t))})).catch((t=>{this.state===Vv||this.state===Jv||(this.warn(`Frag error: ${t?.message||t}`),this.resetFragmentLoading(e))}))}clearTrackerIfNeeded(e){var t;let{fragmentTracker:i}=this;if(i.getState(e)===bv){let t=e.type,r=this.getFwdBufferInfo(this.mediaBuffer,t),s=Math.max(e.duration,r?r.len:this.config.maxBufferLength),n=this.backtrackFragment;(1==(n?e.sn-n.sn:0)||this.reduceMaxBufferLength(s,e.duration))&&i.removeFragment(e)}else 0===(null==(t=this.mediaBuffer)?void 0:t.buffered.length)?i.removeAllFragments():i.hasParts(e.type)&&(i.detectPartialFragments({frag:e,part:null,stats:e.stats,id:e.type}),i.getState(e)===Tv&&i.removeFragment(e))}checkLiveUpdate(e){if(e.updated&&!e.live){let t=e.fragments[e.fragments.length-1];this.fragmentTracker.detectPartialFragments({frag:t,part:null,stats:t.stats,id:t.type})}e.fragments[0]||(e.deltaUpdateFailed=!0)}flushMainBuffer(e,t,i=null){if(!(e-t))return;let r={startOffset:e,endOffset:t,type:i};this.hls.trigger(Yf.BUFFER_FLUSHING,r)}_loadInitSegment(e,t){this._doFragLoad(e,t).then((t=>{if(!t||this.fragContextChanged(e)||!this.levels)throw new Error("init load aborted");return t})).then((t=>{let{hls:i}=this,{payload:r}=t,s=e.decryptdata;if(r&&r.byteLength>0&&null!=s&&s.key&&s.iv&&"AES-128"===s.method){let n=self.performance.now();return this.decrypter.decrypt(new Uint8Array(r),s.key.buffer,s.iv.buffer).catch((t=>{throw i.trigger(Yf.ERROR,{type:zf.MEDIA_ERROR,details:Xf.FRAG_DECRYPT_ERROR,fatal:!1,error:t,reason:t.message,frag:e}),t})).then((r=>{let s=self.performance.now();return i.trigger(Yf.FRAG_DECRYPTED,{frag:e,payload:r,stats:{tstart:n,tdecrypt:s}}),t.payload=r,this.completeInitSegmentLoad(t)}))}return this.completeInitSegmentLoad(t)})).catch((t=>{this.state===Vv||this.state===Jv||(this.warn(t),this.resetFragmentLoading(e))}))}completeInitSegmentLoad(e){let{levels:t}=this;if(!t)throw new Error("init load aborted, missing levels");let i=e.frag.stats;this.state=Kv,e.frag.data=new Uint8Array(e.payload),i.parsing.start=i.buffering.start=self.performance.now(),i.parsing.end=i.buffering.end=self.performance.now(),this.tick()}fragContextChanged(e){let{fragCurrent:t}=this;return!e||!t||e.sn!==t.sn||e.level!==t.level}fragBufferedComplete(e,t){var i,r,s,n;let a=this.mediaBuffer?this.mediaBuffer:this.media;if(this.log(`Buffered ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.playlistType===ng?"level":"track"} ${e.level} (frag:[${(null!=(i=e.startPTS)?i:NaN).toFixed(3)}-${(null!=(r=e.endPTS)?r:NaN).toFixed(3)}] > buffer:${a?jv(Lv.getBuffered(a)):"(detached)"})`),"initSegment"!==e.sn){var o;if(e.type!==og){let t=e.elementaryStreams;if(!Object.keys(t).some((e=>!!t[e])))return void(this.state=Kv)}let t=null==(o=this.levels)?void 0:o[e.level];null!=t&&t.fragmentError&&(this.log(`Resetting level fragment error count of ${t.fragmentError} on frag buffered`),t.fragmentError=0)}this.state=Kv,a&&(!this.loadedmetadata&&e.type==ng&&a.buffered.length&&(null==(s=this.fragCurrent)?void 0:s.sn)===(null==(n=this.fragPrevious)?void 0:n.sn)&&(this.loadedmetadata=!0,this.seekToStartPos()),this.tick())}seekToStartPos(){}_handleFragmentLoadComplete(e){let{transmuxer:t}=this;if(!t)return;let{frag:i,part:r,partsLoaded:s}=e,n=!s||0===s.length||s.some((e=>!e)),a=new Rv(i.level,i.sn,i.stats.chunkCount+1,0,r?r.index:-1,!n);t.flush(a)}_handleFragmentLoadProgress(e){}_doFragLoad(e,t,i=null,r){var s;let n=t?.details;if(!this.levels||!n)throw new Error(`frag load aborted, missing level${n?"":" detail"}s`);let a=null;if(!e.encrypted||null!=(s=e.decryptdata)&&s.key?!e.encrypted&&n.encryptedFragments.length&&this.keyLoader.loadClear(e,n.encryptedFragments):(this.log(`Loading key for ${e.sn} of [${n.startSN}-${n.endSN}], ${"[stream-controller]"===this.logPrefix?"level":"track"} ${e.level}`),this.state=Wv,this.fragCurrent=e,a=this.keyLoader.load(e).then((e=>{if(!this.fragContextChanged(e.frag))return this.hls.trigger(Yf.KEY_LOADED,e),this.state===Wv&&(this.state=Kv),e})),this.hls.trigger(Yf.KEY_LOADING,{frag:e}),null===this.fragCurrent&&(a=Promise.reject(new Error("frag load aborted, context changed in KEY_LOADING")))),i=Math.max(e.start,i||0),this.config.lowLatencyMode&&"initSegment"!==e.sn){let s=n.partList;if(s&&r){i>e.end&&n.fragmentHint&&(e=n.fragmentHint);let o=this.getNextPart(s,e,i);if(o>-1){let l,h=s[o];return this.log(`Loading part sn: ${e.sn} p: ${h.index} cc: ${e.cc} of playlist [${n.startSN}-${n.endSN}] parts [0-${o}-${s.length-1}] ${"[stream-controller]"===this.logPrefix?"level":"track"}: ${e.level}, target: ${parseFloat(i.toFixed(3))}`),this.nextLoadPosition=h.start+h.duration,this.state=qv,l=a?a.then((i=>!i||this.fragContextChanged(i.frag)?null:this.doFragPartsLoad(e,h,t,r))).catch((e=>this.handleFragLoadError(e))):this.doFragPartsLoad(e,h,t,r).catch((e=>this.handleFragLoadError(e))),this.hls.trigger(Yf.FRAG_LOADING,{frag:e,part:h,targetBufferTime:i}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):l}if(!e.url||this.loadedEndOfParts(s,i))return Promise.resolve(null)}}this.log(`Loading fragment ${e.sn} cc: ${e.cc} ${n?"of ["+n.startSN+"-"+n.endSN+"] ":""}${"[stream-controller]"===this.logPrefix?"level":"track"}: ${e.level}, target: ${parseFloat(i.toFixed(3))}`),Kf(e.sn)&&!this.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),this.state=qv;let o,l=this.config.progressive;return o=l&&a?a.then((t=>!t||this.fragContextChanged(t?.frag)?null:this.fragmentLoader.load(e,r))).catch((e=>this.handleFragLoadError(e))):Promise.all([this.fragmentLoader.load(e,l?r:void 0),a]).then((([e])=>(!l&&e&&r&&r(e),e))).catch((e=>this.handleFragLoadError(e))),this.hls.trigger(Yf.FRAG_LOADING,{frag:e,targetBufferTime:i}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):o}doFragPartsLoad(e,t,i,r){return new Promise(((s,n)=>{var a;let o=[],l=null==(a=i.details)?void 0:a.partList,h=t=>{this.fragmentLoader.loadPart(e,t,r).then((r=>{o[t.index]=r;let n=r.part;this.hls.trigger(Yf.FRAG_LOADED,r);let a=Bg(i,e.sn,t.index+1)||Hg(l,e.sn,t.index+1);if(!a)return s({frag:e,part:n,partsLoaded:o});h(a)})).catch(n)};h(t)}))}handleFragLoadError(e){if("data"in e){let t=e.data;e.data&&t.details===Xf.INTERNAL_ABORTED?this.handleFragLoadAborted(t.frag,t.part):this.hls.trigger(Yf.ERROR,t)}else this.hls.trigger(Yf.ERROR,{type:zf.OTHER_ERROR,details:Xf.INTERNAL_EXCEPTION,err:e,error:e,fatal:!0});return null}_handleTransmuxerFlush(e){let t=this.getCurrentContext(e);if(!t||this.state!==Xv)return void(!this.fragCurrent&&this.state!==Vv&&this.state!==Jv&&(this.state=Kv));let{frag:i,part:r,level:s}=t,n=self.performance.now();i.stats.parsing.end=n,r&&(r.stats.parsing.end=n),this.updateLevelTiming(i,r,s,e.partial)}getCurrentContext(e){let{levels:t,fragCurrent:i}=this,{level:r,sn:s,part:n}=e;if(null==t||!t[r])return this.warn(`Levels object was unset while buffering fragment ${s} of level ${r}. The current chunk will not be buffered.`),null;let a=t[r],o=n>-1?Bg(a,s,n):null,l=o?o.fragment:function(e,t,i){if(null==e||!e.details)return null;let r=e.details,s=r.fragments[t-r.startSN];return s||(s=r.fragmentHint,s&&s.sn===t)?s:t<r.startSN&&i&&i.sn===t?i:null}(a,s,i);return l?(i&&i!==l&&(l.stats=i.stats),{frag:l,part:o,level:a}):null}bufferFragmentData(e,t,i,r,s){var n;if(!e||this.state!==Xv)return;let{data1:a,data2:o}=e,l=a;if(a&&o&&(l=gm(a,o)),null==(n=l)||!n.length)return;let h={type:e.type,frag:t,part:i,chunkMeta:r,parent:t.type,data:l};if(this.hls.trigger(Yf.BUFFER_APPENDING,h),e.dropped&&e.independent&&!i){if(s)return;this.flushBufferGap(t)}}flushBufferGap(e){let t=this.media;if(!t)return;if(!Lv.isBuffered(t,t.currentTime))return void this.flushMainBuffer(0,e.start);let i=t.currentTime,r=Lv.bufferInfo(t,i,0),s=e.duration,n=Math.min(2*this.config.maxFragLookUpTolerance,.25*s),a=Math.max(Math.min(e.start-n,r.end-n),i+n);e.start-a>n&&this.flushMainBuffer(a,e.start)}getFwdBufferInfo(e,t){let i=this.getLoadPosition();return Kf(i)?this.getFwdBufferInfoAtPos(e,i,t):null}getFwdBufferInfoAtPos(e,t,i){let{config:{maxBufferHole:r}}=this,s=Lv.bufferInfo(e,t,r);if(0===s.len&&void 0!==s.nextStart){let n=this.fragmentTracker.getBufferedFrag(t,i);if(n&&s.nextStart<n.end)return Lv.bufferInfo(e,t,Math.max(s.nextStart,r))}return s}getMaxBufferLength(e){let t,{config:i}=this;return t=e?Math.max(8*i.maxBufferSize/e,i.maxBufferLength):i.maxBufferLength,Math.min(t,i.maxMaxBufferLength)}reduceMaxBufferLength(e,t){let i=this.config,r=Math.max(Math.min(e-t,i.maxBufferLength),t),s=Math.max(e-3*t,i.maxMaxBufferLength/2,r);return s>=r&&(i.maxMaxBufferLength=s,this.warn(`Reduce max buffer length to ${s}s`),!0)}getAppendedFrag(e,t=ng){let i=this.fragmentTracker.getAppendedFrag(e,ng);return i&&"fragment"in i?i.fragment:i}getNextFragment(e,t){let i=t.fragments,r=i.length;if(!r)return null;let s,{config:n}=this,a=i[0].start;if(t.live){let o=n.initialLiveManifestSize;if(r<o)return this.warn(`Not enough fragments to start playback (have: ${r}, need: ${o})`),null;(!t.PTSKnown&&!this.startFragRequested&&-1===this.startPosition||e<a)&&(s=this.getInitialLiveFragment(t,i),this.startPosition=this.nextLoadPosition=s?this.hls.liveSyncPosition||s.start:e)}else e<=a&&(s=i[0]);if(!s){let i=n.lowLatencyMode?t.partEnd:t.fragmentEnd;s=this.getFragmentAtPosition(e,i,t)}return this.mapToInitFragWhenRequired(s)}isLoopLoading(e,t){let i=this.fragmentTracker.getState(e);return(i===Sv||i===Tv&&!!e.gap)&&this.nextLoadPosition>t}getNextFragmentLoopLoading(e,t,i,r,s){let n=e.gap,a=this.getNextFragment(this.nextLoadPosition,t);if(null===a)return a;if(e=a,n&&e&&!e.gap&&i.nextStart){let t=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,i.nextStart,r);if(null!==t&&i.len+t.len>=s)return this.log(`buffer full after gaps in "${r}" playlist starting at sn: ${e.sn}`),null}return e}mapToInitFragWhenRequired(e){return null==e||!e.initSegment||null!=e&&e.initSegment.data||this.bitrateTest?e:e.initSegment}getNextPart(e,t,i){let r=-1,s=!1,n=!0;for(let a=0,o=e.length;a<o;a++){let o=e[a];if(n=n&&!o.independent,r>-1&&i<o.start)break;let l=o.loaded;l?r=-1:(s||o.independent||n)&&o.fragment===t&&(r=a),s=l}return r}loadedEndOfParts(e,t){let i=e[e.length-1];return i&&t>i.start&&i.loaded}getInitialLiveFragment(e,t){let i=this.fragPrevious,r=null;if(i){if(e.hasProgramDateTime&&(this.log(`Live playlist, switching playlist, load frag with same PDT: ${i.programDateTime}`),r=function(e,t,i){if(null===t||!Array.isArray(e)||!e.length||!Kf(t))return null;if(t<(e[0].programDateTime||0))return null;if(t>=(e[e.length-1].endProgramDateTime||0))return null;i=i||0;for(let r=0;r<e.length;++r){let s=e[r];if(Qg(t,i,s))return s}return null}(t,i.endProgramDateTime,this.config.maxFragLookUpTolerance)),!r){let s=i.sn+1;if(s>=e.startSN&&s<=e.endSN){let n=t[s-e.startSN];i.cc===n.cc&&(r=n,this.log(`Live playlist, switching playlist, load frag with next SN: ${r.sn}`))}r||(r=function(e,t){return Yg(e,(e=>e.cc<t?1:e.cc>t?-1:0))}(t,i.cc),r&&this.log(`Live playlist, switching playlist, load frag with same CC: ${r.sn}`))}}else{let t=this.hls.liveSyncPosition;null!==t&&(r=this.getFragmentAtPosition(t,this.bitrateTest?e.fragmentEnd:e.edge,e))}return r}getFragmentAtPosition(e,t,i){let r,{config:s}=this,{fragPrevious:n}=this,{fragments:a,endSN:o}=i,{fragmentHint:l}=i,{maxFragLookUpTolerance:h}=s,d=i.partList,u=!!(s.lowLatencyMode&&null!=d&&d.length&&l);if(u&&l&&!this.bitrateTest&&(a=a.concat(l),o=l.sn),e<t){r=zg(n,a,e,e>t-h?0:h)}else r=a[a.length-1];if(r){let e=r.sn-i.startSN,t=this.fragmentTracker.getState(r);if((t===Sv||t===Tv&&r.gap)&&(n=r),n&&r.sn===n.sn&&(!u||d[0].fragment.sn>r.sn)&&n&&r.level===n.level){let t=a[e+1];r=r.sn<o&&this.fragmentTracker.getState(t)!==Sv?t:null}}return r}synchronizeToLiveEdge(e){let{config:t,media:i}=this;if(!i)return;let r=this.hls.liveSyncPosition,s=i.currentTime,n=e.fragments[0].start,a=e.edge,o=s>=n-t.maxFragLookUpTolerance&&s<=a;if(null!==r&&i.duration>r&&(s<r||!o)){let n=void 0!==t.liveMaxLatencyDuration?t.liveMaxLatencyDuration:t.liveMaxLatencyDurationCount*e.targetduration;(!o&&i.readyState<4||s<a-n)&&(this.loadedmetadata||(this.nextLoadPosition=r),i.readyState&&(this.warn(`Playback: ${s.toFixed(3)} is located too far from the end of live sliding playlist: ${a}, reset currentTime to : ${r.toFixed(3)}`),i.currentTime=r))}}alignPlaylists(e,t,i){let r=e.fragments.length;if(!r)return this.warn("No fragments in live playlist"),0;let s=e.fragments[0].start,n=!t,a=e.alignedSliding&&Kf(s);if(n||!a&&!s){let{fragPrevious:s}=this;xv(s,i,e);let n=e.fragments[0].start;return this.log(`Live playlist sliding: ${n.toFixed(2)} start-sn: ${t?t.startSN:"na"}->${e.startSN} prev-sn: ${s?s.sn:"na"} fragments: ${r}`),n}return s}waitForCdnTuneIn(e){return e.live&&e.canBlockReload&&e.partTarget&&e.tuneInGoal>Math.max(e.partHoldBack,3*e.partTarget)}setStartPosition(e,t){let i=this.startPosition;if(i<t&&(i=-1),-1===i||-1===this.lastCurrentTime){let r=null!==this.startTimeOffset,s=r?this.startTimeOffset:e.startTimeOffset;null!==s&&Kf(s)?(i=t+s,s<0&&(i+=e.totalduration),i=Math.min(Math.max(t,i),t+e.totalduration),this.log(`Start time offset ${s} found in ${r?"multivariant":"media"} playlist, adjust startPosition to ${i}`),this.startPosition=i):e.live?i=this.hls.liveSyncPosition||t:this.startPosition=i=0,this.lastCurrentTime=i}this.nextLoadPosition=i}getLoadPosition(){let{media:e}=this,t=0;return this.loadedmetadata&&e?t=e.currentTime:this.nextLoadPosition&&(t=this.nextLoadPosition),t}handleFragLoadAborted(e,t){this.transmuxer&&"initSegment"!==e.sn&&e.stats.aborted&&(this.warn(`Fragment ${e.sn}${t?" part "+t.index:""} of level ${e.level} was aborted`),this.resetFragmentLoading(e))}resetFragmentLoading(e){(!this.fragCurrent||!this.fragContextChanged(e)&&this.state!==Yv)&&(this.state=Kv)}onFragmentOrKeyLoadError(e,t){if(t.chunkMeta&&!t.frag){let e=this.getCurrentContext(t.chunkMeta);e&&(t.frag=e.frag)}let i=t.frag;if(!i||i.type!==e||!this.levels)return;var r;if(this.fragContextChanged(i))return void this.warn(`Frag load error must match current frag to retry ${i.url} > ${null==(r=this.fragCurrent)?void 0:r.url}`);let s=t.details===Xf.FRAG_GAP;s&&this.fragmentTracker.fragBuffered(i,!0);let n=t.errorAction,{action:a,retryCount:o=0,retryConfig:l}=n||{};if(n&&a===tv&&l){this.resetStartWhenNotLoaded(this.levelLastLoaded);let r=Kg(l,o);this.warn(`Fragment ${i.sn} of ${e} ${i.level} errored with ${t.details}, retrying loading ${o+1}/${l.maxNumRetry} in ${r}ms`),n.resolved=!0,this.retryDate=self.performance.now()+r,this.state=Yv}else if(l&&n){if(this.resetFragmentErrors(e),!(o<l.maxNumRetry))return void tp.warn(`${t.details} reached or exceeded max retry (${o})`);!s&&a!==ev&&(n.resolved=!0)}else this.state=n?.action===Jg?tE:Jv;this.tickImmediate()}reduceLengthAndFlushBuffer(e){if(this.state===Xv||this.state===Qv){let t=e.frag,i=e.parent,r=this.getFwdBufferInfo(this.mediaBuffer,i),s=r&&r.len>.5;s&&this.reduceMaxBufferLength(r.len,t?.duration||10);let n=!s;return n&&this.warn(`Buffer full error while media.currentTime is not buffered, flush ${i} buffer`),t&&(this.fragmentTracker.removeFragment(t),this.nextLoadPosition=t.start),this.resetLoadingState(),n}return!1}resetFragmentErrors(e){e===ag&&(this.fragCurrent=null),this.loadedmetadata||(this.startFragRequested=!1),this.state!==Vv&&(this.state=Kv)}afterBufferFlushed(e,t,i){if(!e)return;let r=Lv.getBuffered(e);this.fragmentTracker.detectEvictedFragments(t,r,i),this.state===Zv&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state=Kv}resetStartWhenNotLoaded(e){if(!this.loadedmetadata){this.startFragRequested=!1;let t=e?e.details:null;null!=t&&t.live?(this.startPosition=-1,this.setStartPosition(t,0),this.resetLoadingState()):this.nextLoadPosition=this.startPosition}}resetWhenMissingContext(e){this.warn(`The loading context changed while buffering fragment ${e.sn} of level ${e.level}. This chunk will not be buffered.`),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(this.levelLastLoaded),this.resetLoadingState()}removeUnbufferedFrags(e=0){this.fragmentTracker.removeFragmentsInRange(e,1/0,this.playlistType,!1,!0)}updateLevelTiming(e,t,i,r){var s;let n=i.details;if(n){if(!Object.keys(e.elementaryStreams).reduce(((t,s)=>{let a=e.elementaryStreams[s];if(a){let o=a.endPTS-a.startPTS;if(o<=0)return this.warn(`Could not parse fragment ${e.sn} ${s} duration reliably (${o})`),t||!1;let l=r?0:Ug(n,e,a.startPTS,a.endPTS,a.startDTS,a.endDTS);return this.hls.trigger(Yf.LEVEL_PTS_UPDATED,{details:n,level:i,drift:l,type:s,frag:e,start:a.startPTS,end:a.endPTS}),!0}return t}),!1)&&null===(null==(s=this.transmuxer)?void 0:s.error)){let t=new Error(`Found no media in fragment ${e.sn} of level ${e.level} resetting transmuxer to fallback to playlist timing`);if(0===i.fragmentError&&(i.fragmentError++,e.gap=!0,this.fragmentTracker.removeFragment(e),this.fragmentTracker.fragBuffered(e,!0)),this.warn(t.message),this.hls.trigger(Yf.ERROR,{type:zf.MEDIA_ERROR,details:Xf.FRAG_PARSING_ERROR,fatal:!1,error:t,frag:e,reason:`Found no media in msn ${e.sn} of level "${i.url}"`}),!this.hls)return;this.resetTransmuxer()}this.state=Qv,this.hls.trigger(Yf.FRAG_PARSED,{frag:e,part:t})}else this.warn("level.details undefined")}resetTransmuxer(){this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null)}recoverWorkerError(e){"demuxerWorker"===e.event&&(this.fragmentTracker.removeAllFragments(),this.resetTransmuxer(),this.resetStartWhenNotLoaded(this.levelLastLoaded),this.resetLoadingState())}set state(e){let t=this._state;t!==e&&(this._state=e,this.log(`${t}->${e}`))}get state(){return this._state}},rE=class{constructor(){this.chunks=[],this.dataLength=0}push(e){this.chunks.push(e),this.dataLength+=e.length}flush(){let e,{chunks:t,dataLength:i}=this;return t.length?(e=1===t.length?t[0]:function(e,t){let i=new Uint8Array(t),r=0;for(let t=0;t<e.length;t++){let s=e[t];i.set(s,r),r+=s.length}return i}(t,i),this.reset(),e):new Uint8Array(0)}reset(){this.chunks.length=0,this.dataLength=0}};function sE(e="",t=9e4){return{type:e,id:-1,pid:-1,inputTimeScale:t,sequenceNumber:-1,samples:[],dropped:0}}var nE=class{constructor(){this._audioTrack=void 0,this._id3Track=void 0,this.frameIndex=0,this.cachedData=null,this.basePTS=null,this.initPTS=null,this.lastPTS=null}resetInitSegment(e,t,i,r){this._id3Track={type:"id3",id:3,pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0}}resetTimeStamp(e){this.initPTS=e,this.resetContiguity()}resetContiguity(){this.basePTS=null,this.lastPTS=null,this.frameIndex=0}canParse(e,t){return!1}appendFrame(e,t,i){}demux(e,t){this.cachedData&&(e=gm(this.cachedData,e),this.cachedData=null);let i,r=$p(e,0),s=r?r.length:0,n=this._audioTrack,a=this._id3Track,o=r?Hp(r):void 0,l=e.length;for((null===this.basePTS||0===this.frameIndex&&Kf(o))&&(this.basePTS=aE(o,t,this.initPTS),this.lastPTS=this.basePTS),null===this.lastPTS&&(this.lastPTS=this.basePTS),r&&r.length>0&&a.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:r,type:gg,duration:Number.POSITIVE_INFINITY});s<l;){if(this.canParse(e,s)){let t=this.appendFrame(n,e,s);t?(this.frameIndex++,this.lastPTS=t.sample.pts,s+=t.length,i=s):s=l}else Bp(e,s)?(r=$p(e,s),a.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:r,type:gg,duration:Number.POSITIVE_INFINITY}),s+=r.length,i=s):s++;if(s===l&&i!==l){let t=Pp(e,i);this.cachedData?this.cachedData=gm(this.cachedData,t):this.cachedData=t}}return{audioTrack:n,videoTrack:sE(),id3Track:a,textTrack:sE()}}demuxSampleAes(e,t,i){return Promise.reject(new Error(`[${this}] This demuxer does not support Sample-AES decryption`))}flush(e){let t=this.cachedData;return t&&(this.cachedData=null,this.demux(t,0)),{audioTrack:this._audioTrack,videoTrack:sE(),id3Track:this._id3Track,textTrack:sE()}}destroy(){}},aE=(e,t,i)=>{if(Kf(e))return 90*e;return 9e4*t+(i?9e4*i.baseTime/i.timescale:0)};function oE(e,t){return 255===e[t]&&240==(246&e[t+1])}function lE(e,t){return 1&e[t+1]?7:9}function hE(e,t){return(3&e[t+3])<<11|e[t+4]<<3|(224&e[t+5])>>>5}function dE(e,t){return t+1<e.length&&oE(e,t)}function uE(e,t){if(dE(e,t)){let i=lE(e,t);if(t+i>=e.length)return!1;let r=hE(e,t);if(r<=i)return!1;let s=t+r;return s===e.length||dE(e,s)}return!1}function cE(e,t,i,r,s){if(!e.samplerate){let n=function(e,t,i,r){let s,n,a,o,l=navigator.userAgent.toLowerCase(),h=r,d=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350];s=1+((192&t[i+2])>>>6);let u=(60&t[i+2])>>>2;if(!(u>d.length-1))return a=(1&t[i+2])<<2,a|=(192&t[i+3])>>>6,tp.log(`manifest codec:${r}, ADTS type:${s}, samplingIndex:${u}`),/firefox/i.test(l)?u>=6?(s=5,o=new Array(4),n=u-3):(s=2,o=new Array(2),n=u):-1!==l.indexOf("android")?(s=2,o=new Array(2),n=u):(s=5,o=new Array(4),r&&(-1!==r.indexOf("mp4a.40.29")||-1!==r.indexOf("mp4a.40.5"))||!r&&u>=6?n=u-3:((r&&-1!==r.indexOf("mp4a.40.2")&&(u>=6&&1===a||/vivaldi/i.test(l))||!r&&1===a)&&(s=2,o=new Array(2)),n=u)),o[0]=s<<3,o[0]|=(14&u)>>1,o[1]|=(1&u)<<7,o[1]|=a<<3,5===s&&(o[1]|=(14&n)>>1,o[2]=(1&n)<<7,o[2]|=8,o[3]=0),{config:o,samplerate:d[u],channelCount:a,codec:"mp4a.40."+s,manifestCodec:h};{let t=new Error(`invalid ADTS sampling index:${u}`);e.emit(Yf.ERROR,Yf.ERROR,{type:zf.MEDIA_ERROR,details:Xf.FRAG_PARSING_ERROR,fatal:!0,error:t,reason:t.message})}}(t,i,r,s);if(!n)return;e.config=n.config,e.samplerate=n.samplerate,e.channelCount=n.channelCount,e.codec=n.codec,e.manifestCodec=n.manifestCodec,tp.log(`parsed codec:${e.codec}, rate:${n.samplerate}, channels:${n.channelCount}`)}}function fE(e){return 9216e4/e}function pE(e,t,i,r,s){let n,a=r+s*fE(e.samplerate),o=function(e,t){let i=lE(e,t);if(t+i<=e.length){let r=hE(e,t)-i;if(r>0)return{headerLength:i,frameLength:r}}}(t,i);if(o){let{frameLength:r,headerLength:s}=o,l=s+r,h=Math.max(0,i+l-t.length);h?(n=new Uint8Array(l-s),n.set(t.subarray(i+s,t.length),0)):n=t.subarray(i+s,i+l);let d={unit:n,pts:a};return h||e.samples.push(d),{sample:d,length:l,missing:h}}let l=t.length-i;return n=new Uint8Array(l),n.set(t.subarray(i,t.length),0),{sample:{unit:n,pts:a},length:l,missing:-1}}var mE=null,gE=[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],vE=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],EE=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],yE=[0,1,1,4];function bE(e,t,i,r,s){if(i+24>t.length)return;let n=TE(t,i);if(n&&i+n.frameLength<=t.length){let a=r+s*(9e4*n.samplesPerFrame/n.sampleRate),o={unit:t.subarray(i,i+n.frameLength),pts:a,dts:a};return e.config=[],e.channelCount=n.channelCount,e.samplerate=n.sampleRate,e.samples.push(o),{sample:o,length:n.frameLength,missing:0}}}function TE(e,t){let i=e[t+1]>>3&3,r=e[t+1]>>1&3,s=e[t+2]>>4&15,n=e[t+2]>>2&3;if(1!==i&&0!==s&&15!==s&&3!==n){let a=e[t+2]>>1&1,o=e[t+3]>>6,l=1e3*gE[14*(3===i?3-r:3===r?3:4)+s-1],h=vE[3*(3===i?0:2===i?1:2)+n],d=3===o?1:2,u=EE[i][r],c=yE[r],f=8*u*c,p=Math.floor(u*l/h+a)*c;if(null===mE){let e=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);mE=e?parseInt(e[1]):0}return!!mE&&mE<=87&&2===r&&l>=224e3&&0===o&&(e[t+3]=128|e[t+3]),{sampleRate:h,channelCount:d,frameLength:p,samplesPerFrame:f}}}function SE(e,t){return!(255!==e[t]||224&~e[t+1]||!(6&e[t+1]))}function AE(e,t){return t+1<e.length&&SE(e,t)}function _E(e,t){if(t+1<e.length&&SE(e,t)){let i=TE(e,t),r=4;null!=i&&i.frameLength&&(r=i.frameLength);let s=t+r;return s===e.length||AE(e,s)}return!1}var wE=/\/emsg[-/]ID3/i,kE=(e,t)=>{let i=0,r=5;t+=r;let s=new Uint32Array(1),n=new Uint32Array(1),a=new Uint8Array(1);for(;r>0;){a[0]=e[t];let o=Math.min(r,8),l=8-o;n[0]=4278190080>>>24+l<<l,s[0]=(a[0]&n[0])>>l,i=i?i<<o|s[0]:s[0],t+=1,r-=o}return i};function LE(e,t,i,r,s){if(i+8>t.length||11!==t[i]||119!==t[i+1])return-1;let n=t[i+4]>>6;if(n>=3)return-1;let a=[48e3,44100,32e3][n],o=63&t[i+4],l=2*[64,69,96,64,70,96,80,87,120,80,88,120,96,104,144,96,105,144,112,121,168,112,122,168,128,139,192,128,140,192,160,174,240,160,175,240,192,208,288,192,209,288,224,243,336,224,244,336,256,278,384,256,279,384,320,348,480,320,349,480,384,417,576,384,418,576,448,487,672,448,488,672,512,557,768,512,558,768,640,696,960,640,697,960,768,835,1152,768,836,1152,896,975,1344,896,976,1344,1024,1114,1536,1024,1115,1536,1152,1253,1728,1152,1254,1728,1280,1393,1920,1280,1394,1920][3*o+n];if(i+l>t.length)return-1;let h=t[i+6]>>5,d=0;2===h?d+=2:(1&h&&1!==h&&(d+=2),4&h&&(d+=2));let u=(t[i+6]<<8|t[i+7])>>12-d&1,c=[2,1,2,3,3,4,4,5][h]+u,f=t[i+5]>>3,p=7&t[i+5],m=new Uint8Array([n<<6|f<<1|p>>2,(3&p)<<6|h<<3|u<<2|o>>4,o<<4&224]),g=r+s*(1536/a*9e4),v=t.subarray(i,i+l);return e.config=m,e.channelCount=c,e.samplerate=a,e.samples.push({unit:v,pts:g}),l}var RE=class{constructor(){this.VideoSample=null}createVideoSample(e,t,i,r){return{key:e,frame:!1,pts:t,dts:i,units:[],debug:r,length:0}}getLastNalUnit(e){var t;let i,r=this.VideoSample;if((!r||0===r.units.length)&&(r=e[e.length-1]),null!=(t=r)&&t.units){let e=r.units;i=e[e.length-1]}return i}pushAccessUnit(e,t){if(e.units.length&&e.frame){if(void 0===e.pts){let i=t.samples,r=i.length;if(!r)return void t.dropped++;{let t=i[r-1];e.pts=t.pts,e.dts=t.dts}}t.samples.push(e)}e.debug.length&&tp.log(e.pts+"/"+e.dts+":"+e.debug)}},IE=class{constructor(e){this.data=void 0,this.bytesAvailable=void 0,this.word=void 0,this.bitsAvailable=void 0,this.data=e,this.bytesAvailable=e.byteLength,this.word=0,this.bitsAvailable=0}loadWord(){let e=this.data,t=this.bytesAvailable,i=e.byteLength-t,r=new Uint8Array(4),s=Math.min(4,t);if(0===s)throw new Error("no bytes available");r.set(e.subarray(i,i+s)),this.word=new DataView(r.buffer).getUint32(0),this.bitsAvailable=8*s,this.bytesAvailable-=s}skipBits(e){let t;e=Math.min(e,8*this.bytesAvailable+this.bitsAvailable),this.bitsAvailable>e?(this.word<<=e,this.bitsAvailable-=e):(t=(e-=this.bitsAvailable)>>3,e-=t<<3,this.bytesAvailable-=t,this.loadWord(),this.word<<=e,this.bitsAvailable-=e)}readBits(e){let t=Math.min(this.bitsAvailable,e),i=this.word>>>32-t;if(e>32&&tp.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=t,this.bitsAvailable>0)this.word<<=t;else{if(!(this.bytesAvailable>0))throw new Error("no bits available");this.loadWord()}return t=e-t,t>0&&this.bitsAvailable?i<<t|this.readBits(t):i}skipLZ(){let e;for(e=0;e<this.bitsAvailable;++e)if(this.word&2147483648>>>e)return this.word<<=e,this.bitsAvailable-=e,e;return this.loadWord(),e+this.skipLZ()}skipUEG(){this.skipBits(1+this.skipLZ())}skipEG(){this.skipBits(1+this.skipLZ())}readUEG(){let e=this.skipLZ();return this.readBits(e+1)-1}readEG(){let e=this.readUEG();return 1&e?1+e>>>1:-1*(e>>>1)}readBoolean(){return 1===this.readBits(1)}readUByte(){return this.readBits(8)}readUShort(){return this.readBits(16)}readUInt(){return this.readBits(32)}skipScalingList(e){let t,i=8,r=8;for(let s=0;s<e;s++)0!==r&&(t=this.readEG(),r=(i+t+256)%256),i=0===r?i:r}readSPS(){let e,t,i,r=0,s=0,n=0,a=0,o=this.readUByte.bind(this),l=this.readBits.bind(this),h=this.readUEG.bind(this),d=this.readBoolean.bind(this),u=this.skipBits.bind(this),c=this.skipEG.bind(this),f=this.skipUEG.bind(this),p=this.skipScalingList.bind(this);o();let m=o();if(l(5),u(3),o(),f(),100===m||110===m||122===m||244===m||44===m||83===m||86===m||118===m||128===m){let e=h();if(3===e&&u(1),f(),f(),u(1),d())for(t=3!==e?8:12,i=0;i<t;i++)d()&&p(i<6?16:64)}f();let g=h();if(0===g)h();else if(1===g)for(u(1),c(),c(),e=h(),i=0;i<e;i++)c();f(),u(1);let v=h(),E=h(),y=l(1);0===y&&u(1),u(1),d()&&(r=h(),s=h(),n=h(),a=h());let b=[1,1];if(d()&&d())switch(o()){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=[o()<<8|o(),o()<<8|o()]}return{width:Math.ceil(16*(v+1)-2*r-2*s),height:(2-y)*(E+1)*16-(y?2:4)*(n+a),pixelRatio:b}}readSliceType(){return this.readUByte(),this.readUEG(),this.readUEG()}},CE=class extends RE{parseAVCPES(e,t,i,r,s){let n,a=this.parseAVCNALu(e,i.data),o=this.VideoSample,l=!1;i.data=null,o&&a.length&&!e.audFound&&(this.pushAccessUnit(o,e),o=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts,"")),a.forEach((r=>{var a;switch(r.type){case 1:{let t=!1;n=!0;let s=r.data;if(l&&s.length>4){let e=new IE(s).readSliceType();(2===e||4===e||7===e||9===e)&&(t=!0)}var h;if(t)null!=(h=o)&&h.frame&&!o.key&&(this.pushAccessUnit(o,e),o=this.VideoSample=null);o||(o=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts,"")),o.frame=!0,o.key=t;break}case 5:n=!0,null!=(a=o)&&a.frame&&!o.key&&(this.pushAccessUnit(o,e),o=this.VideoSample=null),o||(o=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts,"")),o.key=!0,o.frame=!0;break;case 6:n=!0,ym(r.data,1,i.pts,t.samples);break;case 7:{var d,u;n=!0,l=!0;let t=r.data,i=new IE(t).readSPS();if(!e.sps||e.width!==i.width||e.height!==i.height||(null==(d=e.pixelRatio)?void 0:d[0])!==i.pixelRatio[0]||(null==(u=e.pixelRatio)?void 0:u[1])!==i.pixelRatio[1]){e.width=i.width,e.height=i.height,e.pixelRatio=i.pixelRatio,e.sps=[t],e.duration=s;let r=t.subarray(1,4),n="avc1.";for(let e=0;e<3;e++){let t=r[e].toString(16);t.length<2&&(t="0"+t),n+=t}e.codec=n}break}case 8:n=!0,e.pps=[r.data];break;case 9:n=!0,e.audFound=!0,o&&this.pushAccessUnit(o,e),o=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts,"");break;case 12:n=!0;break;default:n=!1,o&&(o.debug+="unknown NAL "+r.type+" ")}o&&n&&o.units.push(r)})),r&&o&&(this.pushAccessUnit(o,e),this.VideoSample=null)}parseAVCNALu(e,t){let i,r,s,n=t.byteLength,a=e.naluState||0,o=a,l=[],h=0,d=-1,u=0;for(-1===a&&(d=0,u=31&t[0],a=0,h=1);h<n;)if(i=t[h++],a)if(1!==a)if(i)if(1===i){if(r=h-a-1,d>=0){let e={data:t.subarray(d,r),type:u};l.push(e)}else{let i=this.getLastNalUnit(e.samples);i&&(o&&h<=4-o&&i.state&&(i.data=i.data.subarray(0,i.data.byteLength-o)),r>0&&(i.data=gm(i.data,t.subarray(0,r)),i.state=0))}h<n?(s=31&t[h],d=h,u=s,a=0):a=-1}else a=0;else a=3;else a=i?0:2;else a=i?0:1;if(d>=0&&a>=0){let e={data:t.subarray(d,n),type:u,state:a};l.push(e)}if(0===l.length){let i=this.getLastNalUnit(e.samples);i&&(i.data=gm(i.data,t))}return e.naluState=a,l}},DE=class{constructor(e,t,i){this.keyData=void 0,this.decrypter=void 0,this.keyData=i,this.decrypter=new Gv(t,{removePKCS7Padding:!1})}decryptBuffer(e){return this.decrypter.decrypt(e,this.keyData.key.buffer,this.keyData.iv.buffer)}decryptAacSample(e,t,i){let r=e[t].unit;if(r.length<=16)return;let s=r.subarray(16,r.length-r.length%16),n=s.buffer.slice(s.byteOffset,s.byteOffset+s.length);this.decryptBuffer(n).then((s=>{let n=new Uint8Array(s);r.set(n,16),this.decrypter.isSync()||this.decryptAacSamples(e,t+1,i)}))}decryptAacSamples(e,t,i){for(;;t++){if(t>=e.length)return void i();if(!(e[t].unit.length<32||(this.decryptAacSample(e,t,i),this.decrypter.isSync())))return}}getAvcEncryptedData(e){let t=16*Math.floor((e.length-48)/160)+16,i=new Int8Array(t),r=0;for(let t=32;t<e.length-16;t+=160,r+=16)i.set(e.subarray(t,t+16),r);return i}getAvcDecryptedUnit(e,t){let i=new Uint8Array(t),r=0;for(let t=32;t<e.length-16;t+=160,r+=16)e.set(i.subarray(r,r+16),t);return e}decryptAvcSample(e,t,i,r,s){let n=bm(s.data),a=this.getAvcEncryptedData(n);this.decryptBuffer(a.buffer).then((a=>{s.data=this.getAvcDecryptedUnit(n,a),this.decrypter.isSync()||this.decryptAvcSamples(e,t,i+1,r)}))}decryptAvcSamples(e,t,i,r){if(e instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;t++,i=0){if(t>=e.length)return void r();let s=e[t].units;for(;!(i>=s.length);i++){let n=s[i];if(!(n.data.length<=48||1!==n.type&&5!==n.type||(this.decryptAvcSample(e,t,i,r,n),this.decrypter.isSync())))return}}}},xE=188;function ME(e,t){return((31&e[t+1])<<8)+e[t+2]}function PE(e,t){return(31&e[t+10])<<8|e[t+11]}function OE(e,t,i,r,s){let n={audioPid:-1,videoPid:-1,id3Pid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},a=t+3+((15&e[t+1])<<8|e[t+2])-4;for(t+=12+((15&e[t+10])<<8|e[t+11]);t<a;){let a=ME(e,t),o=(15&e[t+3])<<8|e[t+4];switch(e[t]){case 207:if(!r){NE("ADTS AAC");break}case 15:-1===n.audioPid&&(n.audioPid=a);break;case 21:-1===n.id3Pid&&(n.id3Pid=a);break;case 219:if(!r){NE("H.264");break}case 27:-1===n.videoPid&&(n.videoPid=a,n.segmentVideoCodec="avc");break;case 3:case 4:i.mpeg||i.mp3?-1===n.audioPid&&(n.audioPid=a,n.segmentAudioCodec="mp3"):tp.log("MPEG audio found, not supported in this browser");break;case 193:if(!r){NE("AC-3");break}case 129:i.ac3?-1===n.audioPid&&(n.audioPid=a,n.segmentAudioCodec="ac3"):tp.log("AC-3 audio found, not supported in this browser");break;case 6:if(-1===n.audioPid&&o>0){let r=t+5,s=o;for(;s>2;){if(106===e[r])!0!==i.ac3?tp.log("AC-3 audio found, not supported in this browser for now"):(n.audioPid=a,n.segmentAudioCodec="ac3");let t=e[r+1]+2;r+=t,s-=t}}break;case 194:case 135:return UE(s,new Error("Unsupported EC-3 in M2TS found")),n;case 36:return UE(s,new Error("Unsupported HEVC in M2TS found")),n}t+=o+5}return n}function UE(e,t,i){tp.warn(`parsing error: ${t.message}`),e.emit(Yf.ERROR,Yf.ERROR,{type:zf.MEDIA_ERROR,details:Xf.FRAG_PARSING_ERROR,fatal:!1,levelRetry:i,error:t,reason:t.message})}function NE(e){tp.log(`${e} with AES-128-CBC encryption found in unencrypted stream`)}function $E(e){let t,i,r,s,n,a=0,o=e.data;if(!e||0===e.size)return null;for(;o[0].length<19&&o.length>1;)o[0]=gm(o[0],o[1]),o.splice(1,1);if(t=o[0],(t[0]<<16)+(t[1]<<8)+t[2]===1){if(i=(t[4]<<8)+t[5],i&&i>e.size-6)return null;let l=t[7];192&l&&(s=536870912*(14&t[9])+4194304*(255&t[10])+16384*(254&t[11])+128*(255&t[12])+(254&t[13])/2,64&l?(n=536870912*(14&t[14])+4194304*(255&t[15])+16384*(254&t[16])+128*(255&t[17])+(254&t[18])/2,s-n>54e5&&(tp.warn(`${Math.round((s-n)/9e4)}s delta between PTS and DTS, align them`),s=n)):n=s),r=t[8];let h=r+9;if(e.size<=h)return null;e.size-=h;let d=new Uint8Array(e.size);for(let e=0,i=o.length;e<i;e++){t=o[e];let i=t.byteLength;if(h){if(h>i){h-=i;continue}t=t.subarray(h),i-=h,h=0}d.set(t,a),a+=i}return i&&(i-=r+3),{data:d,pts:s,dts:n,len:i}}return null}var FE=class{static getSilentFrame(e,t){if("mp4a.40.2"===e){if(1===t)return new Uint8Array([0,200,0,128,35,128]);if(2===t)return new Uint8Array([33,0,73,144,2,25,0,35,128]);if(3===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,142]);if(4===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,128,44,128,8,2,56]);if(5===t)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(6===t)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])}else{if(1===t)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(2===t)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(3===t)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])}}},BE=Math.pow(2,32)-1,HE=class e{static init(){let t;for(t in e.types={avc1:[],avcC:[],btrt:[],dinf:[],dref:[],esds:[],ftyp:[],hdlr:[],mdat:[],mdhd:[],mdia:[],mfhd:[],minf:[],moof:[],moov:[],mp4a:[],".mp3":[],dac3:[],"ac-3":[],mvex:[],mvhd:[],pasp:[],sdtp:[],stbl:[],stco:[],stsc:[],stsd:[],stsz:[],stts:[],tfdt:[],tfhd:[],traf:[],trak:[],trun:[],trex:[],tkhd:[],vmhd:[],smhd:[]},e.types)e.types.hasOwnProperty(t)&&(e.types[t]=[t.charCodeAt(0),t.charCodeAt(1),t.charCodeAt(2),t.charCodeAt(3)]);let i=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]),r=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]);e.HDLR_TYPES={video:i,audio:r};let 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]);e.STTS=e.STSC=e.STCO=n,e.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),e.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),e.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),e.STSD=new Uint8Array([0,0,0,0,0,0,0,1]);let a=new Uint8Array([105,115,111,109]),o=new Uint8Array([97,118,99,49]),l=new Uint8Array([0,0,0,1]);e.FTYP=e.box(e.types.ftyp,a,l,a,o),e.DINF=e.box(e.types.dinf,e.box(e.types.dref,s))}static box(e,...t){let i=8,r=t.length,s=r;for(;r--;)i+=t[r].byteLength;let n=new Uint8Array(i);for(n[0]=i>>24&255,n[1]=i>>16&255,n[2]=i>>8&255,n[3]=255&i,n.set(e,4),r=0,i=8;r<s;r++)n.set(t[r],i),i+=t[r].byteLength;return n}static hdlr(t){return e.box(e.types.hdlr,e.HDLR_TYPES[t])}static mdat(t){return e.box(e.types.mdat,t)}static mdhd(t,i){i*=t;let r=Math.floor(i/(BE+1)),s=Math.floor(i%(BE+1));return e.box(e.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,255&t,r>>24,r>>16&255,r>>8&255,255&r,s>>24,s>>16&255,s>>8&255,255&s,85,196,0,0]))}static mdia(t){return e.box(e.types.mdia,e.mdhd(t.timescale,t.duration),e.hdlr(t.type),e.minf(t))}static mfhd(t){return e.box(e.types.mfhd,new Uint8Array([0,0,0,0,t>>24,t>>16&255,t>>8&255,255&t]))}static minf(t){return"audio"===t.type?e.box(e.types.minf,e.box(e.types.smhd,e.SMHD),e.DINF,e.stbl(t)):e.box(e.types.minf,e.box(e.types.vmhd,e.VMHD),e.DINF,e.stbl(t))}static moof(t,i,r){return e.box(e.types.moof,e.mfhd(t),e.traf(r,i))}static moov(t){let i=t.length,r=[];for(;i--;)r[i]=e.trak(t[i]);return e.box.apply(null,[e.types.moov,e.mvhd(t[0].timescale,t[0].duration)].concat(r).concat(e.mvex(t)))}static mvex(t){let i=t.length,r=[];for(;i--;)r[i]=e.trex(t[i]);return e.box.apply(null,[e.types.mvex,...r])}static mvhd(t,i){i*=t;let r=Math.floor(i/(BE+1)),s=Math.floor(i%(BE+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,255&t,r>>24,r>>16&255,r>>8&255,255&r,s>>24,s>>16&255,s>>8&255,255&s,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 e.box(e.types.mvhd,n)}static sdtp(t){let i,r,s=t.samples||[],n=new Uint8Array(4+s.length);for(i=0;i<s.length;i++)r=s[i].flags,n[i+4]=r.dependsOn<<4|r.isDependedOn<<2|r.hasRedundancy;return e.box(e.types.sdtp,n)}static stbl(t){return e.box(e.types.stbl,e.stsd(t),e.box(e.types.stts,e.STTS),e.box(e.types.stsc,e.STSC),e.box(e.types.stsz,e.STSZ),e.box(e.types.stco,e.STCO))}static avc1(t){let i,r,s,n=[],a=[];for(i=0;i<t.sps.length;i++)r=t.sps[i],s=r.byteLength,n.push(s>>>8&255),n.push(255&s),n=n.concat(Array.prototype.slice.call(r));for(i=0;i<t.pps.length;i++)r=t.pps[i],s=r.byteLength,a.push(s>>>8&255),a.push(255&s),a=a.concat(Array.prototype.slice.call(r));let o=e.box(e.types.avcC,new Uint8Array([1,n[3],n[4],n[5],255,224|t.sps.length].concat(n).concat([t.pps.length]).concat(a))),l=t.width,h=t.height,d=t.pixelRatio[0],u=t.pixelRatio[1];return e.box(e.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,255&l,h>>8&255,255&h,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,e.box(e.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),e.box(e.types.pasp,new Uint8Array([d>>24,d>>16&255,d>>8&255,255&d,u>>24,u>>16&255,u>>8&255,255&u])))}static esds(e){let t=e.config.length;return new Uint8Array([0,0,0,0,3,23+t,0,1,0,4,15+t,64,21,0,0,0,0,0,0,0,0,0,0,0,5].concat([t]).concat(e.config).concat([6,1,2]))}static audioStsd(e){let t=e.samplerate;return new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,e.channelCount,0,16,0,0,0,0,t>>8&255,255&t,0,0])}static mp4a(t){return e.box(e.types.mp4a,e.audioStsd(t),e.box(e.types.esds,e.esds(t)))}static mp3(t){return e.box(e.types[".mp3"],e.audioStsd(t))}static ac3(t){return e.box(e.types["ac-3"],e.audioStsd(t),e.box(e.types.dac3,t.config))}static stsd(t){return"audio"===t.type?"mp3"===t.segmentCodec&&"mp3"===t.codec?e.box(e.types.stsd,e.STSD,e.mp3(t)):"ac3"===t.segmentCodec?e.box(e.types.stsd,e.STSD,e.ac3(t)):e.box(e.types.stsd,e.STSD,e.mp4a(t)):e.box(e.types.stsd,e.STSD,e.avc1(t))}static tkhd(t){let i=t.id,r=t.duration*t.timescale,s=t.width,n=t.height,a=Math.floor(r/(BE+1)),o=Math.floor(r%(BE+1));return e.box(e.types.tkhd,new Uint8Array([1,0,0,7,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,i>>24&255,i>>16&255,i>>8&255,255&i,0,0,0,0,a>>24,a>>16&255,a>>8&255,255&a,o>>24,o>>16&255,o>>8&255,255&o,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,255&s,0,0,n>>8&255,255&n,0,0]))}static traf(t,i){let r=e.sdtp(t),s=t.id,n=Math.floor(i/(BE+1)),a=Math.floor(i%(BE+1));return e.box(e.types.traf,e.box(e.types.tfhd,new Uint8Array([0,0,0,0,s>>24,s>>16&255,s>>8&255,255&s])),e.box(e.types.tfdt,new Uint8Array([1,0,0,0,n>>24,n>>16&255,n>>8&255,255&n,a>>24,a>>16&255,a>>8&255,255&a])),e.trun(t,r.length+16+20+8+16+8+8),r)}static trak(t){return t.duration=t.duration||4294967295,e.box(e.types.trak,e.tkhd(t),e.mdia(t))}static trex(t){let i=t.id;return e.box(e.types.trex,new Uint8Array([0,0,0,0,i>>24,i>>16&255,i>>8&255,255&i,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))}static trun(t,i){let r,s,n,a,o,l,h=t.samples||[],d=h.length,u=12+16*d,c=new Uint8Array(u);for(i+=8+u,c.set(["video"===t.type?1:0,0,15,1,d>>>24&255,d>>>16&255,d>>>8&255,255&d,i>>>24&255,i>>>16&255,i>>>8&255,255&i],0),r=0;r<d;r++)s=h[r],n=s.duration,a=s.size,o=s.flags,l=s.cts,c.set([n>>>24&255,n>>>16&255,n>>>8&255,255&n,a>>>24&255,a>>>16&255,a>>>8&255,255&a,o.isLeading<<2|o.dependsOn,o.isDependedOn<<6|o.hasRedundancy<<4|o.paddingValue<<1|o.isNonSync,61440&o.degradPrio,15&o.degradPrio,l>>>24&255,l>>>16&255,l>>>8&255,255&l],12+16*r);return e.box(e.types.trun,c)}static initSegment(t){e.types||e.init();let i=e.moov(t);return gm(e.FTYP,i)}};HE.types=void 0,HE.HDLR_TYPES=void 0,HE.STTS=void 0,HE.STSC=void 0,HE.STCO=void 0,HE.STSZ=void 0,HE.VMHD=void 0,HE.SMHD=void 0,HE.STSD=void 0,HE.FTYP=void 0,HE.DINF=void 0;function GE(e,t,i=1,r=!1){let s=e*t*i;return r?Math.round(s):s}function jE(e,t=!1){return GE(e,1e3,1/9e4,t)}var VE=null,KE=null,WE=class{constructor(e,t,i,r=""){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.videoTrackConfig=void 0,this.observer=e,this.config=t,this.typeSupported=i,this.ISGenerated=!1,null===VE){let e=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);VE=e?parseInt(e[1]):0}if(null===KE){let e=navigator.userAgent.match(/Safari\/(\d+)/i);KE=e?parseInt(e[1]):0}}destroy(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null}resetTimeStamp(e){tp.log("[mp4-remuxer]: initPTS & initDTS reset"),this._initPTS=this._initDTS=e}resetNextTimestamp(){tp.log("[mp4-remuxer]: reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1}resetInitSegment(){tp.log("[mp4-remuxer]: ISGenerated flag reset"),this.ISGenerated=!1,this.videoTrackConfig=void 0}getVideoStartPts(e){let t=!1,i=e.reduce(((e,i)=>{let r=i.pts-e;return r<-4294967296?(t=!0,qE(e,i.pts)):r>0?e:i.pts}),e[0].pts);return t&&tp.debug("PTS rollover detected"),i}remux(e,t,i,r,s,n,a,o){let l,h,d,u,c,f,p=s,m=s,g=e.pid>-1,v=t.pid>-1,E=t.samples.length,y=e.samples.length>0,b=a&&E>0||E>1;if((!g||y)&&(!v||b)||this.ISGenerated||a){if(this.ISGenerated){var T,S,A,_;let e=this.videoTrackConfig;e&&(t.width!==e.width||t.height!==e.height||(null==(T=t.pixelRatio)?void 0:T[0])!==(null==(S=e.pixelRatio)?void 0:S[0])||(null==(A=t.pixelRatio)?void 0:A[1])!==(null==(_=e.pixelRatio)?void 0:_[1]))&&this.resetInitSegment()}else d=this.generateIS(e,t,s,n);let i,r=this.isVideoContiguous,a=-1;if(b&&(a=function(e){for(let t=0;t<e.length;t++)if(e[t].key)return t;return-1}(t.samples),!r&&this.config.forceKeyFrameOnDiscontinuity))if(f=!0,a>0){tp.warn(`[mp4-remuxer]: Dropped ${a} out of ${E} video samples due to a missing keyframe`);let e=this.getVideoStartPts(t.samples);t.samples=t.samples.slice(a),t.dropped+=a,m+=(t.samples[0].pts-e)/t.inputTimeScale,i=m}else-1===a&&(tp.warn(`[mp4-remuxer]: No keyframe found out of ${E} video samples`),f=!1);if(this.ISGenerated){if(y&&b){let i=this.getVideoStartPts(t.samples),r=(qE(e.samples[0].pts,i)-i)/t.inputTimeScale;p+=Math.max(0,r),m+=Math.max(0,-r)}if(y){if(e.samplerate||(tp.warn("[mp4-remuxer]: regenerate InitSegment as audio detected"),d=this.generateIS(e,t,s,n)),h=this.remuxAudio(e,p,this.isAudioContiguous,n,v||b||o===ag?m:void 0),b){let i=h?h.endPTS-h.startPTS:0;t.inputTimeScale||(tp.warn("[mp4-remuxer]: regenerate InitSegment as video detected"),d=this.generateIS(e,t,s,n)),l=this.remuxVideo(t,m,r,i)}}else b&&(l=this.remuxVideo(t,m,r,0));l&&(l.firstKeyFrame=a,l.independent=-1!==a,l.firstKeyFramePTS=i)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(i.samples.length&&(c=YE(i,s,this._initPTS,this._initDTS)),r.samples.length&&(u=zE(r,s,this._initPTS))),{audio:h,video:l,initSegment:d,independent:f,text:u,id3:c}}generateIS(e,t,i,r){let s,n,a,o=e.samples,l=t.samples,h=this.typeSupported,d={},u=this._initPTS,c=!u||r,f="audio/mp4";if(c&&(s=n=1/0),e.config&&o.length){switch(e.timescale=e.samplerate,e.segmentCodec){case"mp3":h.mpeg?(f="audio/mpeg",e.codec=""):h.mp3&&(e.codec="mp3");break;case"ac3":e.codec="ac-3"}d.audio={id:"audio",container:f,codec:e.codec,initSegment:"mp3"===e.segmentCodec&&h.mpeg?new Uint8Array(0):HE.initSegment([e]),metadata:{channelCount:e.channelCount}},c&&(a=e.inputTimeScale,u&&a===u.timescale?c=!1:s=n=o[0].pts-Math.round(a*i))}if(t.sps&&t.pps&&l.length){if(t.timescale=t.inputTimeScale,d.video={id:"main",container:"video/mp4",codec:t.codec,initSegment:HE.initSegment([t]),metadata:{width:t.width,height:t.height}},c)if(a=t.inputTimeScale,u&&a===u.timescale)c=!1;else{let e=this.getVideoStartPts(l),t=Math.round(a*i);n=Math.min(n,qE(l[0].dts,e)-t),s=Math.min(s,e-t)}this.videoTrackConfig={width:t.width,height:t.height,pixelRatio:t.pixelRatio}}if(Object.keys(d).length)return this.ISGenerated=!0,c?(this._initPTS={baseTime:s,timescale:a},this._initDTS={baseTime:n,timescale:a}):s=a=void 0,{tracks:d,initPTS:s,timescale:a}}remuxVideo(e,t,i,r){let s,n,a=e.inputTimeScale,o=e.samples,l=[],h=o.length,d=this._initPTS,u=this.nextAvcDts,c=8,f=this.videoSampleDuration,p=Number.POSITIVE_INFINITY,m=Number.NEGATIVE_INFINITY,g=!1;if(!i||null===u){let e=t*a,r=o[0].pts-qE(o[0].dts,o[0].pts);VE&&null!==u&&Math.abs(e-r-u)<15e3?i=!0:u=e-r}let v=d.baseTime*a/d.timescale;for(let e=0;e<h;e++){let t=o[e];t.pts=qE(t.pts-v,u),t.dts=qE(t.dts-v,u),t.dts<o[e>0?e-1:e].dts&&(g=!0)}g&&o.sort((function(e,t){let i=e.dts-t.dts,r=e.pts-t.pts;return i||r})),s=o[0].dts,n=o[o.length-1].dts;let E=n-s,y=E?Math.round(E/(h-1)):f||e.inputTimeScale/30;if(i){let e=s-u,i=e>y,r=e<-1;if((i||r)&&(i?tp.warn(`AVC: ${jE(e,!0)} ms (${e}dts) hole between fragments detected at ${t.toFixed(3)}`):tp.warn(`AVC: ${jE(-e,!0)} ms (${e}dts) overlapping between fragments detected at ${t.toFixed(3)}`),!r||u>=o[0].pts||VE)){s=u;let t=o[0].pts-e;if(i)o[0].dts=s,o[0].pts=t;else for(let i=0;i<o.length&&!(o[i].dts>t);i++)o[i].dts-=e,o[i].pts-=e;tp.log(`Video: Initial PTS/DTS adjusted: ${jE(t,!0)}/${jE(s,!0)}, delta: ${jE(e,!0)} ms`)}}s=Math.max(0,s);let b=0,T=0,S=s;for(let e=0;e<h;e++){let t=o[e],i=t.units,r=i.length,s=0;for(let e=0;e<r;e++)s+=i[e].data.length;T+=s,b+=r,t.length=s,t.dts<S?(t.dts=S,S+=y/4|0||1):S=t.dts,p=Math.min(t.pts,p),m=Math.max(t.pts,m)}n=o[h-1].dts;let A,_=T+4*b+8;try{A=new Uint8Array(_)}catch(e){return void this.observer.emit(Yf.ERROR,Yf.ERROR,{type:zf.MUX_ERROR,details:Xf.REMUX_ALLOC_ERROR,fatal:!1,error:e,bytes:_,reason:`fail allocating video mdat ${_}`})}let w=new DataView(A.buffer);w.setUint32(0,_),A.set(HE.types.mdat,4);let k=!1,L=Number.POSITIVE_INFINITY,R=Number.POSITIVE_INFINITY,I=Number.NEGATIVE_INFINITY,C=Number.NEGATIVE_INFINITY;for(let e=0;e<h;e++){let t,i=o[e],s=i.units,n=0;for(let e=0,t=s.length;e<t;e++){let t=s[e],i=t.data,r=t.data.byteLength;w.setUint32(c,r),c+=4,A.set(i,c),c+=r,n+=4+r}if(e<h-1)f=o[e+1].dts-i.dts,t=o[e+1].pts-i.pts;else{let s=this.config,n=e>0?i.dts-o[e-1].dts:y;if(t=e>0?i.pts-o[e-1].pts:y,s.stretchShortVideoTrack&&null!==this.nextAudioPts){let e=Math.floor(s.maxBufferHole*a),t=(r?p+r*a:this.nextAudioPts)-i.pts;t>e?(f=t-n,f<0?f=n:k=!0,tp.log(`[mp4-remuxer]: It is approximately ${t/90} ms to the next segment; using duration ${f/90} ms for the last video frame.`)):f=n}else f=n}let d=Math.round(i.pts-i.dts);L=Math.min(L,f),I=Math.max(I,f),R=Math.min(R,t),C=Math.max(C,t),l.push(new QE(i.key,f,n,d))}if(l.length)if(VE){if(VE<70){let e=l[0].flags;e.dependsOn=2,e.isNonSync=0}}else if(KE&&C-R<I-L&&y/I<.025&&0===l[0].cts){tp.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");let e=s;for(let t=0,i=l.length;t<i;t++){let r=e+l[t].duration,s=e+l[t].cts;if(t<i-1){let e=r+l[t+1].cts;l[t].duration=e-s}else l[t].duration=t?l[t-1].duration:y;l[t].cts=0,e=r}}f=k||!f?y:f,this.nextAvcDts=u=n+f,this.videoSampleDuration=f,this.isVideoContiguous=!0;let D={data1:HE.moof(e.sequenceNumber++,s,Vf({},e,{samples:l})),data2:A,startPTS:p/a,endPTS:(m+f)/a,startDTS:s/a,endDTS:u/a,type:"video",hasAudio:!1,hasVideo:!0,nb:l.length,dropped:e.dropped};return e.samples=[],e.dropped=0,D}getSamplesPerFrame(e){switch(e.segmentCodec){case"mp3":return 1152;case"ac3":return 1536;default:return 1024}}remuxAudio(e,t,i,r,s){let n=e.inputTimeScale,a=n/(e.samplerate?e.samplerate:n),o=this.getSamplesPerFrame(e),l=o*a,h=this._initPTS,d="mp3"===e.segmentCodec&&this.typeSupported.mpeg,u=[],c=void 0!==s,f=e.samples,p=d?0:8,m=this.nextAudioPts||-1,g=t*n,v=h.baseTime*n/h.timescale;if(this.isAudioContiguous=i=i||f.length&&m>0&&(r&&Math.abs(g-m)<9e3||Math.abs(qE(f[0].pts-v,g)-m)<20*l),f.forEach((function(e){e.pts=qE(e.pts-v,g)})),!i||m<0){if(f=f.filter((e=>e.pts>=0)),!f.length)return;m=0===s?0:r&&!c?Math.max(0,g):f[0].pts}if("aac"===e.segmentCodec){let t=this.config.maxAudioFramesDrift;for(let i=0,r=m;i<f.length;i++){let s=f[i],a=s.pts,o=a-r,h=Math.abs(1e3*o/n);if(o<=-t*l&&c)0===i&&(tp.warn(`Audio frame @ ${(a/n).toFixed(3)}s overlaps nextAudioPts by ${Math.round(1e3*o/n)} ms.`),this.nextAudioPts=m=r=a);else if(o>=t*l&&h<1e4&&c){let t=Math.round(o/l);r=a-t*l,r<0&&(t--,r+=l),0===i&&(this.nextAudioPts=m=r),tp.warn(`[mp4-remuxer]: Injecting ${t} audio frame @ ${(r/n).toFixed(3)}s due to ${Math.round(1e3*o/n)} ms gap.`);for(let n=0;n<t;n++){let t=Math.max(r,0),n=FE.getSilentFrame(e.manifestCodec||e.codec,e.channelCount);n||(tp.log("[mp4-remuxer]: Unable to get silent frame for given audio codec; duplicating last frame instead."),n=s.unit.subarray()),f.splice(i,0,{unit:n,pts:t}),r+=l,i++}}s.pts=r,r+=l}}let E,y=null,b=null,T=0,S=f.length;for(;S--;)T+=f[S].unit.byteLength;for(let t=0,r=f.length;t<r;t++){let r=f[t],s=r.unit,n=r.pts;if(null!==b){u[t-1].duration=Math.round((n-b)/a)}else{if(i&&"aac"===e.segmentCodec&&(n=m),y=n,!(T>0))return;T+=p;try{E=new Uint8Array(T)}catch(e){return void this.observer.emit(Yf.ERROR,Yf.ERROR,{type:zf.MUX_ERROR,details:Xf.REMUX_ALLOC_ERROR,fatal:!1,error:e,bytes:T,reason:`fail allocating audio mdat ${T}`})}d||(new DataView(E.buffer).setUint32(0,T),E.set(HE.types.mdat,4))}E.set(s,p);let l=s.byteLength;p+=l,u.push(new QE(!0,o,l,0)),b=n}let A=u.length;if(!A)return;let _=u[u.length-1];this.nextAudioPts=m=b+a*_.duration;let w=d?new Uint8Array(0):HE.moof(e.sequenceNumber++,y/a,Vf({},e,{samples:u}));e.samples=[];let k=y/n,L=m/n,R={data1:w,data2:E,startPTS:k,endPTS:L,startDTS:k,endDTS:L,type:"audio",hasAudio:!0,hasVideo:!1,nb:A};return this.isAudioContiguous=!0,R}remuxEmptyAudio(e,t,i,r){let s=e.inputTimeScale,n=s/(e.samplerate?e.samplerate:s),a=this.nextAudioPts,o=this._initDTS,l=9e4*o.baseTime/o.timescale,h=(null!==a?a:r.startDTS*s)+l,d=r.endDTS*s+l,u=1024*n,c=Math.ceil((d-h)/u),f=FE.getSilentFrame(e.manifestCodec||e.codec,e.channelCount);if(tp.warn("[mp4-remuxer]: remux empty Audio"),!f)return void tp.trace("[mp4-remuxer]: Unable to remuxEmptyAudio since we were unable to get a silent frame for given audio codec");let p=[];for(let e=0;e<c;e++){let t=h+e*u;p.push({unit:f,pts:t,dts:t})}return e.samples=p,this.remuxAudio(e,t,i,!1)}};function qE(e,t){let i;if(null===t)return e;for(i=t<e?-8589934592:8589934592;Math.abs(e-t)>4294967296;)e+=i;return e}function YE(e,t,i,r){let s=e.samples.length;if(!s)return;let n=e.inputTimeScale;for(let a=0;a<s;a++){let s=e.samples[a];s.pts=qE(s.pts-i.baseTime*n/i.timescale,t*n)/n,s.dts=qE(s.dts-r.baseTime*n/r.timescale,t*n)/n}let a=e.samples;return e.samples=[],{samples:a}}function zE(e,t,i){let r=e.samples.length;if(!r)return;let s=e.inputTimeScale;for(let n=0;n<r;n++){let r=e.samples[n];r.pts=qE(r.pts-i.baseTime*s/i.timescale,t*s)/s}e.samples.sort(((e,t)=>e.pts-t.pts));let n=e.samples;return e.samples=[],{samples:n}}var XE,QE=class{constructor(e,t,i,r){this.size=void 0,this.duration=void 0,this.cts=void 0,this.flags=void 0,this.duration=t,this.size=i,this.cts=r,this.flags={isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:e?2:1,isNonSync:e?0:1}}};function ZE(e,t){let i=e?.codec;if(i&&i.length>4)return i;if(t===hp){if("ec-3"===i||"ac-3"===i||"alac"===i)return i;if("fLaC"===i||"Opus"===i)return Bm(i,!1);let e="mp4a.40.5";return tp.info(`Parsed audio codec "${i}" or audio object type not handled. Using "${e}"`),e}return tp.warn(`Unhandled video codec "${i}"`),"hvc1"===i||"hev1"===i?"hvc1.1.6.L120.90":"av01"===i?"av01.0.04M.08":"avc1.42e01e"}try{XE=self.performance.now.bind(self.performance)}catch{tp.debug("Unable to use Performance API on this environment"),XE=yp?.Date.now}var JE=[{demux:class{constructor(e,t){this.remainderData=null,this.timeOffset=0,this.config=void 0,this.videoTrack=void 0,this.audioTrack=void 0,this.id3Track=void 0,this.txtTrack=void 0,this.config=t}resetTimeStamp(){}resetInitSegment(e,t,i,r){let s=this.videoTrack=sE("video",1),n=this.audioTrack=sE("audio",1),a=this.txtTrack=sE("text",1);if(this.id3Track=sE("id3",1),this.timeOffset=0,null==e||!e.byteLength)return;let o=hm(e);if(o.video){let{id:e,timescale:t,codec:i}=o.video;s.id=e,s.timescale=a.timescale=t,s.codec=i}if(o.audio){let{id:e,timescale:t,codec:i}=o.audio;n.id=e,n.timescale=t,n.codec=i}a.id=em.text,s.sampleDuration=0,s.duration=n.duration=r}resetContiguity(){this.remainderData=null}static probe(e){return function(e){let t=e.byteLength;for(let i=0;i<t;){let r=rm(e,i);if(r>8&&109===e[i+4]&&111===e[i+5]&&111===e[i+6]&&102===e[i+7])return!0;i=r>1?i+r:t}return!1}(e)}demux(e,t){this.timeOffset=t;let i=e,r=this.videoTrack,s=this.txtTrack;if(this.config.progressive){this.remainderData&&(i=gm(this.remainderData,e));let t=function(e){let t={valid:null,remainder:null},i=om(e,["moof"]);if(i.length<2)return t.remainder=e,t;let r=i[i.length-1];return t.valid=Pp(e,0,r.byteOffset-8),t.remainder=Pp(e,r.byteOffset-8),t}(i);this.remainderData=t.remainder,r.samples=t.valid||new Uint8Array}else r.samples=i;let n=this.extractID3Track(r,t);return s.samples=vm(t,r),{videoTrack:r,audioTrack:this.audioTrack,id3Track:n,textTrack:this.txtTrack}}flush(){let e=this.timeOffset,t=this.videoTrack,i=this.txtTrack;t.samples=this.remainderData||new Uint8Array,this.remainderData=null;let r=this.extractID3Track(t,this.timeOffset);return i.samples=vm(e,t),{videoTrack:t,audioTrack:sE(),id3Track:r,textTrack:sE()}}extractID3Track(e,t){let i=this.id3Track;if(e.samples.length){let r=om(e.samples,["emsg"]);r&&r.forEach((e=>{let r=function(e){let t=e[0],i="",r="",s=0,n=0,a=0,o=0,l=0,h=0;if(0===t){for(;"\0"!==tm(e.subarray(h,h+1));)i+=tm(e.subarray(h,h+1)),h+=1;for(i+=tm(e.subarray(h,h+1)),h+=1;"\0"!==tm(e.subarray(h,h+1));)r+=tm(e.subarray(h,h+1)),h+=1;r+=tm(e.subarray(h,h+1)),h+=1,s=rm(e,12),n=rm(e,16),o=rm(e,20),l=rm(e,24),h=28}else if(1===t){h+=4,s=rm(e,h),h+=4;let t=rm(e,h);h+=4;let n=rm(e,h);for(h+=4,a=2**32*t+n,Wf(a)||(a=Number.MAX_SAFE_INTEGER,tp.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),o=rm(e,h),h+=4,l=rm(e,h),h+=4;"\0"!==tm(e.subarray(h,h+1));)i+=tm(e.subarray(h,h+1)),h+=1;for(i+=tm(e.subarray(h,h+1)),h+=1;"\0"!==tm(e.subarray(h,h+1));)r+=tm(e.subarray(h,h+1)),h+=1;r+=tm(e.subarray(h,h+1)),h+=1}return{schemeIdUri:i,value:r,timeScale:s,presentationTime:a,presentationTimeDelta:n,eventDuration:o,id:l,payload:e.subarray(h,e.byteLength)}}(e);if(wE.test(r.schemeIdUri)){let e=Kf(r.presentationTime)?r.presentationTime/r.timeScale:t+r.presentationTimeDelta/r.timeScale,s=4294967295===r.eventDuration?Number.POSITIVE_INFINITY:r.eventDuration/r.timeScale;s<=.001&&(s=Number.POSITIVE_INFINITY);let n=r.payload;i.samples.push({data:n,len:n.byteLength,dts:e,pts:e,type:Eg,duration:s})}}))}return i}demuxSampleAes(e,t,i){return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"))}destroy(){}},remux:class{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(e){this.initPTS=e,this.lastEndTime=null}resetNextTimestamp(){this.lastEndTime=null}resetInitSegment(e,t,i,r){this.audioCodec=t,this.videoCodec=i,this.generateInitSegment(function(e,t){if(!e||!t)return e;let i=t.keyId;return i&&t.isCommonEncryption&&om(e,["moov","trak"]).forEach((e=>{let t=om(e,["mdia","minf","stbl","stsd"])[0].subarray(8),r=om(t,["enca"]),s=r.length>0;s||(r=om(t,["encv"])),r.forEach((e=>{om(s?e.subarray(28):e.subarray(78),["sinf"]).forEach((e=>{let t=pm(e);if(t){let e=t.subarray(8,24);e.some((e=>0!==e))||(tp.log(`[eme] Patching keyId in 'enc${s?"a":"v"}>sinf>>tenc' box: ${Qp(e)} -> ${Qp(i)}`),t.set(i,8))}}))}))})),e}(e,r)),this.emitInitSegment=!0}generateInitSegment(e){let{audioCodec:t,videoCodec:i}=this;if(null==e||!e.byteLength)return this.initTracks=void 0,void(this.initData=void 0);let r=this.initData=hm(e);r.audio&&(t=ZE(r.audio,hp)),r.video&&(i=ZE(r.video,dp));let s={};r.audio&&r.video?s.audiovideo={container:"video/mp4",codec:t+","+i,initSegment:e,id:"main"}:r.audio?s.audio={container:"audio/mp4",codec:t,initSegment:e,id:"audio"}:r.video?s.video={container:"video/mp4",codec:i,initSegment:e,id:"main"}:tp.warn("[passthrough-remuxer.ts]: initSegment does not contain moov or trak boxes."),this.initTracks=s}remux(e,t,i,r,s,n){var a,o;let{initPTS:l,lastEndTime:h}=this,d={audio:void 0,video:void 0,text:r,id3:i,initSegment:void 0};Kf(h)||(h=this.lastEndTime=s||0);let u=t.samples;if(null==u||!u.length)return d;let c={initPTS:void 0,timescale:1},f=this.initData;if(null!=(a=f)&&a.length||(this.generateInitSegment(u),f=this.initData),null==(o=f)||!o.length)return tp.warn("[passthrough-remuxer.ts]: Failed to generate initSegment."),d;this.emitInitSegment&&(c.tracks=this.initTracks,this.emitInitSegment=!1);let p=function(e,t){let i=0,r=0,s=0,n=om(e,["moof","traf"]);for(let e=0;e<n.length;e++){let a=n[e],o=om(a,["tfhd"])[0],l=t[rm(o,4)];if(!l)continue;let h=l.default,d=rm(o,0)|h?.flags,u=h?.duration;8&d&&(u=rm(o,2&d?12:8));let c=l.timescale||9e4,f=om(a,["trun"]);for(let e=0;e<f.length;e++)i=mm(f[e]),!i&&u&&(i=u*rm(f[e],4)),l.type===dp?r+=i/c:l.type===hp&&(s+=i/c)}if(0===r&&0===s){let t=1/0,i=0,r=0,s=om(e,["sidx"]);for(let e=0;e<s.length;e++){let n=lm(s[e]);if(null!=n&&n.references){t=Math.min(t,n.earliestPresentationTime/n.timescale);let e=n.references.reduce(((e,t)=>e+t.info.duration||0),0);i=Math.max(i,e+n.earliestPresentationTime/n.timescale),r=i-t}}if(r&&Kf(r))return r}return r||s}(u,f),m=function(e,t){return om(t,["moof","traf"]).reduce(((t,i)=>{let r=om(i,["tfdt"])[0],s=r[0],n=om(i,["tfhd"]).reduce(((t,i)=>{let n=rm(i,4),a=e[n];if(a){let e=rm(r,4);if(1===s){if(e===Zp)return tp.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"),t;e*=Zp+1,e+=rm(r,8)}let i=e/(a.timescale||9e4);if(Kf(i)&&(null===t||i<t))return i}return t}),null);return null!==n&&Kf(n)&&(null===t||n<t)?n:t}),null)}(f,u),g=null===m?s:m;(function(e,t,i,r){if(null===e)return!0;let s=Math.max(r,1),n=t-e.baseTime/e.timescale;return Math.abs(n-i)>s}(l,g,s,p)||c.timescale!==l.timescale&&n)&&(c.initPTS=g-s,l&&1===l.timescale&&tp.warn("Adjusting initPTS by "+(c.initPTS-l.baseTime)),this.initPTS=l={baseTime:c.initPTS,timescale:1});let v=e?g-l.baseTime/l.timescale:h,E=v+p;(function(e,t,i){om(t,["moof","traf"]).forEach((t=>{om(t,["tfhd"]).forEach((r=>{let s=rm(r,4),n=e[s];if(!n)return;let a=n.timescale||9e4;om(t,["tfdt"]).forEach((e=>{let t=e[0],r=i*a;if(r){let i=rm(e,4);if(0===t)i-=r,i=Math.max(i,0),am(e,4,i);else{i*=Math.pow(2,32),i+=rm(e,8),i-=r,i=Math.max(i,0);let t=Math.floor(i/(Zp+1)),s=Math.floor(i%(Zp+1));am(e,4,t),am(e,8,s)}}}))}))}))})(f,u,l.baseTime/l.timescale),p>0?this.lastEndTime=E:(tp.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());let y=!!f.audio,b=!!f.video,T="";y&&(T+="audio"),b&&(T+="video");let S={data1:u,startPTS:v,startDTS:v,endPTS:E,endDTS:E,type:T,hasAudio:y,hasVideo:b,nb:1,dropped:0};return d.audio="audio"===S.type?S:void 0,d.video="audio"!==S.type?S:void 0,d.initSegment=c,d.id3=YE(i,s,l,l),r.samples.length&&(d.text=zE(r,s,l)),d}}},{demux:class e{constructor(e,t,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._videoTrack=void 0,this._audioTrack=void 0,this._id3Track=void 0,this._txtTrack=void 0,this.aacOverFlow=null,this.remainderData=null,this.videoParser=void 0,this.observer=e,this.config=t,this.typeSupported=i,this.videoParser=new CE}static probe(t){let i=e.syncOffset(t);return i>0&&tp.warn(`MPEG2-TS detected but first sync word found @ offset ${i}`),-1!==i}static syncOffset(e){let t=e.length,i=Math.min(940,t-xE)+1,r=0;for(;r<i;){let s=!1,n=-1,a=0;for(let o=r;o<t;o+=xE){if(71!==e[o]||t-o!==xE&&71!==e[o+xE]){if(a)return-1;break}if(a++,-1===n&&(n=o,0!==n&&(i=Math.min(n+18612,e.length-xE)+1)),s||(s=0===ME(e,o)),s&&a>1&&(0===n&&a>2||o+xE>i))return n}r++}return-1}static createTrack(e,t){return{container:"video"===e||"audio"===e?"video/mp2t":void 0,type:e,id:em[e],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:"audio"===e?t:void 0}}resetInitSegment(t,i,r,s){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=e.createTrack("video"),this._audioTrack=e.createTrack("audio",s),this._id3Track=e.createTrack("id3"),this._txtTrack=e.createTrack("text"),this._audioTrack.segmentCodec="aac",this.aacOverFlow=null,this.remainderData=null,this.audioCodec=i,this.videoCodec=r,this._duration=s}resetTimeStamp(){}resetContiguity(){let{_audioTrack:e,_videoTrack:t,_id3Track:i}=this;e&&(e.pesData=null),t&&(t.pesData=null),i&&(i.pesData=null),this.aacOverFlow=null,this.remainderData=null}demux(t,i,r=!1,s=!1){r||(this.sampleAes=null);let n,a=this._videoTrack,o=this._audioTrack,l=this._id3Track,h=this._txtTrack,d=a.pid,u=a.pesData,c=o.pid,f=l.pid,p=o.pesData,m=l.pesData,g=null,v=this.pmtParsed,E=this._pmtId,y=t.length;if(this.remainderData&&(y=(t=gm(this.remainderData,t)).length,this.remainderData=null),y<xE&&!s)return this.remainderData=t,{audioTrack:o,videoTrack:a,id3Track:l,textTrack:h};let b=Math.max(0,e.syncOffset(t));y-=(y-b)%xE,y<t.byteLength&&!s&&(this.remainderData=new Uint8Array(t.buffer,y,t.buffer.byteLength-y));let T=0;for(let e=b;e<y;e+=xE)if(71===t[e]){let i,s=!!(64&t[e+1]),y=ME(t,e);if((48&t[e+3])>>4>1){if(i=e+5+t[e+4],i===e+xE)continue}else i=e+4;switch(y){case d:s&&(u&&(n=$E(u))&&this.videoParser.parseAVCPES(a,h,n,!1,this._duration),u={data:[],size:0}),u&&(u.data.push(t.subarray(i,e+xE)),u.size+=e+xE-i);break;case c:if(s){if(p&&(n=$E(p)))switch(o.segmentCodec){case"aac":this.parseAACPES(o,n);break;case"mp3":this.parseMPEGPES(o,n);break;case"ac3":this.parseAC3PES(o,n)}p={data:[],size:0}}p&&(p.data.push(t.subarray(i,e+xE)),p.size+=e+xE-i);break;case f:s&&(m&&(n=$E(m))&&this.parseID3PES(l,n),m={data:[],size:0}),m&&(m.data.push(t.subarray(i,e+xE)),m.size+=e+xE-i);break;case 0:s&&(i+=t[i]+1),E=this._pmtId=PE(t,i);break;case E:{s&&(i+=t[i]+1);let n=OE(t,i,this.typeSupported,r,this.observer);d=n.videoPid,d>0&&(a.pid=d,a.segmentCodec=n.segmentVideoCodec),c=n.audioPid,c>0&&(o.pid=c,o.segmentCodec=n.segmentAudioCodec),f=n.id3Pid,f>0&&(l.pid=f),null!==g&&!v&&(tp.warn(`MPEG-TS PMT found at ${e} after unknown PID '${g}'. Backtracking to sync byte @${b} to parse all TS packets.`),g=null,e=b-188),v=this.pmtParsed=!0;break}case 17:case 8191:break;default:g=y}}else T++;T>0&&UE(this.observer,new Error(`Found ${T} TS packet/s that do not start with 0x47`)),a.pesData=u,o.pesData=p,l.pesData=m;let S={audioTrack:o,videoTrack:a,id3Track:l,textTrack:h};return s&&this.extractRemainingSamples(S),S}flush(){let e,{remainderData:t}=this;return this.remainderData=null,e=t?this.demux(t,-1,!1,!0):{videoTrack:this._videoTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(e),this.sampleAes?this.decrypt(e,this.sampleAes):e}extractRemainingSamples(e){let t,{audioTrack:i,videoTrack:r,id3Track:s,textTrack:n}=e,a=r.pesData,o=i.pesData,l=s.pesData;if(a&&(t=$E(a))?(this.videoParser.parseAVCPES(r,n,t,!0,this._duration),r.pesData=null):r.pesData=a,o&&(t=$E(o))){switch(i.segmentCodec){case"aac":this.parseAACPES(i,t);break;case"mp3":this.parseMPEGPES(i,t);break;case"ac3":this.parseAC3PES(i,t)}i.pesData=null}else null!=o&&o.size&&tp.log("last AAC PES packet truncated,might overlap between fragments"),i.pesData=o;l&&(t=$E(l))?(this.parseID3PES(s,t),s.pesData=null):s.pesData=l}demuxSampleAes(e,t,i){let r=this.demux(e,i,!0,!this.config.progressive),s=this.sampleAes=new DE(this.observer,this.config,t);return this.decrypt(r,s)}decrypt(e,t){return new Promise((i=>{let{audioTrack:r,videoTrack:s}=e;r.samples&&"aac"===r.segmentCodec?t.decryptAacSamples(r.samples,0,(()=>{s.samples?t.decryptAvcSamples(s.samples,0,0,(()=>{i(e)})):i(e)})):s.samples&&t.decryptAvcSamples(s.samples,0,0,(()=>{i(e)}))}))}destroy(){this._duration=0}parseAACPES(e,t){let i,r,s,n=0,a=this.aacOverFlow,o=t.data;if(a){this.aacOverFlow=null;let t=a.missing,i=a.sample.unit.byteLength;if(-1===t)o=gm(a.sample.unit,o);else{let r=i-t;a.sample.unit.set(o.subarray(0,t),r),e.samples.push(a.sample),n=a.missing}}for(i=n,r=o.length;i<r-1&&!dE(o,i);i++);if(i!==n){let e,t=i<r-1;if(e=t?`AAC PES did not start with ADTS header,offset:${i}`:"No ADTS header found in AAC PES",UE(this.observer,new Error(e),t),!t)return}if(cE(e,this.observer,o,i,this.audioCodec),void 0!==t.pts)s=t.pts;else{if(!a)return void tp.warn("[tsdemuxer]: AAC PES unknown PTS");{let t=fE(e.samplerate);s=a.sample.pts+t}}let l,h=0;for(;i<r;){if(l=pE(e,o,i,s,h),i+=l.length,l.missing){this.aacOverFlow=l;break}for(h++;i<r-1&&!dE(o,i);i++);}}parseMPEGPES(e,t){let i=t.data,r=i.length,s=0,n=0,a=t.pts;if(void 0!==a)for(;n<r;)if(AE(i,n)){let t=bE(e,i,n,a,s);if(!t)break;n+=t.length,s++}else n++;else tp.warn("[tsdemuxer]: MPEG PES unknown PTS")}parseAC3PES(e,t){{let i=t.data,r=t.pts;if(void 0===r)return void tp.warn("[tsdemuxer]: AC3 PES unknown PTS");let s,n=i.length,a=0,o=0;for(;o<n&&(s=LE(e,i,o,r,a++))>0;)o+=s}}parseID3PES(e,t){if(void 0===t.pts)return void tp.warn("[tsdemuxer]: ID3 PES unknown PTS");let i=Vf({},t,{type:this._videoTrack?Eg:gg,duration:Number.POSITIVE_INFINITY});e.samples.push(i)}},remux:WE},{demux:class extends nE{constructor(e,t){super(),this.observer=void 0,this.config=void 0,this.observer=e,this.config=t}resetInitSegment(e,t,i,r){super.resetInitSegment(e,t,i,r),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:t,duration:r,inputTimeScale:9e4,dropped:0}}static probe(e){if(!e)return!1;let t=$p(e,0),i=t?.length||0;if(_E(e,i))return!1;for(let t=e.length;i<t;i++)if(uE(e,i))return tp.log("ADTS sync word found !"),!0;return!1}canParse(e,t){return function(e,t){return function(e,t){return t+5<e.length}(e,t)&&oE(e,t)&&hE(e,t)<=e.length-t}(e,t)}appendFrame(e,t,i){cE(e,this.observer,t,i,e.manifestCodec);let r=pE(e,t,i,this.basePTS,this.frameIndex);if(r&&0===r.missing)return r}},remux:WE},{demux:class extends nE{resetInitSegment(e,t,i,r){super.resetInitSegment(e,t,i,r),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:t,duration:r,inputTimeScale:9e4,dropped:0}}static probe(e){if(!e)return!1;let t=$p(e,0),i=t?.length||0;if(t&&11===e[i]&&119===e[i+1]&&void 0!==Hp(t)&&kE(e,i)<=16)return!1;for(let t=e.length;i<t;i++)if(_E(e,i))return tp.log("MPEG Audio sync word found !"),!0;return!1}canParse(e,t){return function(e,t){return SE(e,t)&&4<=e.length-t}(e,t)}appendFrame(e,t,i){if(null!==this.basePTS)return bE(e,t,i,this.basePTS,this.frameIndex)}},remux:WE}];JE.splice(2,0,{demux:class extends nE{constructor(e){super(),this.observer=void 0,this.observer=e}resetInitSegment(e,t,i,r){super.resetInitSegment(e,t,i,r),this._audioTrack={container:"audio/ac-3",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"ac3",samples:[],manifestCodec:t,duration:r,inputTimeScale:9e4,dropped:0}}canParse(e,t){return t+64<e.length}appendFrame(e,t,i){let r=LE(e,t,i,this.basePTS,this.frameIndex);if(-1!==r)return{sample:e.samples[e.samples.length-1],length:r,missing:0}}static probe(e){if(!e)return!1;let t=$p(e,0);if(!t)return!1;let i=t.length;return 11===e[i]&&119===e[i+1]&&void 0!==Hp(t)&&kE(e,i)<16}},remux:WE});var ey=class{constructor(e,t,i,r,s){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=e,this.typeSupported=t,this.config=i,this.vendor=r,this.id=s}configure(e){this.transmuxConfig=e,this.decrypter&&this.decrypter.reset()}push(e,t,i,r){let s=i.transmuxing;s.executeStart=XE();let n=new Uint8Array(e),{currentTransmuxState:a,transmuxConfig:o}=this;r&&(this.currentTransmuxState=r);let{contiguous:l,discontinuity:h,trackSwitch:d,accurateTimeOffset:u,timeOffset:c,initSegmentChange:f}=r||a,{audioCodec:p,videoCodec:m,defaultInitPts:g,duration:v,initSegmentData:E}=o,y=function(e,t){let i=null;return e.byteLength>0&&null!=t?.key&&null!==t.iv&&null!=t.method&&(i=t),i}(n,t);if(y&&"AES-128"===y.method){let e=this.getDecrypter();if(!e.isSync())return this.decryptionPromise=e.webCryptoDecrypt(n,y.key.buffer,y.iv.buffer).then((e=>{let t=this.push(e,null,i);return this.decryptionPromise=null,t})),this.decryptionPromise;{let t=e.softwareDecrypt(n,y.key.buffer,y.iv.buffer);if(i.part>-1&&(t=e.flush()),!t)return s.executeEnd=XE(),ty(i);n=new Uint8Array(t)}}let b=this.needsProbing(h,d);if(b){let e=this.configureTransmuxer(n);if(e)return tp.warn(`[transmuxer] ${e.message}`),this.observer.emit(Yf.ERROR,Yf.ERROR,{type:zf.MEDIA_ERROR,details:Xf.FRAG_PARSING_ERROR,fatal:!1,error:e,reason:e.message}),s.executeEnd=XE(),ty(i)}(h||d||f||b)&&this.resetInitSegment(E,p,m,v,t),(h||f||b)&&this.resetInitialTimestamp(g),l||this.resetContiguity();let T=this.transmux(n,y,c,u,i),S=this.currentTransmuxState;return S.contiguous=!0,S.discontinuity=!1,S.trackSwitch=!1,s.executeEnd=XE(),T}flush(e){let t=e.transmuxing;t.executeStart=XE();let{decrypter:i,currentTransmuxState:r,decryptionPromise:s}=this;if(s)return s.then((()=>this.flush(e)));let n=[],{timeOffset:a}=r;if(i){let t=i.flush();t&&n.push(this.push(t,null,e))}let{demuxer:o,remuxer:l}=this;if(!o||!l)return t.executeEnd=XE(),[ty(e)];let h=o.flush(a);return iy(h)?h.then((t=>(this.flushRemux(n,t,e),n))):(this.flushRemux(n,h,e),n)}flushRemux(e,t,i){let{audioTrack:r,videoTrack:s,id3Track:n,textTrack:a}=t,{accurateTimeOffset:o,timeOffset:l}=this.currentTransmuxState;tp.log(`[transmuxer.ts]: Flushed fragment ${i.sn}${i.part>-1?" p: "+i.part:""} of level ${i.level}`);let h=this.remuxer.remux(r,s,n,a,l,o,!0,this.id);e.push({remuxResult:h,chunkMeta:i}),i.transmuxing.executeEnd=XE()}resetInitialTimestamp(e){let{demuxer:t,remuxer:i}=this;!t||!i||(t.resetTimeStamp(e),i.resetTimeStamp(e))}resetContiguity(){let{demuxer:e,remuxer:t}=this;!e||!t||(e.resetContiguity(),t.resetNextTimestamp())}resetInitSegment(e,t,i,r,s){let{demuxer:n,remuxer:a}=this;!n||!a||(n.resetInitSegment(e,t,i,r),a.resetInitSegment(e,t,i,s))}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)}transmux(e,t,i,r,s){let n;return n=t&&"SAMPLE-AES"===t.method?this.transmuxSampleAes(e,t,i,r,s):this.transmuxUnencrypted(e,i,r,s),n}transmuxUnencrypted(e,t,i,r){let{audioTrack:s,videoTrack:n,id3Track:a,textTrack:o}=this.demuxer.demux(e,t,!1,!this.config.progressive);return{remuxResult:this.remuxer.remux(s,n,a,o,t,i,!1,this.id),chunkMeta:r}}transmuxSampleAes(e,t,i,r,s){return this.demuxer.demuxSampleAes(e,t,i).then((e=>({remuxResult:this.remuxer.remux(e.audioTrack,e.videoTrack,e.id3Track,e.textTrack,i,r,!1,this.id),chunkMeta:s})))}configureTransmuxer(e){let t,{config:i,observer:r,typeSupported:s,vendor:n}=this;for(let i=0,r=JE.length;i<r;i++){var a;if(null!=(a=JE[i].demux)&&a.probe(e)){t=JE[i];break}}if(!t)return new Error("Failed to find demuxer by probing fragment data");let o=this.demuxer,l=this.remuxer,h=t.remux,d=t.demux;(!l||!(l instanceof h))&&(this.remuxer=new h(r,i,s,n)),(!o||!(o instanceof d))&&(this.demuxer=new d(r,i,s),this.probe=d.probe)}needsProbing(e,t){return!this.demuxer||!this.remuxer||e||t}getDecrypter(){let e=this.decrypter;return e||(e=this.decrypter=new Gv(this.config)),e}};var ty=e=>({remuxResult:{},chunkMeta:e});function iy(e){return"then"in e&&e.then instanceof Function}var ry=class{constructor(e,t,i,r,s){this.audioCodec=void 0,this.videoCodec=void 0,this.initSegmentData=void 0,this.duration=void 0,this.defaultInitPts=void 0,this.audioCodec=e,this.videoCodec=t,this.initSegmentData=i,this.duration=r,this.defaultInitPts=s||null}},sy=class{constructor(e,t,i,r,s,n){this.discontinuity=void 0,this.contiguous=void 0,this.accurateTimeOffset=void 0,this.trackSwitch=void 0,this.timeOffset=void 0,this.initSegmentChange=void 0,this.discontinuity=e,this.contiguous=t,this.accurateTimeOffset=i,this.trackSwitch=r,this.timeOffset=s,this.initSegmentChange=n}},ny={exports:{}};!function(e){var t=Object.prototype.hasOwnProperty,i="~";function r(){}function s(e,t,i){this.fn=e,this.context=t,this.once=i||!1}function n(e,t,r,n,a){if("function"!=typeof r)throw new TypeError("The listener must be a function");var o=new s(r,n||e,a),l=i?i+t:t;return e._events[l]?e._events[l].fn?e._events[l]=[e._events[l],o]:e._events[l].push(o):(e._events[l]=o,e._eventsCount++),e}function a(e,t){0==--e._eventsCount?e._events=new r:delete e._events[t]}function o(){this._events=new r,this._eventsCount=0}Object.create&&(r.prototype=Object.create(null),(new r).__proto__||(i=!1)),o.prototype.eventNames=function(){var e,r,s=[];if(0===this._eventsCount)return s;for(r in e=this._events)t.call(e,r)&&s.push(i?r.slice(1):r);return Object.getOwnPropertySymbols?s.concat(Object.getOwnPropertySymbols(e)):s},o.prototype.listeners=function(e){var t=i?i+e:e,r=this._events[t];if(!r)return[];if(r.fn)return[r.fn];for(var s=0,n=r.length,a=new Array(n);s<n;s++)a[s]=r[s].fn;return a},o.prototype.listenerCount=function(e){var t=i?i+e:e,r=this._events[t];return r?r.fn?1:r.length:0},o.prototype.emit=function(e,t,r,s,n,a){var o=i?i+e:e;if(!this._events[o])return!1;var l,h,d=this._events[o],u=arguments.length;if(d.fn){switch(d.once&&this.removeListener(e,d.fn,void 0,!0),u){case 1:return d.fn.call(d.context),!0;case 2:return d.fn.call(d.context,t),!0;case 3:return d.fn.call(d.context,t,r),!0;case 4:return d.fn.call(d.context,t,r,s),!0;case 5:return d.fn.call(d.context,t,r,s,n),!0;case 6:return d.fn.call(d.context,t,r,s,n,a),!0}for(h=1,l=new Array(u-1);h<u;h++)l[h-1]=arguments[h];d.fn.apply(d.context,l)}else{var c,f=d.length;for(h=0;h<f;h++)switch(d[h].once&&this.removeListener(e,d[h].fn,void 0,!0),u){case 1:d[h].fn.call(d[h].context);break;case 2:d[h].fn.call(d[h].context,t);break;case 3:d[h].fn.call(d[h].context,t,r);break;case 4:d[h].fn.call(d[h].context,t,r,s);break;default:if(!l)for(c=1,l=new Array(u-1);c<u;c++)l[c-1]=arguments[c];d[h].fn.apply(d[h].context,l)}}return!0},o.prototype.on=function(e,t,i){return n(this,e,t,i,!1)},o.prototype.once=function(e,t,i){return n(this,e,t,i,!0)},o.prototype.removeListener=function(e,t,r,s){var n=i?i+e:e;if(!this._events[n])return this;if(!t)return a(this,n),this;var o=this._events[n];if(o.fn)o.fn===t&&(!s||o.once)&&(!r||o.context===r)&&a(this,n);else{for(var l=0,h=[],d=o.length;l<d;l++)(o[l].fn!==t||s&&!o[l].once||r&&o[l].context!==r)&&h.push(o[l]);h.length?this._events[n]=1===h.length?h[0]:h:a(this,n)}return this},o.prototype.removeAllListeners=function(e){var t;return e?(t=i?i+e:e,this._events[t]&&a(this,t)):(this._events=new r,this._eventsCount=0),this},o.prototype.off=o.prototype.removeListener,o.prototype.addListener=o.prototype.on,o.prefixed=i,o.EventEmitter=o,e.exports=o}(ny);var ay=function(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}(ny.exports),oy=class{constructor(e,t,i,r){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;let s=e.config;this.hls=e,this.id=t,this.useWorker=!!s.enableWorker,this.onTransmuxComplete=i,this.onFlush=r;let n=(e,t)=>{(t=t||{}).frag=this.frag,t.id=this.id,e===Yf.ERROR&&(this.error=t.error),this.hls.trigger(e,t)};this.observer=new ay,this.observer.on(Yf.FRAG_DECRYPTED,n),this.observer.on(Yf.ERROR,n);let a=Dm(s.preferManagedMediaSource)||{isTypeSupported:()=>!1},o={mpeg:a.isTypeSupported("audio/mpeg"),mp3:a.isTypeSupported('audio/mp4; codecs="mp3"'),ac3:a.isTypeSupported('audio/mp4; codecs="ac-3"')};if(this.useWorker&&typeof Worker<"u"&&(s.workerPath||"function"==typeof __HLS_WORKER_BUNDLE__))try{s.workerPath?(tp.log(`loading Web Worker ${s.workerPath} for "${t}"`),this.workerContext=function(e){let t=new self.URL(e,self.location.href).href;return{worker:new self.Worker(t),scriptURL:t}}(s.workerPath)):(tp.log(`injecting Web Worker for "${t}"`),this.workerContext=function(){let e=new self.Blob([`var exports={};var module={exports:exports};function define(f){f()};define.amd=true;(${__HLS_WORKER_BUNDLE__.toString()})(true);`],{type:"text/javascript"}),t=self.URL.createObjectURL(e);return{worker:new self.Worker(t),objectURL:t}}()),this.onwmsg=e=>this.onWorkerMessage(e);let{worker:e}=this.workerContext;e.addEventListener("message",this.onwmsg),e.onerror=e=>{let i=new Error(`${e.message}  (${e.filename}:${e.lineno})`);s.enableWorker=!1,tp.warn(`Error in "${t}" Web Worker, fallback to inline`),this.hls.trigger(Yf.ERROR,{type:zf.OTHER_ERROR,details:Xf.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:i})},e.postMessage({cmd:"init",typeSupported:o,vendor:"",id:t,config:JSON.stringify(s)})}catch(e){tp.warn(`Error setting up "${t}" Web Worker, fallback to inline`,e),this.resetWorker(),this.error=null,this.transmuxer=new ey(this.observer,o,s,"",t)}else this.transmuxer=new ey(this.observer,o,s,"",t)}resetWorker(){if(this.workerContext){let{worker:e,objectURL:t}=this.workerContext;t&&self.URL.revokeObjectURL(t),e.removeEventListener("message",this.onwmsg),e.onerror=null,e.terminate(),this.workerContext=null}}destroy(){if(this.workerContext)this.resetWorker(),this.onwmsg=void 0;else{let e=this.transmuxer;e&&(e.destroy(),this.transmuxer=null)}let e=this.observer;e&&e.removeAllListeners(),this.frag=null,this.observer=null,this.hls=null}push(e,t,i,r,s,n,a,o,l,h){var d,u;l.transmuxing.start=self.performance.now();let{transmuxer:c}=this,f=n?n.start:s.start,p=s.decryptdata,m=this.frag,g=!(m&&s.cc===m.cc),v=!(m&&l.level===m.level),E=m?l.sn-m.sn:-1,y=this.part?l.part-this.part.index:-1,b=0===E&&l.id>1&&l.id===m?.stats.chunkCount,T=!v&&(1===E||0===E&&(1===y||b&&y<=0)),S=self.performance.now();(v||E||0===s.stats.parsing.start)&&(s.stats.parsing.start=S),n&&(y||!T)&&(n.stats.parsing.start=S);let A=!(m&&(null==(d=s.initSegment)?void 0:d.url)===(null==(u=m.initSegment)?void 0:u.url)),_=new sy(g,T,o,v,f,A);if(!T||g||A){tp.log(`[transmuxer-interface, ${s.type}]: Starting new transmux session for sn: ${l.sn} p: ${l.part} level: ${l.level} id: ${l.id}\n        discontinuity: ${g}\n        trackSwitch: ${v}\n        contiguous: ${T}\n        accurateTimeOffset: ${o}\n        timeOffset: ${f}\n        initSegmentChange: ${A}`);let e=new ry(i,r,t,a,h);this.configureTransmuxer(e)}if(this.frag=s,this.part=n,this.workerContext)this.workerContext.worker.postMessage({cmd:"demux",data:e,decryptdata:p,chunkMeta:l,state:_},e instanceof ArrayBuffer?[e]:[]);else if(c){let t=c.push(e,p,l,_);iy(t)?(c.async=!0,t.then((e=>{this.handleTransmuxComplete(e)})).catch((e=>{this.transmuxerError(e,l,"transmuxer-interface push error")}))):(c.async=!1,this.handleTransmuxComplete(t))}}flush(e){e.transmuxing.start=self.performance.now();let{transmuxer:t}=this;if(this.workerContext)this.workerContext.worker.postMessage({cmd:"flush",chunkMeta:e});else if(t){let i=t.flush(e);iy(i)||t.async?(iy(i)||(i=Promise.resolve(i)),i.then((t=>{this.handleFlushResult(t,e)})).catch((t=>{this.transmuxerError(t,e,"transmuxer-interface flush error")}))):this.handleFlushResult(i,e)}}transmuxerError(e,t,i){this.hls&&(this.error=e,this.hls.trigger(Yf.ERROR,{type:zf.MEDIA_ERROR,details:Xf.FRAG_PARSING_ERROR,chunkMeta:t,frag:this.frag||void 0,fatal:!1,error:e,err:e,reason:i}))}handleFlushResult(e,t){e.forEach((e=>{this.handleTransmuxComplete(e)})),this.onFlush(t)}onWorkerMessage(e){let t=e.data;if(null==t||!t.event)return void tp.warn("worker message received with no "+(t?"event name":"data"));let i=this.hls;if(this.hls)switch(t.event){case"init":{var r;let e=null==(r=this.workerContext)?void 0:r.objectURL;e&&self.URL.revokeObjectURL(e);break}case"transmuxComplete":this.handleTransmuxComplete(t.data);break;case"flush":this.onFlush(t.data);break;case"workerLog":tp[t.data.logType]&&tp[t.data.logType](t.data.message);break;default:t.data=t.data||{},t.data.frag=this.frag,t.data.id=this.id,i.trigger(t.event,t.data)}}configureTransmuxer(e){let{transmuxer:t}=this;this.workerContext?this.workerContext.worker.postMessage({cmd:"configure",config:e}):t&&t.configure(e)}handleTransmuxComplete(e){e.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(e)}};function ly(e,t){if(e.length!==t.length)return!1;for(let i=0;i<e.length;i++)if(!hy(e[i].attrs,t[i].attrs))return!1;return!0}function hy(e,t,i){let r=e["STABLE-RENDITION-ID"];return r&&!i?r===t["STABLE-RENDITION-ID"]:!(i||["LANGUAGE","NAME","CHARACTERISTICS","AUTOSELECT","DEFAULT","FORCED","ASSOC-LANGUAGE"]).some((i=>e[i]!==t[i]))}function dy(e,t){return t.label.toLowerCase()===e.name.toLowerCase()&&(!t.language||t.language.toLowerCase()===(e.lang||"").toLowerCase())}var uy=class{constructor(e){this.buffered=void 0;let t=(t,i,r)=>{if((i>>>=0)>r-1)throw new DOMException(`Failed to execute '${t}' on 'TimeRanges': The index provided (${i}) is greater than the maximum bound (${r})`);return e[i][t]};this.buffered={get length(){return e.length},end:i=>t("end",i,e.length),start:i=>t("start",i,e.length)}}},cy=class{constructor(e){this.buffers=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.buffers=e}append(e,t,i){let r=this.queues[t];r.push(e),1===r.length&&!i&&this.executeNext(t)}insertAbort(e,t){this.queues[t].unshift(e),this.executeNext(t)}appendBlocker(e){let t,i=new Promise((e=>{t=e})),r={execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};return this.append(r,e),i}executeNext(e){let t=this.queues[e];if(t.length){let i=t[0];try{i.execute()}catch(t){tp.warn(`[buffer-operation-queue]: Exception executing "${e}" SourceBuffer operation: ${t}`),i.onError(t);let r=this.buffers[e];null!=r&&r.updating||this.shiftAndExecuteNext(e)}}}shiftAndExecuteNext(e){this.queues[e].shift(),this.executeNext(e)}current(e){return this.queues[e][0]}},fy=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/;function py(e){let t=e.querySelectorAll("source");[].slice.call(t).forEach((t=>{e.removeChild(t)}))}var my={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},gy=e=>String.fromCharCode(my[e]||e),vy=15,Ey=100,yy={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},by={17:2,18:4,21:6,22:8,23:10,19:13,20:15},Ty={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},Sy={25:2,26:4,29:6,30:8,31:10,27:13,28:15},Ay=["white","green","blue","cyan","red","yellow","magenta","black","transparent"],_y=class{constructor(){this.time=null,this.verboseLevel=0}log(e,t){if(this.verboseLevel>=e){let i="function"==typeof t?t():t;tp.log(`${this.time} [${e}] ${i}`)}}},wy=function(e){let t=[];for(let i=0;i<e.length;i++)t.push(e[i].toString(16));return t},ky=class{constructor(){this.foreground="white",this.underline=!1,this.italics=!1,this.background="black",this.flash=!1}reset(){this.foreground="white",this.underline=!1,this.italics=!1,this.background="black",this.flash=!1}setStyles(e){let t=["foreground","underline","italics","background","flash"];for(let i=0;i<t.length;i++){let r=t[i];e.hasOwnProperty(r)&&(this[r]=e[r])}}isDefault(){return"white"===this.foreground&&!this.underline&&!this.italics&&"black"===this.background&&!this.flash}equals(e){return this.foreground===e.foreground&&this.underline===e.underline&&this.italics===e.italics&&this.background===e.background&&this.flash===e.flash}copy(e){this.foreground=e.foreground,this.underline=e.underline,this.italics=e.italics,this.background=e.background,this.flash=e.flash}toString(){return"color="+this.foreground+", underline="+this.underline+", italics="+this.italics+", background="+this.background+", flash="+this.flash}},Ly=class{constructor(){this.uchar=" ",this.penState=new ky}reset(){this.uchar=" ",this.penState.reset()}setChar(e,t){this.uchar=e,this.penState.copy(t)}setPenState(e){this.penState.copy(e)}equals(e){return this.uchar===e.uchar&&this.penState.equals(e.penState)}copy(e){this.uchar=e.uchar,this.penState.copy(e.penState)}isEmpty(){return" "===this.uchar&&this.penState.isDefault()}},Ry=class{constructor(e){this.chars=[],this.pos=0,this.currPenState=new ky,this.cueStartTime=null,this.logger=void 0;for(let e=0;e<Ey;e++)this.chars.push(new Ly);this.logger=e}equals(e){for(let t=0;t<Ey;t++)if(!this.chars[t].equals(e.chars[t]))return!1;return!0}copy(e){for(let t=0;t<Ey;t++)this.chars[t].copy(e.chars[t])}isEmpty(){let e=!0;for(let t=0;t<Ey;t++)if(!this.chars[t].isEmpty()){e=!1;break}return e}setCursor(e){this.pos!==e&&(this.pos=e),this.pos<0?(this.logger.log(3,"Negative cursor position "+this.pos),this.pos=0):this.pos>Ey&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=Ey)}moveCursor(e){let t=this.pos+e;if(e>1)for(let e=this.pos+1;e<t+1;e++)this.chars[e].setPenState(this.currPenState);this.setCursor(t)}backSpace(){this.moveCursor(-1),this.chars[this.pos].setChar(" ",this.currPenState)}insertChar(e){e>=144&&this.backSpace();let t=gy(e);this.pos>=Ey?this.logger.log(0,(()=>"Cannot insert "+e.toString(16)+" ("+t+") at position "+this.pos+". Skipping it!")):(this.chars[this.pos].setChar(t,this.currPenState),this.moveCursor(1))}clearFromPos(e){let t;for(t=e;t<Ey;t++)this.chars[t].reset()}clear(){this.clearFromPos(0),this.pos=0,this.currPenState.reset()}clearToEndOfRow(){this.clearFromPos(this.pos)}getTextString(){let e=[],t=!0;for(let i=0;i<Ey;i++){let r=this.chars[i].uchar;" "!==r&&(t=!1),e.push(r)}return t?"":e.join("")}setPenStyles(e){this.currPenState.setStyles(e),this.chars[this.pos].setPenState(this.currPenState)}},Iy=class{constructor(e){this.rows=[],this.currRow=14,this.nrRollUpRows=null,this.lastOutputScreen=null,this.logger=void 0;for(let t=0;t<vy;t++)this.rows.push(new Ry(e));this.logger=e}reset(){for(let e=0;e<vy;e++)this.rows[e].clear();this.currRow=14}equals(e){let t=!0;for(let i=0;i<vy;i++)if(!this.rows[i].equals(e.rows[i])){t=!1;break}return t}copy(e){for(let t=0;t<vy;t++)this.rows[t].copy(e.rows[t])}isEmpty(){let e=!0;for(let t=0;t<vy;t++)if(!this.rows[t].isEmpty()){e=!1;break}return e}backSpace(){this.rows[this.currRow].backSpace()}clearToEndOfRow(){this.rows[this.currRow].clearToEndOfRow()}insertChar(e){this.rows[this.currRow].insertChar(e)}setPen(e){this.rows[this.currRow].setPenStyles(e)}moveCursor(e){this.rows[this.currRow].moveCursor(e)}setCursor(e){this.logger.log(2,"setCursor: "+e),this.rows[this.currRow].setCursor(e)}setPAC(e){this.logger.log(2,(()=>"pacData = "+JSON.stringify(e)));let t=e.row-1;if(this.nrRollUpRows&&t<this.nrRollUpRows-1&&(t=this.nrRollUpRows-1),this.nrRollUpRows&&this.currRow!==t){for(let e=0;e<vy;e++)this.rows[e].clear();let e=this.currRow+1-this.nrRollUpRows,i=this.lastOutputScreen;if(i){let r=i.rows[e].cueStartTime,s=this.logger.time;if(null!==r&&null!==s&&r<s)for(let r=0;r<this.nrRollUpRows;r++)this.rows[t-this.nrRollUpRows+r+1].copy(i.rows[e+r])}}this.currRow=t;let i=this.rows[this.currRow];if(null!==e.indent){let t=e.indent,r=Math.max(t-1,0);i.setCursor(e.indent),e.color=i.chars[r].penState.foreground}let r={foreground:e.color,underline:e.underline,italics:e.italics,background:"black",flash:!1};this.setPen(r)}setBkgData(e){this.logger.log(2,(()=>"bkgData = "+JSON.stringify(e))),this.backSpace(),this.setPen(e),this.insertChar(32)}setRollUpRows(e){this.nrRollUpRows=e}rollUp(){if(null===this.nrRollUpRows)return void this.logger.log(3,"roll_up but nrRollUpRows not set yet");this.logger.log(1,(()=>this.getDisplayText()));let e=this.currRow+1-this.nrRollUpRows,t=this.rows.splice(e,1)[0];t.clear(),this.rows.splice(this.currRow,0,t),this.logger.log(2,"Rolling up")}getDisplayText(e){e=e||!1;let t=[],i="",r=-1;for(let i=0;i<vy;i++){let s=this.rows[i].getTextString();s&&(r=i+1,e?t.push("Row "+r+": '"+s+"'"):t.push(s.trim()))}return t.length>0&&(i=e?"["+t.join(" | ")+"]":t.join("\n")),i}getTextAndFormat(){return this.rows}},Cy=class{constructor(e,t,i){this.chNr=void 0,this.outputFilter=void 0,this.mode=void 0,this.verbose=void 0,this.displayedMemory=void 0,this.nonDisplayedMemory=void 0,this.lastOutputScreen=void 0,this.currRollUpRow=void 0,this.writeScreen=void 0,this.cueStartTime=void 0,this.logger=void 0,this.chNr=e,this.outputFilter=t,this.mode=null,this.verbose=0,this.displayedMemory=new Iy(i),this.nonDisplayedMemory=new Iy(i),this.lastOutputScreen=new Iy(i),this.currRollUpRow=this.displayedMemory.rows[14],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[14],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null}getHandler(){return this.outputFilter}setHandler(e){this.outputFilter=e}setPAC(e){this.writeScreen.setPAC(e)}setBkgData(e){this.writeScreen.setBkgData(e)}setMode(e){e!==this.mode&&(this.mode=e,this.logger.log(2,(()=>"MODE="+e)),"MODE_POP-ON"===this.mode?this.writeScreen=this.nonDisplayedMemory:(this.writeScreen=this.displayedMemory,this.writeScreen.reset()),"MODE_ROLL-UP"!==this.mode&&(this.displayedMemory.nrRollUpRows=null,this.nonDisplayedMemory.nrRollUpRows=null),this.mode=e)}insertChars(e){for(let t=0;t<e.length;t++)this.writeScreen.insertChar(e[t]);let t=this.writeScreen===this.displayedMemory?"DISP":"NON_DISP";this.logger.log(2,(()=>t+": "+this.writeScreen.getDisplayText(!0))),("MODE_PAINT-ON"===this.mode||"MODE_ROLL-UP"===this.mode)&&(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"),"MODE_TEXT"!==this.mode&&(this.writeScreen.backSpace(),this.writeScreen===this.displayedMemory&&this.outputDataUpdate())}ccAOF(){}ccAON(){}ccDER(){this.logger.log(2,"DER- Delete to End of Row"),this.writeScreen.clearToEndOfRow(),this.outputDataUpdate()}ccRU(e){this.logger.log(2,"RU("+e+") - Roll Up"),this.writeScreen=this.displayedMemory,this.setMode("MODE_ROLL-UP"),this.writeScreen.setRollUpRows(e)}ccFON(){this.logger.log(2,"FON - Flash On"),this.writeScreen.setPen({flash:!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"),"MODE_POP-ON"===this.mode){let e=this.displayedMemory;this.displayedMemory=this.nonDisplayedMemory,this.nonDisplayedMemory=e,this.writeScreen=this.nonDisplayedMemory,this.logger.log(1,(()=>"DISP: "+this.displayedMemory.getDisplayText()))}this.outputDataUpdate(!0)}ccTO(e){this.logger.log(2,"TO("+e+") - Tab Offset"),this.writeScreen.moveCursor(e)}ccMIDROW(e){let t={flash:!1};if(t.underline=e%2==1,t.italics=e>=46,t.italics)t.foreground="white";else{let i=Math.floor(e/2)-16,r=["white","green","blue","cyan","red","yellow","magenta"];t.foreground=r[i]}this.logger.log(2,"MIDROW: "+JSON.stringify(t)),this.writeScreen.setPen(t)}outputDataUpdate(e=!1){let t=this.logger.time;null!==t&&this.outputFilter&&(null!==this.cueStartTime||this.displayedMemory.isEmpty()?this.displayedMemory.equals(this.lastOutputScreen)||(this.outputFilter.newCue(this.cueStartTime,t,this.lastOutputScreen),e&&this.outputFilter.dispatchCue&&this.outputFilter.dispatchCue(),this.cueStartTime=this.displayedMemory.isEmpty()?null:t):this.cueStartTime=t,this.lastOutputScreen.copy(this.displayedMemory))}cueSplitAtTime(e){this.outputFilter&&(this.displayedMemory.isEmpty()||(this.outputFilter.newCue&&this.outputFilter.newCue(this.cueStartTime,e,this.displayedMemory),this.cueStartTime=e))}},Dy=class{constructor(e,t,i){this.channels=void 0,this.currentChannel=0,this.cmdHistory={a:null,b:null},this.logger=void 0;let r=this.logger=new _y;this.channels=[null,new Cy(e,t,r),new Cy(e+1,i,r)]}getHandler(e){return this.channels[e].getHandler()}setHandler(e,t){this.channels[e].setHandler(t)}addData(e,t){this.logger.time=e;for(let e=0;e<t.length;e+=2){let i=127&t[e],r=127&t[e+1],s=!1,n=null;if(0===i&&0===r)continue;this.logger.log(3,(()=>"["+wy([t[e],t[e+1]])+"] -> ("+wy([i,r])+")"));let a=this.cmdHistory;if(i>=16&&i<=31){if(My(i,r,a)){xy(null,null,a),this.logger.log(3,(()=>"Repeated command ("+wy([i,r])+") is dropped"));continue}xy(i,r,this.cmdHistory),s=this.parseCmd(i,r),s||(s=this.parseMidrow(i,r)),s||(s=this.parsePAC(i,r)),s||(s=this.parseBackgroundAttributes(i,r))}else xy(null,null,a);if(!s&&(n=this.parseChars(i,r),n)){let e=this.currentChannel;e&&e>0?this.channels[e].insertChars(n):this.logger.log(2,"No channel found yet. TEXT-MODE?")}!s&&!n&&this.logger.log(2,(()=>"Couldn't parse cleaned data "+wy([i,r])+" orig: "+wy([t[e],t[e+1]])))}}parseCmd(e,t){if(!((20===e||28===e||21===e||29===e)&&t>=32&&t<=47)&&!((23===e||31===e)&&t>=33&&t<=35))return!1;let i=20===e||21===e||23===e?1:2,r=this.channels[i];return 20===e||21===e||28===e||29===e?32===t?r.ccRCL():33===t?r.ccBS():34===t?r.ccAOF():35===t?r.ccAON():36===t?r.ccDER():37===t?r.ccRU(2):38===t?r.ccRU(3):39===t?r.ccRU(4):40===t?r.ccFON():41===t?r.ccRDC():42===t?r.ccTR():43===t?r.ccRTD():44===t?r.ccEDM():45===t?r.ccCR():46===t?r.ccENM():47===t&&r.ccEOC():r.ccTO(t-32),this.currentChannel=i,!0}parseMidrow(e,t){let i=0;if((17===e||25===e)&&t>=32&&t<=47){if(i=17===e?1:2,i!==this.currentChannel)return this.logger.log(0,"Mismatch channel in midrow parsing"),!1;let r=this.channels[i];return!!r&&(r.ccMIDROW(t),this.logger.log(3,(()=>"MIDROW ("+wy([e,t])+")")),!0)}return!1}parsePAC(e,t){let i;if(!((e>=17&&e<=23||e>=25&&e<=31)&&t>=64&&t<=127)&&!((16===e||24===e)&&t>=64&&t<=95))return!1;let r=e<=23?1:2;i=t>=64&&t<=95?1===r?yy[e]:Ty[e]:1===r?by[e]:Sy[e];let s=this.channels[r];return!!s&&(s.setPAC(this.interpretPAC(i,t)),this.currentChannel=r,!0)}interpretPAC(e,t){let i,r={color:null,italics:!1,indent:null,underline:!1,row:e};return i=t>95?t-96:t-64,r.underline=!(1&~i),i<=13?r.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(i/2)]:i<=15?(r.italics=!0,r.color="white"):r.indent=4*Math.floor((i-16)/2),r}parseChars(e,t){let i,r=null,s=null;if(e>=25?(i=2,s=e-8):(i=1,s=e),s>=17&&s<=19){let e;e=17===s?t+80:18===s?t+112:t+144,this.logger.log(2,(()=>"Special char '"+gy(e)+"' in channel "+i)),r=[e]}else e>=32&&e<=127&&(r=0===t?[e]:[e,t]);return r&&this.logger.log(3,(()=>"Char codes =  "+wy(r).join(","))),r}parseBackgroundAttributes(e,t){if(!((16===e||24===e)&&t>=32&&t<=47)&&!((23===e||31===e)&&t>=45&&t<=47))return!1;let i,r={};16===e||24===e?(i=Math.floor((t-32)/2),r.background=Ay[i],t%2==1&&(r.background=r.background+"_semi")):45===t?r.background="transparent":(r.foreground="black",47===t&&(r.underline=!0));let s=e<=23?1:2;return this.channels[s].setBkgData(r),!0}reset(){for(let e=0;e<Object.keys(this.channels).length;e++){let t=this.channels[e];t&&t.reset()}xy(null,null,this.cmdHistory)}cueSplitAtTime(e){for(let t=0;t<this.channels.length;t++){let i=this.channels[t];i&&i.cueSplitAtTime(e)}}};function xy(e,t,i){i.a=e,i.b=t}function My(e,t,i){return i.a===e&&i.b===t}var Py=class{constructor(e,t){this.timelineController=void 0,this.cueRanges=[],this.trackName=void 0,this.startTime=null,this.endTime=null,this.screen=null,this.timelineController=e,this.trackName=t}dispatchCue(){null!==this.startTime&&(this.timelineController.addCues(this.trackName,this.startTime,this.endTime,this.screen,this.cueRanges),this.startTime=null)}newCue(e,t,i){(null===this.startTime||this.startTime>e)&&(this.startTime=e),this.endTime=t,this.screen=i,this.timelineController.createCaptionsTrack(this.trackName)}reset(){this.cueRanges=[],this.startTime=null}},Oy=function(){if(null!=yp&&yp.VTTCue)return self.VTTCue;let e=["","lr","rl"],t=["start","middle","end","left","right"];function i(e,t){if("string"!=typeof t||!Array.isArray(e))return!1;let i=t.toLowerCase();return!!~e.indexOf(i)&&i}function r(e){return i(t,e)}function s(e,...t){let i=1;for(;i<arguments.length;i++){let t=arguments[i];for(let i in t)e[i]=t[i]}return e}function n(t,n,a){let o=this,l={enumerable:!0};o.hasBeenReset=!1;let h="",d=!1,u=t,c=n,f=a,p=null,m="",g=!0,v="auto",E="start",y=50,b="middle",T=50,S="middle";Object.defineProperty(o,"id",s({},l,{get:function(){return h},set:function(e){h=""+e}})),Object.defineProperty(o,"pauseOnExit",s({},l,{get:function(){return d},set:function(e){d=!!e}})),Object.defineProperty(o,"startTime",s({},l,{get:function(){return u},set:function(e){if("number"!=typeof e)throw new TypeError("Start time must be set to a number.");u=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"endTime",s({},l,{get:function(){return c},set:function(e){if("number"!=typeof e)throw new TypeError("End time must be set to a number.");c=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"text",s({},l,{get:function(){return f},set:function(e){f=""+e,this.hasBeenReset=!0}})),Object.defineProperty(o,"region",s({},l,{get:function(){return p},set:function(e){p=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"vertical",s({},l,{get:function(){return m},set:function(t){let r=function(t){return i(e,t)}(t);if(!1===r)throw new SyntaxError("An invalid or illegal string was specified.");m=r,this.hasBeenReset=!0}})),Object.defineProperty(o,"snapToLines",s({},l,{get:function(){return g},set:function(e){g=!!e,this.hasBeenReset=!0}})),Object.defineProperty(o,"line",s({},l,{get:function(){return v},set:function(e){if("number"!=typeof e&&"auto"!==e)throw new SyntaxError("An invalid number or illegal string was specified.");v=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"lineAlign",s({},l,{get:function(){return E},set:function(e){let t=r(e);if(!t)throw new SyntaxError("An invalid or illegal string was specified.");E=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"position",s({},l,{get:function(){return y},set:function(e){if(e<0||e>100)throw new Error("Position must be between 0 and 100.");y=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"positionAlign",s({},l,{get:function(){return b},set:function(e){let t=r(e);if(!t)throw new SyntaxError("An invalid or illegal string was specified.");b=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"size",s({},l,{get:function(){return T},set:function(e){if(e<0||e>100)throw new Error("Size must be between 0 and 100.");T=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"align",s({},l,{get:function(){return S},set:function(e){let t=r(e);if(!t)throw new SyntaxError("An invalid or illegal string was specified.");S=t,this.hasBeenReset=!0}})),o.displayState=void 0}return n.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},n}(),Uy=class{decode(e,t){if(!e)return"";if("string"!=typeof e)throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(e))}};function Ny(e){function t(e,t,i,r){return 3600*(0|e)+60*(0|t)+(0|i)+parseFloat(r||0)}let i=e.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);return i?parseFloat(i[2])>59?t(i[2],i[3],0,i[4]):t(i[1],i[2],i[3],i[4]):null}var $y=class{constructor(){this.values=Object.create(null)}set(e,t){!this.get(e)&&""!==t&&(this.values[e]=t)}get(e,t,i){return i?this.has(e)?this.values[e]:t[i]:this.has(e)?this.values[e]:t}has(e){return e in this.values}alt(e,t,i){for(let r=0;r<i.length;++r)if(t===i[r]){this.set(e,t);break}}integer(e,t){/^-?\d+$/.test(t)&&this.set(e,parseInt(t,10))}percent(e,t){if(/^([\d]{1,3})(\.[\d]*)?%$/.test(t)){let i=parseFloat(t);if(i>=0&&i<=100)return this.set(e,i),!0}return!1}};function Fy(e,t,i,r){let s=r?e.split(r):[e];for(let e in s){if("string"!=typeof s[e])continue;let r=s[e].split(i);2===r.length&&t(r[0],r[1])}}var By=new Oy(0,0,""),Hy="middle"===By.align?"middle":"center";function Gy(e,t,i){let r=e;function s(){let t=Ny(e);if(null===t)throw new Error("Malformed timestamp: "+r);return e=e.replace(/^[^\sa-zA-Z-]+/,""),t}function n(){e=e.replace(/^\s+/,"")}if(n(),t.startTime=s(),n(),"--\x3e"!==e.slice(0,3))throw new Error("Malformed time stamp (time stamps must be separated by '--\x3e'): "+r);e=e.slice(3),n(),t.endTime=s(),n(),function(e,t){let r=new $y;Fy(e,(function(e,t){let s;switch(e){case"region":for(let s=i.length-1;s>=0;s--)if(i[s].id===t){r.set(e,i[s].region);break}break;case"vertical":r.alt(e,t,["rl","lr"]);break;case"line":s=t.split(","),r.integer(e,s[0]),r.percent(e,s[0])&&r.set("snapToLines",!1),r.alt(e,s[0],["auto"]),2===s.length&&r.alt("lineAlign",s[1],["start",Hy,"end"]);break;case"position":s=t.split(","),r.percent(e,s[0]),2===s.length&&r.alt("positionAlign",s[1],["start",Hy,"end","line-left","line-right","auto"]);break;case"size":r.percent(e,t);break;case"align":r.alt(e,t,["start",Hy,"end","left","right"])}}),/:/,/\s/),t.region=r.get("region",null),t.vertical=r.get("vertical","");let s=r.get("line","auto");"auto"===s&&-1===By.line&&(s=-1),t.line=s,t.lineAlign=r.get("lineAlign","start"),t.snapToLines=r.get("snapToLines",!0),t.size=r.get("size",100),t.align=r.get("align",Hy);let n=r.get("position","auto");"auto"===n&&50===By.position&&(n="start"===t.align||"left"===t.align?0:"end"===t.align||"right"===t.align?100:50),t.position=n}(e,t)}function jy(e){return e.replace(/<br(?: \/)?>/gi,"\n")}var Vy=class{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new Uy,this.regionList=[],this.cue=null,this.oncue=void 0,this.onparsingerror=void 0,this.onflush=void 0}parse(e){let t=this;function i(){let e=t.buffer,i=0;for(e=jy(e);i<e.length&&"\r"!==e[i]&&"\n"!==e[i];)++i;let r=e.slice(0,i);return"\r"===e[i]&&++i,"\n"===e[i]&&++i,t.buffer=e.slice(i),r}function r(e){Fy(e,(function(e,t){}),/:/)}e&&(t.buffer+=t.decoder.decode(e,{stream:!0}));try{let e="";if("INITIAL"===t.state){if(!/\r\n|\n/.test(t.buffer))return this;e=i();let r=e.match(/^(ï»¿)?WEBVTT([ \t].*)?$/);if(null==r||!r[0])throw new Error("Malformed WebVTT signature.");t.state="HEADER"}let s=!1;for(;t.buffer;){if(!/\r\n|\n/.test(t.buffer))return this;switch(s?s=!1:e=i(),t.state){case"HEADER":/:/.test(e)?r(e):e||(t.state="ID");continue;case"NOTE":e||(t.state="ID");continue;case"ID":if(/^NOTE($|[ \t])/.test(e)){t.state="NOTE";break}if(!e)continue;if(t.cue=new Oy(0,0,""),t.state="CUE",-1===e.indexOf("--\x3e")){t.cue.id=e;continue}case"CUE":if(!t.cue){t.state="BADCUE";continue}try{Gy(e,t.cue,t.regionList)}catch{t.cue=null,t.state="BADCUE";continue}t.state="CUETEXT";continue;case"CUETEXT":{let i=-1!==e.indexOf("--\x3e");if(!e||i&&(s=!0)){t.oncue&&t.cue&&t.oncue(t.cue),t.cue=null,t.state="ID";continue}if(null===t.cue)continue;t.cue.text&&(t.cue.text+="\n"),t.cue.text+=e}continue;case"BADCUE":e||(t.state="ID")}}}catch{"CUETEXT"===t.state&&t.cue&&t.oncue&&t.oncue(t.cue),t.cue=null,t.state="INITIAL"===t.state?"BADWEBVTT":"BADCUE"}return this}flush(){let e=this;try{if((e.cue||"HEADER"===e.state)&&(e.buffer+="\n\n",e.parse()),"INITIAL"===e.state||"BADWEBVTT"===e.state)throw new Error("Malformed WebVTT signature.")}catch(t){e.onparsingerror&&e.onparsingerror(t)}return e.onflush&&e.onflush(),this}},Ky=/\r\n|\n\r|\n|\r/g,Wy=function(e,t,i=0){return e.slice(i,i+t.length)===t},qy=function(e){let t=5381,i=e.length;for(;i;)t=33*t^e.charCodeAt(--i);return(t>>>0).toString()};function Yy(e,t,i){return qy(e.toString())+qy(t.toString())+qy(i)}function zy(e,t,i,r,s,n,a){let o,l=new Vy,h=Xp(new Uint8Array(e)).trim().replace(Ky,"\n").split("\n"),d=[],u=t?function(e,t=1){return GE(e,9e4,1/t)}(t.baseTime,t.timescale):0,c="00:00.000",f=0,p=0,m=!0;l.oncue=function(e){let n=i[r],a=i.ccOffset,l=(f-u)/9e4;if(null!=n&&n.new&&(void 0!==p?a=i.ccOffset=n.start:function(e,t,i){let r=e[t],s=e[r.prevCC];if(!s||!s.new&&r.new)return e.ccOffset=e.presentationOffset=r.start,void(r.new=!1);for(;null!=(n=s)&&n.new;){var n;e.ccOffset+=r.start-s.start,r.new=!1,r=s,s=e[r.prevCC]}e.presentationOffset=i}(i,r,l)),l){if(!t)return void(o=new Error("Missing initPTS for VTT MPEGTS"));a=l-i.presentationOffset}let h=e.endTime-e.startTime,c=qE(9e4*(e.startTime+a-p),9e4*s)/9e4;e.startTime=Math.max(c,0),e.endTime=Math.max(c+h,0);let m=e.text.trim();e.text=decodeURIComponent(encodeURIComponent(m)),e.id||(e.id=Yy(e.startTime,e.endTime,m)),e.endTime>0&&d.push(e)},l.onparsingerror=function(e){o=e},l.onflush=function(){o?a(o):n(d)},h.forEach((e=>{if(m){if(Wy(e,"X-TIMESTAMP-MAP=")){m=!1,e.slice(16).split(",").forEach((e=>{Wy(e,"LOCAL:")?c=e.slice(6):Wy(e,"MPEGTS:")&&(f=parseInt(e.slice(7)))}));try{p=function(e){let t=parseInt(e.slice(-3)),i=parseInt(e.slice(-6,-4)),r=parseInt(e.slice(-9,-7)),s=e.length>9?parseInt(e.substring(0,e.indexOf(":"))):0;if(!(Kf(t)&&Kf(i)&&Kf(r)&&Kf(s)))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${e}`);return t+=1e3*i,t+=6e4*r,t+=36e5*s,t}(c)/1e3}catch(e){o=e}return}""===e&&(m=!1)}l.parse(e+"\n")})),l.flush()}var Xy="stpp.ttml.im1t",Qy=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,Zy=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,Jy={left:"start",center:"center",right:"end",start:"start",end:"end"};function eb(e,t,i,r){let s=om(new Uint8Array(e),["mdat"]);if(0===s.length)return void r(new Error("Could not parse IMSC1 mdat"));let n=s.map((e=>Xp(e))),a=function(e,t,i=1,r=!1){return GE(e,t,1/i,r)}(t.baseTime,1,t.timescale);try{n.forEach((e=>i(function(e,t){let i=(new DOMParser).parseFromString(e,"text/xml").getElementsByTagName("tt")[0];if(!i)throw new Error("Invalid ttml");let r={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:0},s=Object.keys(r).reduce(((e,t)=>(e[t]=i.getAttribute(`ttp:${t}`)||r[t],e)),{}),n="preserve"!==i.getAttribute("xml:space"),a=ib(tb(i,"styling","style")),o=ib(tb(i,"layout","region")),l=tb(i,"body","[begin]");return[].map.call(l,(e=>{let i=rb(e,n);if(!i||!e.hasAttribute("begin"))return null;let r=ab(e.getAttribute("begin"),s),l=ab(e.getAttribute("dur"),s),h=ab(e.getAttribute("end"),s);if(null===r)throw nb(e);if(null===h){if(null===l)throw nb(e);h=r+l}let d=new Oy(r-t,h-t,i);d.id=Yy(d.startTime,d.endTime,d.text);let u=function(e,t,i){let r="http://www.w3.org/ns/ttml#styling",s=null,n=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],a=null!=e&&e.hasAttribute("style")?e.getAttribute("style"):null;return a&&i.hasOwnProperty(a)&&(s=i[a]),n.reduce(((i,n)=>{let a=sb(t,r,n)||sb(e,r,n)||sb(s,r,n);return a&&(i[n]=a),i}),{})}(o[e.getAttribute("region")],a[e.getAttribute("style")],a),{textAlign:c}=u;if(c){let e=Jy[c];e&&(d.lineAlign=e),d.align=c}return Vf(d,u),d})).filter((e=>null!==e))}(e,a))))}catch(e){r(e)}}function tb(e,t,i){let r=e.getElementsByTagName(t)[0];return r?[].slice.call(r.querySelectorAll(i)):[]}function ib(e){return e.reduce(((e,t)=>{let i=t.getAttribute("xml:id");return i&&(e[i]=t),e}),{})}function rb(e,t){return[].slice.call(e.childNodes).reduce(((e,i,r)=>{var s;return"br"===i.nodeName&&r?e+"\n":null!=(s=i.childNodes)&&s.length?rb(i,t):t?e+i.textContent.trim().replace(/\s+/g," "):e+i.textContent}),"")}function sb(e,t,i){return e&&e.hasAttributeNS(t,i)?e.getAttributeNS(t,i):null}function nb(e){return new Error(`Could not parse ttml timestamp ${e}`)}function ab(e,t){if(!e)return null;let i=Ny(e);return null===i&&(Qy.test(e)?i=function(e,t){let i=Qy.exec(e),r=(0|i[4])+(0|i[5])/t.subFrameRate;return 3600*(0|i[1])+60*(0|i[2])+(0|i[3])+r/t.frameRate}(e,t):Zy.test(e)&&(i=function(e,t){let i=Zy.exec(e),r=Number(i[1]);switch(i[2]){case"h":return 3600*r;case"m":return 60*r;case"ms":return 1e3*r;case"f":return r/t.frameRate;case"t":return r/t.tickRate}return r}(e,t))),i}function ob(e){return e.characteristics&&/transcribes-spoken-dialog/gi.test(e.characteristics)&&/describes-music-and-sound/gi.test(e.characteristics)?"captions":"subtitles"}function lb(e,t){return!!e&&e.kind===ob(t)&&dy(t,e)}function hb(e,t,i,r){return Math.min(t,r)-Math.max(e,i)}var db="[eme]",ub=class e{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=e.CDMCleanupPromise?[e.CDMCleanupPromise]:[],this.onMediaEncrypted=this._onMediaEncrypted.bind(this),this.onWaitingForKey=this._onWaitingForKey.bind(this),this.debug=tp.debug.bind(tp,db),this.log=tp.log.bind(tp,db),this.warn=tp.warn.bind(tp,db),this.error=tp.error.bind(tp,db),this.hls=t,this.config=t.config,this.registerListeners()}destroy(){this.unregisterListeners(),this.onMediaDetached();let e=this.config;e.requestMediaKeySystemAccessFunc=null,e.licenseXhrSetup=e.licenseResponseCallback=void 0,e.drmSystems=e.drmSystemOptions={},this.hls=this.onMediaEncrypted=this.onWaitingForKey=this.keyIdToKeySessionPromise=null,this.config=null}registerListeners(){this.hls.on(Yf.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(Yf.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(Yf.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(Yf.MANIFEST_LOADED,this.onManifestLoaded,this)}unregisterListeners(){this.hls.off(Yf.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(Yf.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(Yf.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(Yf.MANIFEST_LOADED,this.onManifestLoaded,this)}getLicenseServerUrl(e){let{drmSystems:t,widevineLicenseUrl:i}=this.config,r=t[e];if(r)return r.licenseUrl;if(e===bp.WIDEVINE&&i)return i;throw new Error(`no license server URL configured for key-system "${e}"`)}getServerCertificateUrl(e){let{drmSystems:t}=this.config,i=t[e];if(i)return i.serverCertificateUrl;this.log(`No Server Certificate in config.drmSystems["${e}"]`)}attemptKeySystemAccess(e){let t=this.hls.levels,i=(e,t,i)=>!!e&&i.indexOf(e)===t,r=t.map((e=>e.audioCodec)).filter(i),s=t.map((e=>e.videoCodec)).filter(i);return r.length+s.length===0&&s.push("avc1.42e01e"),new Promise(((t,i)=>{let n=e=>{let a=e.shift();this.getMediaKeysPromise(a,r,s).then((e=>t({keySystem:a,mediaKeys:e}))).catch((t=>{e.length?n(e):i(t instanceof mb?t:new mb({type:zf.KEY_SYSTEM_ERROR,details:Xf.KEY_SYSTEM_NO_ACCESS,error:t,fatal:!0},t.message))}))};n(e)}))}requestMediaKeySystemAccess(e,t){let{requestMediaKeySystemAccessFunc:i}=this.config;if("function"!=typeof i){let e=`Configured requestMediaKeySystemAccess is not a function ${i}`;return null===Mp&&"http:"===self.location.protocol&&(e=`navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`),Promise.reject(new Error(e))}return i(e,t)}getMediaKeysPromise(e,t,i){let r=function(e,t,i,r){let s;switch(e){case bp.FAIRPLAY:s=["cenc","sinf"];break;case bp.WIDEVINE:case bp.PLAYREADY:s=["cenc"];break;case bp.CLEARKEY:s=["cenc","keyids"];break;default:throw new Error(`Unknown key-system: ${e}`)}return function(e,t,i,r){return[{initDataTypes:e,persistentState:r.persistentState||"optional",distinctiveIdentifier:r.distinctiveIdentifier||"optional",sessionTypes:r.sessionTypes||[r.sessionType||"temporary"],audioCapabilities:t.map((e=>({contentType:`audio/mp4; codecs="${e}"`,robustness:r.audioRobustness||"",encryptionScheme:r.audioEncryptionScheme||null}))),videoCapabilities:i.map((e=>({contentType:`video/mp4; codecs="${e}"`,robustness:r.videoRobustness||"",encryptionScheme:r.videoEncryptionScheme||null})))}]}(s,t,i,r)}(e,t,i,this.config.drmSystemOptions),s=this.keySystemAccessPromises[e],n=s?.keySystemAccess;if(!n){this.log(`Requesting encrypted media "${e}" key-system access with config: ${JSON.stringify(r)}`),n=this.requestMediaKeySystemAccess(e,r);let t=this.keySystemAccessPromises[e]={keySystemAccess:n};return n.catch((t=>{this.log(`Failed to obtain access to key-system "${e}": ${t}`)})),n.then((i=>{this.log(`Access for key-system "${i.keySystem}" obtained`);let r=this.fetchServerCertificate(e);return this.log(`Create media-keys for "${e}"`),t.mediaKeys=i.createMediaKeys().then((t=>(this.log(`Media-keys created for "${e}"`),r.then((i=>i?this.setMediaKeysServerCertificate(t,e,i):t))))),t.mediaKeys.catch((t=>{this.error(`Failed to create media-keys for "${e}"}: ${t}`)})),t.mediaKeys}))}return n.then((()=>s.mediaKeys))}createMediaKeySessionContext({decryptdata:e,keySystem:t,mediaKeys:i}){this.log(`Creating key-system session "${t}" keyId: ${Qp(e.keyId||[])}`);let r=i.createSession(),s={decryptdata:e,keySystem:t,mediaKeys:i,mediaKeysSession:r,keyStatus:"status-pending"};return this.mediaKeySessions.push(s),s}renewKeySession(e){let t=e.decryptdata;if(t.pssh){let i=this.createMediaKeySessionContext(e),r=this.getKeyIdString(t),s="cenc";this.keyIdToKeySessionPromise[r]=this.generateRequestWithPreferredKeySession(i,s,t.pssh,"expired")}else this.warn("Could not renew expired session. Missing pssh initData.");this.removeSession(e)}getKeyIdString(e){if(!e)throw new Error("Could not read keyId of undefined decryptdata");if(null===e.keyId)throw new Error("keyId is null");return Qp(e.keyId)}updateKeySession(e,t){var i;let r=e.mediaKeysSession;return this.log(`Updating key-session "${r.sessionId}" for keyID ${Qp((null==(i=e.decryptdata)?void 0:i.keyId)||[])}\n      } (data length: ${t&&t.byteLength})`),r.update(t)}selectKeySystemFormat(e){let t=Object.keys(e.levelkeys||{});return this.keyFormatPromise||(this.log(`Selecting key-system from fragment (sn: ${e.sn} ${e.type}: ${e.level}) key formats ${t.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(t)),this.keyFormatPromise}getKeyFormatPromise(e){return new Promise(((t,i)=>{let r=xp(this.config),s=e.map(wp).filter((e=>!!e&&-1!==r.indexOf(e)));return this.getKeySystemSelectionPromise(s).then((({keySystem:e})=>{let r=Dp(e);r?t(r):i(new Error(`Unable to find format for key-system "${e}"`))})).catch(i)}))}loadKey(e){let t=e.keyInfo.decryptdata,i=this.getKeyIdString(t),r=`(keyId: ${i} format: "${t.keyFormat}" method: ${t.method} uri: ${t.uri})`;this.log(`Starting session for key ${r}`);let s=this.keyIdToKeySessionPromise[i];return s||(s=this.keyIdToKeySessionPromise[i]=this.getKeySystemForKeyPromise(t).then((({keySystem:i,mediaKeys:s})=>(this.throwIfDestroyed(),this.log(`Handle encrypted media sn: ${e.frag.sn} ${e.frag.type}: ${e.frag.level} using key ${r}`),this.attemptSetMediaKeys(i,s).then((()=>{this.throwIfDestroyed();let e=this.createMediaKeySessionContext({keySystem:i,mediaKeys:s,decryptdata:t});return this.generateRequestWithPreferredKeySession(e,"cenc",t.pssh,"playlist-key")}))))),s.catch((e=>this.handleError(e)))),s}throwIfDestroyed(e="Invalid state"){if(!this.hls)throw new Error("invalid state")}handleError(e){this.hls&&(this.error(e.message),e instanceof mb?this.hls.trigger(Yf.ERROR,e.data):this.hls.trigger(Yf.ERROR,{type:zf.KEY_SYSTEM_ERROR,details:Xf.KEY_SYSTEM_NO_KEYS,error:e,fatal:!0}))}getKeySystemForKeyPromise(e){let t=this.getKeyIdString(e),i=this.keyIdToKeySessionPromise[t];if(!i){let t=wp(e.keyFormat),i=t?[t]:xp(this.config);return this.attemptKeySystemAccess(i)}return i}getKeySystemSelectionPromise(e){if(e.length||(e=xp(this.config)),0===e.length)throw new mb({type:zf.KEY_SYSTEM_ERROR,details:Xf.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${JSON.stringify({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(e)}_onMediaEncrypted(e){let t,i,{initDataType:r,initData:s}=e,n=`"${e.type}" event: init data type: "${r}"`;if(this.debug(n),null===s)return;if("sinf"===r&&this.config.drmSystems[bp.FAIRPLAY]){let e=tm(new Uint8Array(s));try{let r=gp(JSON.parse(e).sinf),s=pm(new Uint8Array(r));if(!s)throw new Error("'schm' box missing or not cbcs/cenc with schi > tenc");t=s.subarray(8,24),i=bp.FAIRPLAY}catch(e){return void this.warn(`${n} Failed to parse sinf: ${e}`)}}else{let e=function(e){let t=[];if(e instanceof ArrayBuffer){let i=e.byteLength,r=0;for(;r+32<i;){let i=Sm(new DataView(e,r));t.push(i),r+=i.size}}return t}(s),r=e.filter((e=>e.systemId===Ip))[0];if(!r)return void(0===e.length||e.some((e=>!e.systemId))?this.warn(`${n} contains incomplete or invalid pssh data`):this.log(`ignoring ${n} for ${e.map((e=>Cp(e.systemId))).join(",")} pssh data in favor of playlist keys`));if(i=Cp(r.systemId),0===r.version&&r.data){let e=r.data.length-22;t=r.data.subarray(e,e+16)}}if(!i||!t)return;let a=Qp(t),{keyIdToKeySessionPromise:o,mediaKeySessions:l}=this,h=o[a];for(let e=0;e<l.length;e++){let i=l[e],n=i.decryptdata;if(!n.keyId)continue;let d=Qp(n.keyId);if(a===d||-1!==n.uri.replace(/-/g,"").indexOf(a)){if(h=o[d],n.pssh)break;delete o[d],n.pssh=new Uint8Array(s),n.keyId=t,h=o[a]=h.then((()=>this.generateRequestWithPreferredKeySession(i,r,s,"encrypted-event-key-match")));break}}h||(h=o[a]=this.getKeySystemSelectionPromise([i]).then((({keySystem:e,mediaKeys:i})=>{var n;this.throwIfDestroyed();let o=new _m("ISO-23001-7",a,null!=(n=Dp(e))?n:"");return o.pssh=new Uint8Array(s),o.keyId=t,this.attemptSetMediaKeys(e,i).then((()=>{this.throwIfDestroyed();let t=this.createMediaKeySessionContext({decryptdata:o,keySystem:e,mediaKeys:i});return this.generateRequestWithPreferredKeySession(t,r,s,"encrypted-event-no-match")}))}))),h.catch((e=>this.handleError(e)))}_onWaitingForKey(e){this.log(`"${e.type}" event`)}attemptSetMediaKeys(e,t){let i=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${e}"`);let r=Promise.all(i).then((()=>{if(!this.media)throw new Error("Attempted to set mediaKeys without media element attached");return this.media.setMediaKeys(t)}));return this.setMediaKeysQueue.push(r),r.then((()=>{this.log(`Media-keys set for "${e}"`),i.push(r),this.setMediaKeysQueue=this.setMediaKeysQueue.filter((e=>-1===i.indexOf(e)))}))}generateRequestWithPreferredKeySession(e,t,i,r){var s,n;let a=null==(s=this.config.drmSystems)||null==(n=s[e.keySystem])?void 0:n.generateRequest;if(a)try{let r=a.call(this.hls,t,i,e);if(!r)throw new Error("Invalid response from configured generateRequest filter");t=r.initDataType,i=e.decryptdata.pssh=r.initData?new Uint8Array(r.initData):null}catch(e){var o;if(this.warn(e.message),null!=(o=this.hls)&&o.config.debug)throw e}if(null===i)return this.log(`Skipping key-session request for "${r}" (no initData)`),Promise.resolve(e);let l=this.getKeyIdString(e.decryptdata);this.log(`Generating key-session request for "${r}": ${l} (init data type: ${t} length: ${i?i.byteLength:null})`);let h=new ay,d=e._onmessage=t=>{let i=e.mediaKeysSession;if(!i)return void h.emit("error",new Error("invalid state"));let{messageType:r,message:s}=t;this.log(`"${r}" message event for session "${i.sessionId}" message size: ${s.byteLength}`),"license-request"===r||"license-renewal"===r?this.renewLicense(e,s).catch((e=>{this.handleError(e),h.emit("error",e)})):"license-release"===r?e.keySystem===bp.FAIRPLAY&&(this.updateKeySession(e,Ep("acknowledged")),this.removeSession(e)):this.warn(`unhandled media key message type "${r}"`)},u=e._onkeystatuseschange=t=>{if(!e.mediaKeysSession)return void h.emit("error",new Error("invalid state"));this.onKeyStatusChange(e);let i=e.keyStatus;h.emit("keyStatus",i),"expired"===i&&(this.warn(`${e.keySystem} expired for key ${l}`),this.renewKeySession(e))};e.mediaKeysSession.addEventListener("message",d),e.mediaKeysSession.addEventListener("keystatuseschange",u);let c=new Promise(((e,t)=>{h.on("error",t),h.on("keyStatus",(i=>{i.startsWith("usable")?e():"output-restricted"===i?t(new mb({type:zf.KEY_SYSTEM_ERROR,details:Xf.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED,fatal:!1},"HDCP level output restricted")):"internal-error"===i?t(new mb({type:zf.KEY_SYSTEM_ERROR,details:Xf.KEY_SYSTEM_STATUS_INTERNAL_ERROR,fatal:!0},`key status changed to "${i}"`)):"expired"===i?t(new Error("key expired while generating request")):this.warn(`unhandled key status change "${i}"`)}))}));return e.mediaKeysSession.generateRequest(t,i).then((()=>{var t;this.log(`Request generated for key-session "${null==(t=e.mediaKeysSession)?void 0:t.sessionId}" keyId: ${l}`)})).catch((e=>{throw new mb({type:zf.KEY_SYSTEM_ERROR,details:Xf.KEY_SYSTEM_NO_SESSION,error:e,fatal:!1},`Error generating key-session request: ${e}`)})).then((()=>c)).catch((t=>{throw h.removeAllListeners(),this.removeSession(e),t})).then((()=>(h.removeAllListeners(),e)))}onKeyStatusChange(e){e.mediaKeysSession.keyStatuses.forEach(((t,i)=>{this.log(`key status change "${t}" for keyStatuses keyId: ${Qp("buffer"in i?new Uint8Array(i.buffer,i.byteOffset,i.byteLength):new Uint8Array(i))} session keyId: ${Qp(new Uint8Array(e.decryptdata.keyId||[]))} uri: ${e.decryptdata.uri}`),e.keyStatus=t}))}fetchServerCertificate(e){let t=this.config,i=new(0,t.loader)(t),r=this.getServerCertificateUrl(e);return r?(this.log(`Fetching server certificate for "${e}"`),new Promise(((s,n)=>{let a={responseType:"arraybuffer",url:r},o=t.certLoadPolicy.default,l={loadPolicy:o,timeout:o.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},h={onSuccess:(e,t,i,r)=>{s(e.data)},onError:(t,i,s,o)=>{n(new mb({type:zf.KEY_SYSTEM_ERROR,details:Xf.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:s,response:Hf({url:a.url,data:void 0},t)},`"${e}" certificate request failed (${r}). Status: ${t.code} (${t.text})`))},onTimeout:(t,i,s)=>{n(new mb({type:zf.KEY_SYSTEM_ERROR,details:Xf.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:s,response:{url:a.url,data:void 0}},`"${e}" certificate request timed out (${r})`))},onAbort:(e,t,i)=>{n(new Error("aborted"))}};i.load(a,l,h)}))):Promise.resolve()}setMediaKeysServerCertificate(e,t,i){return new Promise(((r,s)=>{e.setServerCertificate(i).then((s=>{this.log(`setServerCertificate ${s?"success":"not supported by CDM"} (${i?.byteLength}) on "${t}"`),r(e)})).catch((e=>{s(new mb({type:zf.KEY_SYSTEM_ERROR,details:Xf.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:e,fatal:!0},e.message))}))}))}renewLicense(e,t){return this.requestLicense(e,new Uint8Array(t)).then((t=>this.updateKeySession(e,new Uint8Array(t)).catch((e=>{throw new mb({type:zf.KEY_SYSTEM_ERROR,details:Xf.KEY_SYSTEM_SESSION_UPDATE_FAILED,error:e,fatal:!0},e.message)}))))}unpackPlayReadyKeyMessage(e,t){let i=String.fromCharCode.apply(null,new Uint16Array(t.buffer));if(!i.includes("PlayReadyKeyMessage"))return e.setRequestHeader("Content-Type","text/xml; charset=utf-8"),t;let r=(new DOMParser).parseFromString(i,"application/xml"),s=r.querySelectorAll("HttpHeader");if(s.length>0){let t;for(let i=0,r=s.length;i<r;i++){var n,a;t=s[i];let r=null==(n=t.querySelector("name"))?void 0:n.textContent,o=null==(a=t.querySelector("value"))?void 0:a.textContent;r&&o&&e.setRequestHeader(r,o)}}let o=r.querySelector("Challenge"),l=o?.textContent;if(!l)throw new Error("Cannot find <Challenge> in key message");return Ep(atob(l))}setupLicenseXHR(e,t,i,r){let s=this.config.licenseXhrSetup;return s?Promise.resolve().then((()=>{if(!i.decryptdata)throw new Error("Key removed");return s.call(this.hls,e,t,i,r)})).catch((n=>{if(!i.decryptdata)throw n;return e.open("POST",t,!0),s.call(this.hls,e,t,i,r)})).then((i=>(e.readyState||e.open("POST",t,!0),{xhr:e,licenseChallenge:i||r}))):(e.open("POST",t,!0),Promise.resolve({xhr:e,licenseChallenge:r}))}requestLicense(e,t){let i=this.config.keyLoadPolicy.default;return new Promise(((r,s)=>{let n=this.getLicenseServerUrl(e.keySystem);this.log(`Sending license request to URL: ${n}`);let a=new XMLHttpRequest;a.responseType="arraybuffer",a.onreadystatechange=()=>{if(!this.hls||!e.mediaKeysSession)return s(new Error("invalid state"));if(4===a.readyState)if(200===a.status){this._requestLicenseFailureCount=0;let t=a.response;this.log(`License received ${t instanceof ArrayBuffer?t.byteLength:t}`);let i=this.config.licenseResponseCallback;if(i)try{t=i.call(this.hls,a,n,e)}catch(e){this.error(e)}r(t)}else{let o=i.errorRetry,l=o?o.maxNumRetry:0;if(this._requestLicenseFailureCount++,this._requestLicenseFailureCount>l||a.status>=400&&a.status<500)s(new mb({type:zf.KEY_SYSTEM_ERROR,details:Xf.KEY_SYSTEM_LICENSE_REQUEST_FAILED,fatal:!0,networkDetails:a,response:{url:n,data:void 0,code:a.status,text:a.statusText}},`License Request XHR failed (${n}). Status: ${a.status} (${a.statusText})`));else{let i=l-this._requestLicenseFailureCount+1;this.warn(`Retrying license request, ${i} attempts left`),this.requestLicense(e,t).then(r,s)}}},e.licenseXhr&&e.licenseXhr.readyState!==XMLHttpRequest.DONE&&e.licenseXhr.abort(),e.licenseXhr=a,this.setupLicenseXHR(a,n,e,t).then((({xhr:t,licenseChallenge:i})=>{e.keySystem==bp.PLAYREADY&&(i=this.unpackPlayReadyKeyMessage(t,i)),t.send(i)}))}))}onMediaAttached(e,t){if(!this.config.emeEnabled)return;let i=t.media;this.media=i,i.addEventListener("encrypted",this.onMediaEncrypted),i.addEventListener("waitingforkey",this.onWaitingForKey)}onMediaDetached(){let t=this.media,i=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={},_m.clearKeyUriToKeyIdMap();let r=i.length;e.CDMCleanupPromise=Promise.all(i.map((e=>this.removeSession(e))).concat(t?.setMediaKeys(null).catch((e=>{this.log(`Could not clear media keys: ${e}`)})))).then((()=>{r&&(this.log("finished closing key sessions and clearing media keys"),i.length=0)})).catch((e=>{this.log(`Could not close sessions and clear media keys: ${e}`)}))}onManifestLoading(){this.keyFormatPromise=null}onManifestLoaded(e,{sessionKeys:t}){if(t&&this.config.emeEnabled&&!this.keyFormatPromise){let e=t.reduce(((e,t)=>(-1===e.indexOf(t.keyFormat)&&e.push(t.keyFormat),e)),[]);this.log(`Selecting key-system from session-keys ${e.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(e)}}removeSession(e){let{mediaKeysSession:t,licenseXhr:i}=e;if(t){this.log(`Remove licenses and keys and close session ${t.sessionId}`),e._onmessage&&(t.removeEventListener("message",e._onmessage),e._onmessage=void 0),e._onkeystatuseschange&&(t.removeEventListener("keystatuseschange",e._onkeystatuseschange),e._onkeystatuseschange=void 0),i&&i.readyState!==XMLHttpRequest.DONE&&i.abort(),e.mediaKeysSession=e.decryptdata=e.licenseXhr=void 0;let r=this.mediaKeySessions.indexOf(e);return r>-1&&this.mediaKeySessions.splice(r,1),t.remove().catch((e=>{this.log(`Could not remove session: ${e}`)})).then((()=>t.close())).catch((e=>{this.log(`Could not close session: ${e}`)}))}}};ub.CDMCleanupPromise=void 0;var cb,fb,pb,mb=class extends Error{constructor(e,t){super(t),this.data=void 0,e.error||(e.error=new Error(t)),this.data=e,e.err=e.error}};!function(e){e.MANIFEST="m",e.AUDIO="a",e.VIDEO="v",e.MUXED="av",e.INIT="i",e.CAPTION="c",e.TIMED_TEXT="tt",e.KEY="k",e.OTHER="o"}(cb||(cb={})),function(e){e.DASH="d",e.HLS="h",e.SMOOTH="s",e.OTHER="o"}(fb||(fb={})),function(e){e.OBJECT="CMCD-Object",e.REQUEST="CMCD-Request",e.SESSION="CMCD-Session",e.STATUS="CMCD-Status"}(pb||(pb={}));var gb={[pb.OBJECT]:["br","d","ot","tb"],[pb.REQUEST]:["bl","dl","mtp","nor","nrr","su"],[pb.SESSION]:["cid","pr","sf","sid","st","v"],[pb.STATUS]:["bs","rtp"]},vb=class e{constructor(t,i){this.value=void 0,this.params=void 0,Array.isArray(t)&&(t=t.map((t=>t instanceof e?t:new e(t)))),this.value=t,this.params=i}},Eb=class{constructor(e){this.description=void 0,this.description=e}};function yb(e,t,i,r){return new Error(`failed to ${e} "${function(e){return Array.isArray(e)?JSON.stringify(e):e instanceof Map?"Map{}":e instanceof Set?"Set{}":"object"==typeof e?JSON.stringify(e):String(e)}(t)}" as ${i}`,{cause:r})}var bb="Bare Item";var Tb=/[\x00-\x1f\x7f]+/;function Sb(e,t,i){return yb("serialize",e,t,i)}function Ab(e){if(!1===ArrayBuffer.isView(e))throw Sb(e,"Byte Sequence");return`:${function(e){return btoa(String.fromCharCode(...e))}(e)}:`}function _b(e){if(function(e){return e<-999999999999999||999999999999999<e}(e))throw Sb(e,"Integer");return e.toString()}function wb(e,t){if(e<0)return-wb(-e,t);let i=Math.pow(10,t);if(Math.abs(e*i%1-.5)<Number.EPSILON){let t=Math.floor(e*i);return(t%2==0?t:t+1)/i}return Math.round(e*i)/i}function kb(e){let t=wb(e,3);if(Math.floor(Math.abs(t)).toString().length>12)throw Sb(e,"Decimal");let i=t.toString();return i.includes(".")?i:`${i}.0`}function Lb(e){let t=function(e){return e.description||e.toString().slice(7,-1)}(e);if(!1===/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(t))throw Sb(t,"Token");return t}function Rb(e){switch(typeof e){case"number":if(!Kf(e))throw Sb(e,bb);return Number.isInteger(e)?_b(e):kb(e);case"string":return function(e){if(Tb.test(e))throw Sb(e,"String");return`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}(e);case"symbol":return Lb(e);case"boolean":return function(e){if("boolean"!=typeof e)throw Sb(e,"Boolean");return e?"?1":"?0"}(e);case"object":if(e instanceof Date)return function(e){return`@${_b(e.getTime()/1e3)}`}(e);if(e instanceof Uint8Array)return Ab(e);if(e instanceof Eb)return Lb(e);default:throw Sb(e,bb)}}function Ib(e){if(!1===/^[a-z*][a-z0-9\-_.*]*$/.test(e))throw Sb(e,"Key");return e}function Cb(e){return null==e?"":Object.entries(e).map((([e,t])=>!0===t?`;${Ib(e)}`:`;${Ib(e)}=${Rb(t)}`)).join("")}function Db(e){return e instanceof vb?`${Rb(e.value)}${Cb(e.params)}`:Rb(e)}function xb(e,t={whitespace:!0}){if("object"!=typeof e)throw Sb(e,"Dict");let i=e instanceof Map?e.entries():Object.entries(e),r=null!=t&&t.whitespace?" ":"";return Array.from(i).map((([e,t])=>{t instanceof vb||(t=new vb(t));let i=Ib(e);return!0===t.value?i+=Cb(t.params):(i+="=",Array.isArray(t.value)?i+=function(e){return`(${e.value.map(Db).join(" ")})${Cb(e.params)}`}(t):i+=Db(t)),i})).join(`,${r}`)}var Mb=e=>Math.round(e),Pb=e=>100*Mb(e/100),Ob={br:Mb,d:Mb,bl:Pb,dl:Pb,mtp:Pb,nor:(e,t)=>(null!=t&&t.baseUrl&&(e=function(e,t){let i=new URL(e),r=new URL(t);if(i.origin!==r.origin)return e;let s=i.pathname.split("/").slice(1),n=r.pathname.split("/").slice(1,-1);for(;s[0]===n[0];)s.shift(),n.shift();for(;n.length;)n.shift(),s.unshift("..");return s.join("/")}(e,t.baseUrl)),encodeURIComponent(e)),rtp:Pb,tb:Mb};function Ub(e,t){let i={};if(null==e||"object"!=typeof e)return i;let r=Object.keys(e).sort(),s=Vf({},Ob,t?.formatters),n=t?.filter;return r.forEach((r=>{if(null!=n&&n(r))return;let a=e[r],o=s[r];o&&(a=o(a,t)),("v"!==r||1!==a)&&("pr"==r&&1===a||(e=>"number"==typeof e?Kf(e):null!=e&&""!==e&&!1!==e)(a)&&((e=>"ot"===e||"sf"===e||"st"===e)(r)&&"string"==typeof a&&(a=new Eb(a)),i[r]=a))})),i}function Nb(e,t={}){return e?function(e,t){return xb(e,t)}(Ub(e,t),Vf({whitespace:!1},t)):""}function $b(e,t,i){return Vf(e,function(e,t={}){if(!e)return{};let i=Object.entries(e),r=Object.entries(gb).concat(Object.entries(t?.customHeaderMap||{})),s=i.reduce(((e,t)=>{var i;let[s,n]=t,a=(null==(i=r.find((e=>e[1].includes(s))))?void 0:i[0])||pb.REQUEST;return null!=e[a]||(e[a]={}),e[a][s]=n,e}),{});return Object.entries(s).reduce(((e,[i,r])=>(e[i]=Nb(r,t),e)),{})}(t,i))}var Fb=/CMCD=[^&#]+/;function Bb(e,t,i){let r=function(e,t={}){if(!e)return"";let i=Nb(e,t);return`CMCD=${encodeURIComponent(i)}`}(t,i);if(!r)return e;if(Fb.test(e))return e.replace(Fb,r);let s=e.includes("?")?"&":"?";return`${e}${s}${r}`}function Hb(e,t,i,r){e&&Object.keys(t).forEach((s=>{let n=e.filter((e=>e.groupId===s)).map((e=>{let n=Vf({},e);return n.details=void 0,n.attrs=new sp(n.attrs),n.url=n.attrs.URI=Gb(e.url,e.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",i),n.groupId=n.attrs["GROUP-ID"]=t[s],n.attrs["PATHWAY-ID"]=r,n}));e.push(...n)}))}function Gb(e,t,i,r){let s,{HOST:n,PARAMS:a,[i]:o}=r;t&&(s=o?.[t],s&&(e=s));let l=new self.URL(e);return n&&!s&&(l.host=n),a&&Object.keys(a).sort().forEach((e=>{e&&l.searchParams.set(e,a[e])})),l.href}var jb=/^age:\s*[\d.]+\s*$/im,Vb=class{constructor(e){this.xhrSetup=void 0,this.requestTimeout=void 0,this.retryTimeout=void 0,this.retryDelay=void 0,this.config=null,this.callbacks=null,this.context=null,this.loader=null,this.stats=void 0,this.xhrSetup=e&&e.xhrSetup||null,this.stats=new lp,this.retryDelay=0}destroy(){this.callbacks=null,this.abortInternal(),this.loader=null,this.config=null,this.context=null,this.xhrSetup=null}abortInternal(){let e=this.loader;self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),e&&(e.onreadystatechange=null,e.onprogress=null,4!==e.readyState&&(this.stats.aborted=!0,e.abort()))}abort(){var e;this.abortInternal(),null!=(e=this.callbacks)&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.loader)}load(e,t,i){if(this.stats.loading.start)throw new Error("Loader can only be used once.");this.stats.loading.start=self.performance.now(),this.context=e,this.config=t,this.callbacks=i,this.loadInternal()}loadInternal(){let{config:e,context:t}=this;if(!e||!t)return;let i=this.loader=new self.XMLHttpRequest,r=this.stats;r.loading.first=0,r.loaded=0,r.aborted=!1;let s=this.xhrSetup;s?Promise.resolve().then((()=>{if(this.loader===i&&!this.stats.aborted)return s(i,t.url)})).catch((e=>{if(this.loader===i&&!this.stats.aborted)return i.open("GET",t.url,!0),s(i,t.url)})).then((()=>{this.loader!==i||this.stats.aborted||this.openAndSendXhr(i,t,e)})).catch((e=>{this.callbacks.onError({code:i.status,text:e.message},t,i,r)})):this.openAndSendXhr(i,t,e)}openAndSendXhr(e,t,i){e.readyState||e.open("GET",t.url,!0);let r=t.headers,{maxTimeToFirstByteMs:s,maxLoadTimeMs:n}=i.loadPolicy;if(r)for(let t in r)e.setRequestHeader(t,r[t]);t.rangeEnd&&e.setRequestHeader("Range","bytes="+t.rangeStart+"-"+(t.rangeEnd-1)),e.onreadystatechange=this.readystatechange.bind(this),e.onprogress=this.loadprogress.bind(this),e.responseType=t.responseType,self.clearTimeout(this.requestTimeout),i.timeout=s&&Kf(s)?s:n,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),i.timeout),e.send()}readystatechange(){let{context:e,loader:t,stats:i}=this;if(!e||!t)return;let r=t.readyState,s=this.config;if(!i.aborted&&r>=2&&(0===i.loading.first&&(i.loading.first=Math.max(self.performance.now(),i.loading.start),s.timeout!==s.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),s.timeout=s.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),s.loadPolicy.maxLoadTimeMs-(i.loading.first-i.loading.start)))),4===r)){self.clearTimeout(this.requestTimeout),t.onreadystatechange=null,t.onprogress=null;let r=t.status,n="text"!==t.responseType;if(r>=200&&r<300&&(n&&t.response||null!==t.responseText)){i.loading.end=Math.max(self.performance.now(),i.loading.first);let s=n?t.response:t.responseText,a="arraybuffer"===t.responseType?s.byteLength:s.length;if(i.loaded=i.total=a,i.bwEstimate=8e3*i.total/(i.loading.end-i.loading.first),!this.callbacks)return;let o=this.callbacks.onProgress;if(o&&o(i,e,s,t),!this.callbacks)return;let l={url:t.responseURL,data:s,code:r};this.callbacks.onSuccess(l,i,e,t)}else{let n=s.loadPolicy.errorRetry;qg(n,i.retry,!1,{url:e.url,data:void 0,code:r})?this.retry(n):(tp.error(`${r} while loading ${e.url}`),this.callbacks.onError({code:r,text:t.statusText},e,t,i))}}}loadtimeout(){if(!this.config)return;let e=this.config.loadPolicy.timeoutRetry;if(qg(e,this.stats.retry,!0))this.retry(e);else{var t;tp.warn(`timeout while loading ${null==(t=this.context)?void 0:t.url}`);let e=this.callbacks;e&&(this.abortInternal(),e.onTimeout(this.stats,this.context,this.loader))}}retry(e){let{context:t,stats:i}=this;this.retryDelay=Kg(e,i.retry),i.retry++,tp.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${t?.url}, retrying ${i.retry}/${e.maxNumRetry} in ${this.retryDelay}ms`),this.abortInternal(),this.loader=null,self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(this.loadInternal.bind(this),this.retryDelay)}loadprogress(e){let t=this.stats;t.loaded=e.loaded,e.lengthComputable&&(t.total=e.total)}getCacheAge(){let e=null;if(this.loader&&jb.test(this.loader.getAllResponseHeaders())){let t=this.loader.getResponseHeader("age");e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.loader&&new RegExp(`^${e}:\\s*[\\d.]+\\s*$`,"im").test(this.loader.getAllResponseHeaders())?this.loader.getResponseHeader(e):null}};var Kb=/(\d+)-(\d+)\/(\d+)/,Wb=class{constructor(e){this.fetchSetup=void 0,this.requestTimeout=void 0,this.request=null,this.response=null,this.controller=void 0,this.context=null,this.config=null,this.callbacks=null,this.stats=void 0,this.loader=null,this.fetchSetup=e.fetchSetup||qb,this.controller=new self.AbortController,this.stats=new lp}destroy(){this.loader=this.callbacks=this.context=this.config=this.request=null,this.abortInternal(),this.response=null,this.fetchSetup=this.controller=this.stats=null}abortInternal(){this.controller&&!this.stats.loading.end&&(this.stats.aborted=!0,this.controller.abort())}abort(){var e;this.abortInternal(),null!=(e=this.callbacks)&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.response)}load(e,t,i){let r=this.stats;if(r.loading.start)throw new Error("Loader can only be used once.");r.loading.start=self.performance.now();let s=function(e,t){let i={method:"GET",mode:"cors",credentials:"same-origin",signal:t,headers:new self.Headers(Vf({},e.headers))};return e.rangeEnd&&i.headers.set("Range","bytes="+e.rangeStart+"-"+String(e.rangeEnd-1)),i}(e,this.controller.signal),n=i.onProgress,a="arraybuffer"===e.responseType,o=a?"byteLength":"length",{maxTimeToFirstByteMs:l,maxLoadTimeMs:h}=t.loadPolicy;this.context=e,this.config=t,this.callbacks=i,this.request=this.fetchSetup(e,s),self.clearTimeout(this.requestTimeout),t.timeout=l&&Kf(l)?l:h,this.requestTimeout=self.setTimeout((()=>{this.abortInternal(),i.onTimeout(r,e,this.response)}),t.timeout),self.fetch(this.request).then((s=>{this.response=this.loader=s;let o=Math.max(self.performance.now(),r.loading.start);if(self.clearTimeout(this.requestTimeout),t.timeout=h,this.requestTimeout=self.setTimeout((()=>{this.abortInternal(),i.onTimeout(r,e,this.response)}),h-(o-r.loading.start)),!s.ok){let{status:e,statusText:t}=s;throw new Yb(t||"fetch, bad network response",e,s)}return r.loading.first=o,r.total=function(e){let t=e.get("Content-Range");if(t){let e=function(e){let t=Kb.exec(e);if(t)return parseInt(t[2])-parseInt(t[1])+1}(t);if(Kf(e))return e}let i=e.get("Content-Length");if(i)return parseInt(i)}(s.headers)||r.total,n&&Kf(t.highWaterMark)?this.loadProgressively(s,r,e,t.highWaterMark,n):a?s.arrayBuffer():"json"===e.responseType?s.json():s.text()})).then((s=>{let a=this.response;if(!a)throw new Error("loader destroyed");self.clearTimeout(this.requestTimeout),r.loading.end=Math.max(self.performance.now(),r.loading.first);let l=s[o];l&&(r.loaded=r.total=l);let h={url:a.url,data:s,code:a.status};n&&!Kf(t.highWaterMark)&&n(r,e,s,a),i.onSuccess(h,r,e,a)})).catch((t=>{if(self.clearTimeout(this.requestTimeout),r.aborted)return;let s=t&&t.code||0,n=t?t.message:null;i.onError({code:s,text:n},e,t?t.details:null,r)}))}getCacheAge(){let e=null;if(this.response){let t=this.response.headers.get("age");e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.response?this.response.headers.get(e):null}loadProgressively(e,t,i,r=0,s){let n=new rE,a=e.body.getReader(),o=()=>a.read().then((a=>{if(a.done)return n.dataLength&&s(t,i,n.flush(),e),Promise.resolve(new ArrayBuffer(0));let l=a.value,h=l.length;return t.loaded+=h,h<r||n.dataLength?(n.push(l),n.dataLength>=r&&s(t,i,n.flush(),e)):s(t,i,l,e),o()})).catch((()=>Promise.reject()));return o()}};function qb(e,t){return new self.Request(e.url,t)}var Yb=class extends Error{constructor(e,t,i){super(e),this.code=void 0,this.details=void 0,this.code=t,this.details=i}},zb=/\s/,Xb={newCue(e,t,i,r){let s,n,a,o,l,h=[],d=self.VTTCue||self.TextTrackCue;for(let c=0;c<r.rows.length;c++)if(s=r.rows[c],a=!0,o=0,l="",!s.isEmpty()){var u;for(let e=0;e<s.chars.length;e++)zb.test(s.chars[e].uchar)&&a?o++:(l+=s.chars[e].uchar,a=!1);s.cueStartTime=t,t===i&&(i+=1e-4),o>=16?o--:o++;let r=jy(l.trim()),f=Yy(t,i,r);null!=e&&null!=(u=e.cues)&&u.getCueById(f)||(n=new d(t,i,r),n.id=f,n.line=c+1,n.align="left",n.position=10+Math.min(80,10*Math.floor(8*o/32)),h.push(n))}return e&&h.length&&(h.sort(((e,t)=>"auto"===e.line||"auto"===t.line?0:e.line>8&&t.line>8?t.line-e.line:e.line-t.line)),h.forEach((t=>cg(e,t)))),h}},Qb=Hf(Hf({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,preferManagedMediaSource:!0,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,frontBufferFlushThreshold:1/0,maxBufferSize:6e7,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:Vb,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:class{constructor(e){this.hls=void 0,this.lastLevelLoadSec=0,this.lastLoadedFragLevel=-1,this.firstSelection=-1,this._nextAutoLevel=-1,this.nextAutoLevelKey="",this.audioTracksByGroup=null,this.codecTiers=null,this.timer=-1,this.fragCurrent=null,this.partCurrent=null,this.bitrateTestDelay=0,this.bwEstimator=void 0,this._abandonRulesCheck=()=>{let{fragCurrent:e,partCurrent:t,hls:i}=this,{autoLevelEnabled:r,media:s}=i;if(!e||!s)return;let n=performance.now(),a=t?t.stats:e.stats,o=t?t.duration:e.duration,l=n-a.loading.start,h=i.minAutoLevel;if(a.aborted||a.loaded&&a.loaded===a.total||e.level<=h)return this.clearTimer(),void(this._nextAutoLevel=-1);if(!r||s.paused||!s.playbackRate||!s.readyState)return;let d=i.mainForwardBufferInfo;if(null===d)return;let u=this.bwEstimator.getEstimateTTFB(),c=Math.abs(s.playbackRate);if(l<=Math.max(u,o/(2*c)*1e3))return;let f=d.len/c,p=a.loading.first?a.loading.first-a.loading.start:-1,m=a.loaded&&p>-1,g=this.getBwEstimate(),v=i.levels,E=v[e.level],y=a.total||Math.max(a.loaded,Math.round(o*E.averageBitrate/8)),b=m?l-p:l;b<1&&m&&(b=Math.min(l,8*a.loaded/g));let T=m?1e3*a.loaded/b:0,S=T?(y-a.loaded)/T:8*y/g+u/1e3;if(S<=f)return;let A,_=T?8*T:g,w=Number.POSITIVE_INFINITY;for(A=e.level-1;A>h;A--){let e=v[A].maxBitrate;if(w=this.getTimeToLoadFrag(u/1e3,_,o*e,!v[A].details),w<f)break}if(w>=S||w>10*o)return;i.nextLoadLevel=i.nextAutoLevel=A,m?this.bwEstimator.sample(l-Math.min(u,p),a.loaded):this.bwEstimator.sampleTTFB(l);let k=v[A].maxBitrate;this.getBwEstimate()*this.hls.config.abrBandWidthUpFactor>k&&this.resetEstimator(k),this.clearTimer(),tp.warn(`[abr] Fragment ${e.sn}${t?" part "+t.index:""} of level ${e.level} is loading too slowly;\n      Time to underbuffer: ${f.toFixed(3)} s\n      Estimated load time for current fragment: ${S.toFixed(3)} s\n      Estimated load time for down switch fragment: ${w.toFixed(3)} s\n      TTFB estimate: ${0|p} ms\n      Current BW estimate: ${Kf(g)?0|g:"Unknown"} bps\n      New BW estimate: ${0|this.getBwEstimate()} bps\n      Switching to level ${A} @ ${0|k} bps`),i.trigger(Yf.FRAG_LOAD_EMERGENCY_ABORTED,{frag:e,part:t,stats:a})},this.hls=e,this.bwEstimator=this.initEstimator(),this.registerListeners()}resetEstimator(e){e&&(tp.log(`setting initial bwe to ${e}`),this.hls.config.abrEwmaDefaultEstimate=e),this.firstSelection=-1,this.bwEstimator=this.initEstimator()}initEstimator(){let e=this.hls.config;return new ov(e.abrEwmaSlowVoD,e.abrEwmaFastVoD,e.abrEwmaDefaultEstimate)}registerListeners(){let{hls:e}=this;e.on(Yf.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Yf.FRAG_LOADING,this.onFragLoading,this),e.on(Yf.FRAG_LOADED,this.onFragLoaded,this),e.on(Yf.FRAG_BUFFERED,this.onFragBuffered,this),e.on(Yf.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(Yf.LEVEL_LOADED,this.onLevelLoaded,this),e.on(Yf.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(Yf.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.on(Yf.ERROR,this.onError,this)}unregisterListeners(){let{hls:e}=this;e&&(e.off(Yf.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Yf.FRAG_LOADING,this.onFragLoading,this),e.off(Yf.FRAG_LOADED,this.onFragLoaded,this),e.off(Yf.FRAG_BUFFERED,this.onFragBuffered,this),e.off(Yf.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(Yf.LEVEL_LOADED,this.onLevelLoaded,this),e.off(Yf.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(Yf.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.off(Yf.ERROR,this.onError,this))}destroy(){this.unregisterListeners(),this.clearTimer(),this.hls=this._abandonRulesCheck=null,this.fragCurrent=this.partCurrent=null}onManifestLoading(e,t){this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.lastLevelLoadSec=0,this.fragCurrent=this.partCurrent=null,this.onLevelsUpdated(),this.clearTimer()}onLevelsUpdated(){this.lastLoadedFragLevel>-1&&this.fragCurrent&&(this.lastLoadedFragLevel=this.fragCurrent.level),this._nextAutoLevel=-1,this.onMaxAutoLevelUpdated(),this.codecTiers=null,this.audioTracksByGroup=null}onMaxAutoLevelUpdated(){this.firstSelection=-1,this.nextAutoLevelKey=""}onFragLoading(e,t){let i=t.frag;if(!this.ignoreFragment(i)){var r;if(!i.bitrateTest)this.fragCurrent=i,this.partCurrent=null!=(r=t.part)?r:null;this.clearTimer(),this.timer=self.setInterval(this._abandonRulesCheck,100)}}onLevelSwitching(e,t){this.clearTimer()}onError(e,t){if(!t.fatal)switch(t.details){case Xf.BUFFER_ADD_CODEC_ERROR:case Xf.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case Xf.FRAG_LOAD_TIMEOUT:{let e=t.frag,{fragCurrent:i,partCurrent:r}=this;if(e&&i&&e.sn===i.sn&&e.level===i.level){let t=performance.now(),i=r?r.stats:e.stats,s=t-i.loading.start,n=i.loading.first?i.loading.first-i.loading.start:-1;if(i.loaded&&n>-1){let e=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(s-Math.min(e,n),i.loaded)}else this.bwEstimator.sampleTTFB(s)}break}}}getTimeToLoadFrag(e,t,i,r){return e+i/t+(r?this.lastLevelLoadSec:0)}onLevelLoaded(e,t){let i=this.hls.config,{loading:r}=t.stats,s=r.end-r.start;Kf(s)&&(this.lastLevelLoadSec=s/1e3),t.details.live?this.bwEstimator.update(i.abrEwmaSlowLive,i.abrEwmaFastLive):this.bwEstimator.update(i.abrEwmaSlowVoD,i.abrEwmaFastVoD)}onFragLoaded(e,{frag:t,part:i}){let r=i?i.stats:t.stats;if(t.type===ng&&this.bwEstimator.sampleTTFB(r.loading.first-r.loading.start),!this.ignoreFragment(t)){if(this.clearTimer(),t.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,this.hls.config.abrMaxWithRealBitrate){let e=i?i.duration:t.duration,s=this.hls.levels[t.level],n=(s.loaded?s.loaded.bytes:0)+r.loaded,a=(s.loaded?s.loaded.duration:0)+e;s.loaded={bytes:n,duration:a},s.realBitrate=Math.round(8*n/a)}if(t.bitrateTest){let e={stats:r,frag:t,part:i,id:t.type};this.onFragBuffered(Yf.FRAG_BUFFERED,e),t.bitrateTest=!1}else this.lastLoadedFragLevel=t.level}}onFragBuffered(e,t){let{frag:i,part:r}=t,s=null!=r&&r.stats.loaded?r.stats:i.stats;if(s.aborted||this.ignoreFragment(i))return;let n=s.parsing.end-s.loading.start-Math.min(s.loading.first-s.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(n,s.loaded),s.bwEstimate=this.getBwEstimate(),i.bitrateTest?this.bitrateTestDelay=n/1e3:this.bitrateTestDelay=0}ignoreFragment(e){return e.type!==ng||"initSegment"===e.sn}clearTimer(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)}get firstAutoLevel(){let{maxAutoLevel:e,minAutoLevel:t}=this.hls,i=this.getBwEstimate(),r=this.hls.config.maxStarvationDelay,s=this.findBestLevel(i,t,e,0,r,1,1);if(s>-1)return s;let n=this.hls.firstLevel,a=Math.min(Math.max(n,t),e);return tp.warn(`[abr] Could not find best starting auto level. Defaulting to first in playlist ${n} clamped to ${a}`),a}get forcedAutoLevel(){return this.nextAutoLevelKey?-1:this._nextAutoLevel}get nextAutoLevel(){let e=this.forcedAutoLevel,t=this.bwEstimator.canEstimate(),i=this.lastLoadedFragLevel>-1;if(!(-1===e||t&&i&&this.nextAutoLevelKey!==this.getAutoLevelKey()))return e;let r=t&&i?this.getNextABRAutoLevel():this.firstAutoLevel;if(-1!==e){let t=this.hls.levels;if(t.length>Math.max(e,r)&&t[e].loadError<=t[r].loadError)return e}return this._nextAutoLevel=r,this.nextAutoLevelKey=this.getAutoLevelKey(),r}getAutoLevelKey(){return`${this.getBwEstimate()}_${this.getStarvationDelay().toFixed(2)}`}getNextABRAutoLevel(){let{fragCurrent:e,partCurrent:t,hls:i}=this,{maxAutoLevel:r,config:s,minAutoLevel:n}=i,a=t?t.duration:e?e.duration:0,o=this.getBwEstimate(),l=this.getStarvationDelay(),h=s.abrBandWidthFactor,d=s.abrBandWidthUpFactor;if(l){let e=this.findBestLevel(o,n,r,l,0,h,d);if(e>=0)return e}let u=a?Math.min(a,s.maxStarvationDelay):s.maxStarvationDelay;if(!l){let e=this.bitrateTestDelay;e&&(u=(a?Math.min(a,s.maxLoadingDelay):s.maxLoadingDelay)-e,tp.info(`[abr] bitrate test took ${Math.round(1e3*e)}ms, set first fragment max fetchDuration to ${Math.round(1e3*u)} ms`),h=d=1)}let c=this.findBestLevel(o,n,r,l,u,h,d);if(tp.info(`[abr] ${l?"rebuffering expected":"buffer is empty"}, optimal quality level ${c}`),c>-1)return c;let f=i.levels[n],p=i.levels[i.loadLevel];return f?.bitrate<p?.bitrate?n:i.loadLevel}getStarvationDelay(){let e=this.hls,t=e.media;if(!t)return 1/0;let i=t&&0!==t.playbackRate?Math.abs(t.playbackRate):1,r=e.mainForwardBufferInfo;return(r?r.len:0)/i}getBwEstimate(){return this.bwEstimator.canEstimate()?this.bwEstimator.getEstimate():this.hls.config.abrEwmaDefaultEstimate}findBestLevel(e,t,i,r,s,n,a){var o;let l=r+s,h=this.lastLoadedFragLevel,d=-1===h?this.hls.firstLevel:h,{fragCurrent:u,partCurrent:c}=this,{levels:f,allAudioTracks:p,loadLevel:m,config:g}=this.hls;if(1===f.length)return 0;let v,E=f[d],y=!(null==E||null==(o=E.details)||!o.live),b=-1===m||-1===h,T="SDR",S=E?.frameRate||0,{audioPreference:A,videoPreference:_}=g,w=this.audioTracksByGroup||(this.audioTracksByGroup=function(e){return e.reduce(((e,t)=>{let i=e.groups[t.groupId];i||(i=e.groups[t.groupId]={tracks:[],channels:{2:0},hasDefault:!1,hasAutoSelect:!1}),i.tracks.push(t);let r=t.channels||"2";return i.channels[r]=(i.channels[r]||0)+1,i.hasDefault=i.hasDefault||t.default,i.hasAutoSelect=i.hasAutoSelect||t.autoselect,i.hasDefault&&(e.hasDefaultAudio=!0),i.hasAutoSelect&&(e.hasAutoSelectAudio=!0),e}),{hasDefaultAudio:!1,hasAutoSelectAudio:!1,groups:{}})}(p));if(b){if(-1!==this.firstSelection)return this.firstSelection;let r=this.codecTiers||(this.codecTiers=function(e,t,i,r){return e.slice(i,r+1).reduce(((e,i)=>{if(!i.codecSet)return e;let r=i.audioGroups,s=e[i.codecSet];s||(e[i.codecSet]=s={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!r,fragmentError:0}),s.minBitrate=Math.min(s.minBitrate,i.bitrate);let n=Math.min(i.height,i.width);return s.minHeight=Math.min(s.minHeight,n),s.minFramerate=Math.min(s.minFramerate,i.frameRate),s.maxScore=Math.max(s.maxScore,i.score),s.fragmentError+=i.fragmentError,s.videoRanges[i.videoRange]=(s.videoRanges[i.videoRange]||0)+1,r&&r.forEach((e=>{if(!e)return;let i=t.groups[e];i&&(s.hasDefaultAudio=s.hasDefaultAudio||t.hasDefaultAudio?i.hasDefault:i.hasAutoSelect||!t.hasDefaultAudio&&!t.hasAutoSelectAudio,Object.keys(i.channels).forEach((e=>{s.channels[e]=(s.channels[e]||0)+i.channels[e]})))})),e}),{})}(f,w,t,i)),s=function(e,t,i,r,s){let n=Object.keys(e),a=r?.channels,o=r?.audioCodec,l=a&&2===parseInt(a),h=!0,d=!1,u=1/0,c=1/0,f=1/0,p=0,m=[],{preferHDR:g,allowedVideoRanges:v}=cv(t,s);for(let t=n.length;t--;){let i=e[n[t]];h=i.channels[2]>0,u=Math.min(u,i.minHeight),c=Math.min(c,i.minFramerate),f=Math.min(f,i.minBitrate);let r=v.filter((e=>i.videoRanges[e]>0));r.length>0&&(d=!0,m=r)}u=Kf(u)?u:0,c=Kf(c)?c:0;let E=Math.max(1080,u),y=Math.max(30,c);return f=Kf(f)?f:i,i=Math.max(f,i),d||(t=void 0,m=[]),{codecSet:n.reduce(((t,r)=>{let s=e[r];if(r===t)return t;if(s.minBitrate>i)return fv(r,`min bitrate of ${s.minBitrate} > current estimate of ${i}`),t;if(!s.hasDefaultAudio)return fv(r,"no renditions with default or auto-select sound found"),t;if(o&&r.indexOf(o.substring(0,4))%5!=0)return fv(r,`audio codec preference "${o}" not found`),t;if(a&&!l){if(!s.channels[a])return fv(r,`no renditions with ${a} channel sound found (channels options: ${Object.keys(s.channels)})`),t}else if((!o||l)&&h&&0===s.channels[2])return fv(r,"no renditions with stereo sound found"),t;return s.minHeight>E?(fv(r,`min resolution of ${s.minHeight} > maximum of ${E}`),t):s.minFramerate>y?(fv(r,`min framerate of ${s.minFramerate} > maximum of ${y}`),t):m.some((e=>s.videoRanges[e]>0))?s.maxScore<p?(fv(r,`max score of ${s.maxScore} < selected max of ${p}`),t):t&&(Nm(r)>=Nm(t)||s.fragmentError>e[t].fragmentError)?t:(p=s.maxScore,r):(fv(r,`no variants with VIDEO-RANGE of ${JSON.stringify(m)} found`),t)}),void 0),videoRanges:m,preferHDR:g,minFramerate:c,minBitrate:f}}(r,T,e,A,_),{codecSet:n,videoRanges:a,minFramerate:o,minBitrate:l,preferHDR:h}=s;v=n,T=h?a[a.length-1]:a[0],S=o,e=Math.max(e,l),tp.log(`[abr] picked start tier ${JSON.stringify(s)}`)}else v=E?.codecSet,T=E?.videoRange;let k=c?c.duration:u?u.duration:0,L=this.bwEstimator.getEstimateTTFB()/1e3,R=[];for(let o=i;o>=t;o--){var I;let t=f[o],u=o>d;if(!t)continue;if(g.useMediaCapabilities&&!t.supportedResult&&!t.supportedPromise){let i=navigator.mediaCapabilities;"function"==typeof i?.decodingInfo&&dv(t,w,T,S,e,A)?(t.supportedPromise=uv(t,w,i),t.supportedPromise.then((e=>{if(!this.hls)return;t.supportedResult=e;let i=this.hls.levels,r=i.indexOf(t);e.error?tp.warn(`[abr] MediaCapabilities decodingInfo error: "${e.error}" for level ${r} ${JSON.stringify(e)}`):e.supported||(tp.warn(`[abr] Unsupported MediaCapabilities decodingInfo result for level ${r} ${JSON.stringify(e)}`),r>-1&&i.length>1&&(tp.log(`[abr] Removing unsupported level ${r}`),this.hls.removeLevel(r)))}))):t.supportedResult=lv}if(v&&t.codecSet!==v||T&&t.videoRange!==T||u&&S>t.frameRate||!u&&S>0&&S<t.frameRate||t.supportedResult&&(null==(I=t.supportedResult.decodingInfoResults)||!I[0].smooth)){R.push(o);continue}let p,_=t.details,C=(c?_?.partTarget:_?.averagetargetduration)||k;p=u?a*e:n*e;let D=k&&r>=2*k&&0===s?f[o].averageBitrate:f[o].maxBitrate,x=this.getTimeToLoadFrag(L,p,D*C,void 0===_);if(p>=D&&(o===h||0===t.loadError&&0===t.fragmentError)&&(x<=L||!Kf(x)||y&&!this.bitrateTestDelay||x<l)){let e=this.forcedAutoLevel;return o!==m&&(-1===e||e!==m)&&(R.length&&tp.trace(`[abr] Skipped level(s) ${R.join(",")} of ${i} max with CODECS and VIDEO-RANGE:"${f[R[0]].codecs}" ${f[R[0]].videoRange}; not compatible with "${E.codecs}" ${T}`),tp.info(`[abr] switch candidate:${d}->${o} adjustedbw(${Math.round(p)})-bitrate=${Math.round(p-D)} ttfb:${L.toFixed(1)} avgDuration:${C.toFixed(1)} maxFetchDuration:${l.toFixed(1)} fetchDuration:${x.toFixed(1)} firstSelection:${b} codecSet:${v} videoRange:${T} hls.loadLevel:${m}`)),b&&(this.firstSelection=o),o}}return-1}set nextAutoLevel(e){let{maxAutoLevel:t,minAutoLevel:i}=this.hls,r=Math.min(Math.max(e,i),t);this._nextAutoLevel!==r&&(this.nextAutoLevelKey="",this._nextAutoLevel=r)}},bufferController:class{constructor(e){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.appendSource=void 0,this.appendErrors={audio:0,video:0,audiovideo:0},this.tracks={},this.pendingTracks={},this.sourceBuffer=void 0,this.log=void 0,this.warn=void 0,this.error=void 0,this._onEndStreaming=e=>{this.hls&&this.hls.pauseBuffering()},this._onStartStreaming=e=>{this.hls&&this.hls.resumeBuffering()},this._onMediaSourceOpen=()=>{let{media:e,mediaSource:t}=this;this.log("Media source opened"),e&&(e.removeEventListener("emptied",this._onMediaEmptied),this.updateMediaElementDuration(),this.hls.trigger(Yf.MEDIA_ATTACHED,{media:e,mediaSource:t})),t&&t.removeEventListener("sourceopen",this._onMediaSourceOpen),this.checkPendingTracks()},this._onMediaSourceClose=()=>{this.log("Media source closed")},this._onMediaSourceEnded=()=>{this.log("Media source ended")},this._onMediaEmptied=()=>{let{mediaSrc:e,_objectUrl:t}=this;e!==t&&tp.error(`Media element src was set while attaching MediaSource (${t} > ${e})`)},this.hls=e;let t="[buffer-controller]";this.appendSource=function(e){return typeof self<"u"&&e===self.ManagedMediaSource}(Dm(e.config.preferManagedMediaSource)),this.log=tp.log.bind(tp,t),this.warn=tp.warn.bind(tp,t),this.error=tp.error.bind(tp,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,this.hls=null}registerListeners(){let{hls:e}=this;e.on(Yf.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(Yf.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(Yf.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Yf.MANIFEST_PARSED,this.onManifestParsed,this),e.on(Yf.BUFFER_RESET,this.onBufferReset,this),e.on(Yf.BUFFER_APPENDING,this.onBufferAppending,this),e.on(Yf.BUFFER_CODECS,this.onBufferCodecs,this),e.on(Yf.BUFFER_EOS,this.onBufferEos,this),e.on(Yf.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(Yf.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(Yf.FRAG_PARSED,this.onFragParsed,this),e.on(Yf.FRAG_CHANGED,this.onFragChanged,this)}unregisterListeners(){let{hls:e}=this;e.off(Yf.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(Yf.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(Yf.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Yf.MANIFEST_PARSED,this.onManifestParsed,this),e.off(Yf.BUFFER_RESET,this.onBufferReset,this),e.off(Yf.BUFFER_APPENDING,this.onBufferAppending,this),e.off(Yf.BUFFER_CODECS,this.onBufferCodecs,this),e.off(Yf.BUFFER_EOS,this.onBufferEos,this),e.off(Yf.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(Yf.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(Yf.FRAG_PARSED,this.onFragParsed,this),e.off(Yf.FRAG_CHANGED,this.onFragChanged,this)}_initSourceBuffer(){this.sourceBuffer={},this.operationQueue=new cy(this.sourceBuffer),this.listeners={audio:[],video:[],audiovideo:[]},this.appendErrors={audio:0,video:0,audiovideo:0},this.lastMpegAudioChunk=null}onManifestLoading(){this.bufferCodecEventsExpected=this._bufferCodecEventsTotal=0,this.details=null}onManifestParsed(e,t){let i=2;(t.audio&&!t.video||!t.altAudio)&&(i=1),this.bufferCodecEventsExpected=this._bufferCodecEventsTotal=i,this.log(`${this.bufferCodecEventsExpected} bufferCodec event(s) expected`)}onMediaAttaching(e,t){let i=this.media=t.media,r=Dm(this.appendSource);if(i&&r){var s;let e=this.mediaSource=new r;this.log(`created media source: ${null==(s=e.constructor)?void 0:s.name}`),e.addEventListener("sourceopen",this._onMediaSourceOpen),e.addEventListener("sourceended",this._onMediaSourceEnded),e.addEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(e.addEventListener("startstreaming",this._onStartStreaming),e.addEventListener("endstreaming",this._onEndStreaming));let t=this._objectUrl=self.URL.createObjectURL(e);if(this.appendSource)try{i.removeAttribute("src");let r=self.ManagedMediaSource;i.disableRemotePlayback=i.disableRemotePlayback||r&&e instanceof r,py(i),function(e,t){let i=self.document.createElement("source");i.type="video/mp4",i.src=t,e.appendChild(i)}(i,t),i.load()}catch{i.src=t}else i.src=t;i.addEventListener("emptied",this._onMediaEmptied)}}onMediaDetaching(){let{media:e,mediaSource:t,_objectUrl:i}=this;if(t){if(this.log("media source detaching"),"open"===t.readyState)try{t.endOfStream()}catch(e){this.warn(`onMediaDetaching: ${e.message} while calling endOfStream`)}this.onBufferReset(),t.removeEventListener("sourceopen",this._onMediaSourceOpen),t.removeEventListener("sourceended",this._onMediaSourceEnded),t.removeEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(t.removeEventListener("startstreaming",this._onStartStreaming),t.removeEventListener("endstreaming",this._onEndStreaming)),e&&(e.removeEventListener("emptied",this._onMediaEmptied),i&&self.URL.revokeObjectURL(i),this.mediaSrc===i?(e.removeAttribute("src"),this.appendSource&&py(e),e.load()):this.warn("media|source.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(Yf.MEDIA_DETACHED,void 0)}onBufferReset(){this.getSourceBufferTypes().forEach((e=>{this.resetBuffer(e)})),this._initSourceBuffer()}resetBuffer(e){let t=this.sourceBuffer[e];try{var i;if(t)this.removeBufferListeners(e),this.sourceBuffer[e]=void 0,null!=(i=this.mediaSource)&&i.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(t)}catch(t){this.warn(`onBufferReset ${e}`,t)}}onBufferCodecs(e,t){let i=this.getSourceBufferTypes().length,r=Object.keys(t);if(r.forEach((e=>{if(i){let i=this.tracks[e];if(i&&"function"==typeof i.buffer.changeType){var r;let{id:s,codec:n,levelCodec:a,container:o,metadata:l}=t[e],h=Hm(i.codec,i.levelCodec),d=h?.replace(fy,"$1"),u=Hm(n,a),c=null==(r=u)?void 0:r.replace(fy,"$1");if(u&&d!==c){"audio"===e.slice(0,5)&&(u=Bm(u,this.appendSource));let t=`${o};codecs=${u}`;this.appendChangeType(e,t),this.log(`switching codec ${h} to ${u}`),this.tracks[e]={buffer:i.buffer,codec:n,container:o,levelCodec:a,metadata:l,id:s}}}}else this.pendingTracks[e]=t[e]})),i)return;let s=Math.max(this.bufferCodecEventsExpected-1,0);this.bufferCodecEventsExpected!==s&&(this.log(`${s} bufferCodec event(s) expected ${r.join(",")}`),this.bufferCodecEventsExpected=s),this.mediaSource&&"open"===this.mediaSource.readyState&&this.checkPendingTracks()}appendChangeType(e,t){let{operationQueue:i}=this,r={execute:()=>{let r=this.sourceBuffer[e];r&&(this.log(`changing ${e} sourceBuffer type to ${t}`),r.changeType(t)),i.shiftAndExecuteNext(e)},onStart:()=>{},onComplete:()=>{},onError:t=>{this.warn(`Failed to change ${e} SourceBuffer type`,t)}};i.append(r,e,!!this.pendingTracks[e])}onBufferAppending(e,t){let{hls:i,operationQueue:r,tracks:s}=this,{data:n,type:a,frag:o,part:l,chunkMeta:h}=t,d=h.buffering[a],u=self.performance.now();d.start=u;let c=o.stats.buffering,f=l?l.stats.buffering:null;0===c.start&&(c.start=u),f&&0===f.start&&(f.start=u);let p=s.audio,m=!1;"audio"===a&&"audio/mpeg"===p?.container&&(m=!this.lastMpegAudioChunk||1===h.id||this.lastMpegAudioChunk.sn!==h.sn,this.lastMpegAudioChunk=h);let g=o.start,v={execute:()=>{if(d.executeStart=self.performance.now(),m){let e=this.sourceBuffer[a];if(e){let t=g-e.timestampOffset;Math.abs(t)>=.1&&(this.log(`Updating audio SourceBuffer timestampOffset to ${g} (delta: ${t}) sn: ${o.sn})`),e.timestampOffset=g)}}this.appendExecutor(n,a)},onStart:()=>{},onComplete:()=>{let e=self.performance.now();d.executeEnd=d.end=e,0===c.first&&(c.first=e),f&&0===f.first&&(f.first=e);let{sourceBuffer:t}=this,i={};for(let e in t)i[e]=Lv.getBuffered(t[e]);this.appendErrors[a]=0,"audio"===a||"video"===a?this.appendErrors.audiovideo=0:(this.appendErrors.audio=0,this.appendErrors.video=0),this.hls.trigger(Yf.BUFFER_APPENDED,{type:a,frag:o,part:l,chunkMeta:h,parent:o.type,timeRanges:i})},onError:e=>{let t={type:zf.MEDIA_ERROR,parent:o.type,details:Xf.BUFFER_APPEND_ERROR,sourceBufferName:a,frag:o,part:l,chunkMeta:h,error:e,err:e,fatal:!1};if(e.code===DOMException.QUOTA_EXCEEDED_ERR)t.details=Xf.BUFFER_FULL_ERROR;else{let e=++this.appendErrors[a];t.details=Xf.BUFFER_APPEND_ERROR,this.warn(`Failed ${e}/${i.config.appendErrorMaxRetry} times to append segment in "${a}" sourceBuffer`),e>=i.config.appendErrorMaxRetry&&(t.fatal=!0)}i.trigger(Yf.ERROR,t)}};r.append(v,a,!!this.pendingTracks[a])}onBufferFlushing(e,t){let{operationQueue:i}=this,r=e=>({execute:this.removeExecutor.bind(this,e,t.startOffset,t.endOffset),onStart:()=>{},onComplete:()=>{this.hls.trigger(Yf.BUFFER_FLUSHED,{type:e})},onError:t=>{this.warn(`Failed to remove from ${e} SourceBuffer`,t)}});t.type?i.append(r(t.type),t.type):this.getSourceBufferTypes().forEach((e=>{i.append(r(e),e)}))}onFragParsed(e,t){let{frag:i,part:r}=t,s=[],n=r?r.elementaryStreams:i.elementaryStreams;n[up]?s.push("audiovideo"):(n[hp]&&s.push("audio"),n[dp]&&s.push("video"));0===s.length&&this.warn(`Fragments must have at least one ElementaryStreamType set. type: ${i.type} level: ${i.level} sn: ${i.sn}`),this.blockBuffers((()=>{let e=self.performance.now();i.stats.buffering.end=e,r&&(r.stats.buffering.end=e);let t=r?r.stats:i.stats;this.hls.trigger(Yf.FRAG_BUFFERED,{frag:i,part:r,stats:t,id:i.type})}),s)}onFragChanged(e,t){this.trimBuffers()}onBufferEos(e,t){this.getSourceBufferTypes().reduce(((e,i)=>{let r=this.sourceBuffer[i];return r&&(!t.type||t.type===i)&&(r.ending=!0,r.ended||(r.ended=!0,this.log(`${i} sourceBuffer now EOS`))),e&&!(r&&!r.ended)}),!0)&&(this.log("Queueing mediaSource.endOfStream()"),this.blockBuffers((()=>{this.getSourceBufferTypes().forEach((e=>{let t=this.sourceBuffer[e];t&&(t.ending=!1)}));let{mediaSource:e}=this;e&&"open"===e.readyState?(this.log("Calling mediaSource.endOfStream()"),e.endOfStream()):e&&this.log(`Could not call mediaSource.endOfStream(). mediaSource.readyState: ${e.readyState}`)})))}onLevelUpdated(e,{details:t}){t.fragments.length&&(this.details=t,this.getSourceBufferTypes().length?this.blockBuffers(this.updateMediaElementDuration.bind(this)):this.updateMediaElementDuration())}trimBuffers(){let{hls:e,details:t,media:i}=this;if(!i||null===t||!this.getSourceBufferTypes().length)return;let r=e.config,s=i.currentTime,n=t.levelTargetDuration,a=t.live&&null!==r.liveBackBufferLength?r.liveBackBufferLength:r.backBufferLength;if(Kf(a)&&a>0){let e=Math.max(a,n),t=Math.floor(s/n)*n-e;this.flushBackBuffer(s,n,t)}if(Kf(r.frontBufferFlushThreshold)&&r.frontBufferFlushThreshold>0){let e=Math.max(r.maxBufferLength,r.frontBufferFlushThreshold),t=Math.max(e,n),i=Math.floor(s/n)*n+t;this.flushFrontBuffer(s,n,i)}}flushBackBuffer(e,t,i){let{details:r,sourceBuffer:s}=this;this.getSourceBufferTypes().forEach((n=>{let a=s[n];if(a){let s=Lv.getBuffered(a);if(s.length>0&&i>s.start(0)){if(this.hls.trigger(Yf.BACK_BUFFER_REACHED,{bufferEnd:i}),null!=r&&r.live)this.hls.trigger(Yf.LIVE_BACK_BUFFER_REACHED,{bufferEnd:i});else if(a.ended&&s.end(s.length-1)-e<2*t)return void this.log(`Cannot flush ${n} back buffer while SourceBuffer is in ended state`);this.hls.trigger(Yf.BUFFER_FLUSHING,{startOffset:0,endOffset:i,type:n})}}}))}flushFrontBuffer(e,t,i){let{sourceBuffer:r}=this;this.getSourceBufferTypes().forEach((s=>{let n=r[s];if(n){let r=Lv.getBuffered(n),a=r.length;if(a<2)return;let o=r.start(a-1),l=r.end(a-1);if(i>o||e>=o&&e<=l)return;if(n.ended&&e-l<2*t)return void this.log(`Cannot flush ${s} front buffer while SourceBuffer is in ended state`);this.hls.trigger(Yf.BUFFER_FLUSHING,{startOffset:o,endOffset:1/0,type:s})}}))}updateMediaElementDuration(){if(!this.details||!this.media||!this.mediaSource||"open"!==this.mediaSource.readyState)return;let{details:e,hls:t,media:i,mediaSource:r}=this,s=e.fragments[0].start+e.totalduration,n=i.duration,a=Kf(r.duration)?r.duration:0;e.live&&t.config.liveDurationInfinity?(r.duration=1/0,this.updateSeekableRange(e)):(s>a&&s>n||!Kf(n))&&(this.log(`Updating Media Source duration to ${s.toFixed(3)}`),r.duration=s)}updateSeekableRange(e){let t=this.mediaSource,i=e.fragments;if(i.length&&e.live&&null!=t&&t.setLiveSeekableRange){let r=Math.max(0,i[0].start),s=Math.max(r,r+e.totalduration);this.log(`Media Source duration is set to ${t.duration}. Setting seekable range to ${r}-${s}.`),t.setLiveSeekableRange(r,s)}}checkPendingTracks(){let{bufferCodecEventsExpected:e,operationQueue:t,pendingTracks:i}=this,r=Object.keys(i).length;if(r&&(!e||2===r||"audiovideo"in i)){this.createSourceBuffers(i),this.pendingTracks={};let e=this.getSourceBufferTypes();if(e.length)this.hls.trigger(Yf.BUFFER_CREATED,{tracks:this.tracks}),e.forEach((e=>{t.executeNext(e)}));else{let e=new Error("could not create source buffer for media codec(s)");this.hls.trigger(Yf.ERROR,{type:zf.MEDIA_ERROR,details:Xf.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:e,reason:e.message})}}}createSourceBuffers(e){let{sourceBuffer:t,mediaSource:i}=this;if(!i)throw Error("createSourceBuffers called when mediaSource was null");for(let s in e)if(!t[s]){var r;let n=e[s];if(!n)throw Error(`source buffer exists for track ${s}, however track does not`);let a=-1===(null==(r=n.levelCodec)?void 0:r.indexOf(","))?n.levelCodec:n.codec;a&&"audio"===s.slice(0,5)&&(a=Bm(a,this.appendSource));let o=`${n.container};codecs=${a}`;this.log(`creating sourceBuffer(${o})`);try{let e=t[s]=i.addSourceBuffer(o),r=s;this.addBufferListener(r,"updatestart",this._onSBUpdateStart),this.addBufferListener(r,"updateend",this._onSBUpdateEnd),this.addBufferListener(r,"error",this._onSBUpdateError),this.appendSource&&this.addBufferListener(r,"bufferedchange",((e,t)=>{let i=t.removedRanges;null!=i&&i.length&&this.hls.trigger(Yf.BUFFER_FLUSHED,{type:s})})),this.tracks[s]={buffer:e,codec:a,container:n.container,levelCodec:n.levelCodec,metadata:n.metadata,id:n.id}}catch(e){this.error(`error while trying to add sourceBuffer: ${e.message}`),this.hls.trigger(Yf.ERROR,{type:zf.MEDIA_ERROR,details:Xf.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:e,sourceBufferName:s,mimeType:o})}}}get mediaSrc(){var e,t;let i=(null==(e=this.media)||null==(t=e.querySelector)?void 0:t.call(e,"source"))||this.media;return i?.src}_onSBUpdateStart(e){let{operationQueue:t}=this;t.current(e).onStart()}_onSBUpdateEnd(e){var t;if("closed"===(null==(t=this.mediaSource)?void 0:t.readyState))return void this.resetBuffer(e);let{operationQueue:i}=this;i.current(e).onComplete(),i.shiftAndExecuteNext(e)}_onSBUpdateError(e,t){var i;let r=new Error(`${e} SourceBuffer error. MediaSource readyState: ${null==(i=this.mediaSource)?void 0:i.readyState}`);this.error(`${r}`,t),this.hls.trigger(Yf.ERROR,{type:zf.MEDIA_ERROR,details:Xf.BUFFER_APPENDING_ERROR,sourceBufferName:e,error:r,fatal:!1});let s=this.operationQueue.current(e);s&&s.onError(r)}removeExecutor(e,t,i){let{media:r,mediaSource:s,operationQueue:n,sourceBuffer:a}=this,o=a[e];if(!r||!s||!o)return this.warn(`Attempting to remove from the ${e} SourceBuffer, but it does not exist`),void n.shiftAndExecuteNext(e);let l=Kf(r.duration)?r.duration:1/0,h=Kf(s.duration)?s.duration:1/0,d=Math.max(0,t),u=Math.min(i,l,h);u>d&&(!o.ending||o.ended)?(o.ended=!1,this.log(`Removing [${d},${u}] from the ${e} SourceBuffer`),o.remove(d,u)):n.shiftAndExecuteNext(e)}appendExecutor(e,t){let i=this.sourceBuffer[t];if(i)i.ended=!1,i.appendBuffer(e);else if(!this.pendingTracks[t])throw new Error(`Attempting to append to the ${t} SourceBuffer, but it does not exist`)}blockBuffers(e,t=this.getSourceBufferTypes()){if(!t.length)return this.log("Blocking operation requested, but no SourceBuffers exist"),void Promise.resolve().then(e);let{operationQueue:i}=this,r=t.map((e=>i.appendBlocker(e)));Promise.all(r).then((()=>{e(),t.forEach((e=>{let t=this.sourceBuffer[e];null!=t&&t.updating||i.shiftAndExecuteNext(e)}))}))}getSourceBufferTypes(){return Object.keys(this.sourceBuffer)}addBufferListener(e,t,i){let r=this.sourceBuffer[e];if(!r)return;let s=i.bind(this,e);this.listeners[e].push({event:t,listener:s}),r.addEventListener(t,s)}removeBufferListeners(e){let t=this.sourceBuffer[e];t&&this.listeners[e].forEach((e=>{t.removeEventListener(e.event,e.listener)}))}},capLevelController:class e{constructor(e){this.hls=void 0,this.autoLevelCapping=void 0,this.firstLevel=void 0,this.media=void 0,this.restrictedLevels=void 0,this.timer=void 0,this.clientRect=void 0,this.streamController=void 0,this.hls=e,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.firstLevel=-1,this.media=null,this.restrictedLevels=[],this.timer=void 0,this.clientRect=null,this.registerListeners()}setStreamController(e){this.streamController=e}destroy(){this.hls&&this.unregisterListener(),this.timer&&this.stopCapping(),this.media=null,this.clientRect=null,this.hls=this.streamController=null}registerListeners(){let{hls:e}=this;e.on(Yf.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.on(Yf.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(Yf.MANIFEST_PARSED,this.onManifestParsed,this),e.on(Yf.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(Yf.BUFFER_CODECS,this.onBufferCodecs,this),e.on(Yf.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListener(){let{hls:e}=this;e.off(Yf.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.off(Yf.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(Yf.MANIFEST_PARSED,this.onManifestParsed,this),e.off(Yf.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(Yf.BUFFER_CODECS,this.onBufferCodecs,this),e.off(Yf.MEDIA_DETACHING,this.onMediaDetaching,this)}onFpsDropLevelCapping(e,t){let i=this.hls.levels[t.droppedLevel];this.isLevelAllowed(i)&&this.restrictedLevels.push({bitrate:i.bitrate,height:i.height,width:i.width})}onMediaAttaching(e,t){this.media=t.media instanceof HTMLVideoElement?t.media:null,this.clientRect=null,this.timer&&this.hls.levels.length&&this.detectPlayerSize()}onManifestParsed(e,t){let i=this.hls;this.restrictedLevels=[],this.firstLevel=t.firstLevel,i.config.capLevelToPlayerSize&&t.video&&this.startCapping()}onLevelsUpdated(e,t){this.timer&&Kf(this.autoLevelCapping)&&this.detectPlayerSize()}onBufferCodecs(e,t){this.hls.config.capLevelToPlayerSize&&t.video&&this.startCapping()}onMediaDetaching(){this.stopCapping()}detectPlayerSize(){if(this.media){if(this.mediaHeight<=0||this.mediaWidth<=0)return void(this.clientRect=null);let e=this.hls.levels;if(e.length){let t=this.hls,i=this.getMaxLevel(e.length-1);i!==this.autoLevelCapping&&tp.log(`Setting autoLevelCapping to ${i}: ${e[i].height}p@${e[i].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`),t.autoLevelCapping=i,t.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=t.autoLevelCapping}}}getMaxLevel(t){let i=this.hls.levels;if(!i.length)return-1;let r=i.filter(((e,i)=>this.isLevelAllowed(e)&&i<=t));return this.clientRect=null,e.getMaxLevelByMediaSize(r,this.mediaWidth,this.mediaHeight)}startCapping(){this.timer||(this.autoLevelCapping=Number.POSITIVE_INFINITY,self.clearInterval(this.timer),this.timer=self.setInterval(this.detectPlayerSize.bind(this),1e3),this.detectPlayerSize())}stopCapping(){this.restrictedLevels=[],this.firstLevel=-1,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer&&(self.clearInterval(this.timer),this.timer=void 0)}getDimensions(){if(this.clientRect)return this.clientRect;let e=this.media,t={width:0,height:0};if(e){let i=e.getBoundingClientRect();t.width=i.width,t.height=i.height,!t.width&&!t.height&&(t.width=i.right-i.left||e.width||0,t.height=i.bottom-i.top||e.height||0)}return this.clientRect=t,t}get mediaWidth(){return this.getDimensions().width*this.contentScaleFactor}get mediaHeight(){return this.getDimensions().height*this.contentScaleFactor}get contentScaleFactor(){let e=1;if(!this.hls.config.ignoreDevicePixelRatio)try{e=self.devicePixelRatio}catch{}return e}isLevelAllowed(e){return!this.restrictedLevels.some((t=>e.bitrate===t.bitrate&&e.width===t.width&&e.height===t.height))}static getMaxLevelByMediaSize(e,t,i){if(null==e||!e.length)return-1;let r=(e,t)=>!t||(e.width!==t.width||e.height!==t.height),s=e.length-1,n=Math.max(t,i);for(let t=0;t<e.length;t+=1){let i=e[t];if((i.width>=n||i.height>=n)&&r(i,e[t+1])){s=t;break}}return s}},errorController:class{constructor(e){this.hls=void 0,this.playlistError=0,this.penalizedRenditions={},this.log=void 0,this.warn=void 0,this.error=void 0,this.hls=e,this.log=tp.log.bind(tp,"[info]:"),this.warn=tp.warn.bind(tp,"[warning]:"),this.error=tp.error.bind(tp,"[error]:"),this.registerListeners()}registerListeners(){let e=this.hls;e.on(Yf.ERROR,this.onError,this),e.on(Yf.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Yf.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){let e=this.hls;e&&(e.off(Yf.ERROR,this.onError,this),e.off(Yf.ERROR,this.onErrorOut,this),e.off(Yf.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Yf.LEVEL_UPDATED,this.onLevelUpdated,this))}destroy(){this.unregisterListeners(),this.hls=null,this.penalizedRenditions={}}startLoad(e){}stopLoad(){this.playlistError=0}getVariantLevelIndex(e){return e?.type===ng?e.level:this.hls.loadLevel}onManifestLoading(){this.playlistError=0,this.penalizedRenditions={}}onLevelUpdated(){this.playlistError=0}onError(e,t){var i,r;if(t.fatal)return;let s=this.hls,n=t.context;switch(t.details){case Xf.FRAG_LOAD_ERROR:case Xf.FRAG_LOAD_TIMEOUT:case Xf.KEY_LOAD_ERROR:case Xf.KEY_LOAD_TIMEOUT:return void(t.errorAction=this.getFragRetryOrSwitchAction(t));case Xf.FRAG_PARSING_ERROR:if(null!=(i=t.frag)&&i.gap)return void(t.errorAction={action:Zg,flags:iv});case Xf.FRAG_GAP:case Xf.FRAG_DECRYPT_ERROR:return t.errorAction=this.getFragRetryOrSwitchAction(t),void(t.errorAction.action=Jg);case Xf.LEVEL_EMPTY_ERROR:case Xf.LEVEL_PARSING_ERROR:{var a,o;let e=t.parent===ng?t.level:s.loadLevel;t.details===Xf.LEVEL_EMPTY_ERROR&&null!=(a=t.context)&&null!=(o=a.levelDetails)&&o.live?t.errorAction=this.getPlaylistRetryOrSwitchAction(t,e):(t.levelRetry=!1,t.errorAction=this.getLevelSwitchAction(t,e))}return;case Xf.LEVEL_LOAD_ERROR:case Xf.LEVEL_LOAD_TIMEOUT:return void("number"==typeof n?.level&&(t.errorAction=this.getPlaylistRetryOrSwitchAction(t,n.level)));case Xf.AUDIO_TRACK_LOAD_ERROR:case Xf.AUDIO_TRACK_LOAD_TIMEOUT:case Xf.SUBTITLE_LOAD_ERROR:case Xf.SUBTITLE_TRACK_LOAD_TIMEOUT:if(n){let e=s.levels[s.loadLevel];if(e&&(n.type===rg&&e.hasAudioGroup(n.groupId)||n.type===sg&&e.hasSubtitleGroup(n.groupId)))return t.errorAction=this.getPlaylistRetryOrSwitchAction(t,s.loadLevel),t.errorAction.action=Jg,void(t.errorAction.flags=rv)}return;case Xf.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:{let e=s.levels[s.loadLevel],i=e?.attrs["HDCP-LEVEL"];i?t.errorAction={action:Jg,flags:sv,hdcpLevel:i}:this.keySystemError(t)}return;case Xf.BUFFER_ADD_CODEC_ERROR:case Xf.REMUX_ALLOC_ERROR:case Xf.BUFFER_APPEND_ERROR:return void(t.errorAction=this.getLevelSwitchAction(t,null!=(r=t.level)?r:s.loadLevel));case Xf.INTERNAL_EXCEPTION:case Xf.BUFFER_APPENDING_ERROR:case Xf.BUFFER_FULL_ERROR:case Xf.LEVEL_SWITCH_ERROR:case Xf.BUFFER_STALLED_ERROR:case Xf.BUFFER_SEEK_OVER_HOLE:case Xf.BUFFER_NUDGE_ON_STALL:return void(t.errorAction={action:Zg,flags:iv})}t.type===zf.KEY_SYSTEM_ERROR&&this.keySystemError(t)}keySystemError(e){let t=this.getVariantLevelIndex(e.frag);e.levelRetry=!1,e.errorAction=this.getLevelSwitchAction(e,t)}getPlaylistRetryOrSwitchAction(e,t){let i=Vg(this.hls.config.playlistLoadPolicy,e),r=this.playlistError++;if(qg(i,r,jg(e),e.response))return{action:tv,flags:iv,retryConfig:i,retryCount:r};let s=this.getLevelSwitchAction(e,t);return i&&(s.retryConfig=i,s.retryCount=r),s}getFragRetryOrSwitchAction(e){let t=this.hls,i=this.getVariantLevelIndex(e.frag),r=t.levels[i],{fragLoadPolicy:s,keyLoadPolicy:n}=t.config,a=Vg(e.details.startsWith("key")?n:s,e),o=t.levels.reduce(((e,t)=>e+t.fragmentError),0);if(r&&(e.details!==Xf.FRAG_GAP&&r.fragmentError++,qg(a,o,jg(e),e.response)))return{action:tv,flags:iv,retryConfig:a,retryCount:o};let l=this.getLevelSwitchAction(e,i);return a&&(l.retryConfig=a,l.retryCount=o),l}getLevelSwitchAction(e,t){let i=this.hls;null==t&&(t=i.loadLevel);let r=this.hls.levels[t];if(r){var s,n;let t=e.details;r.loadError++,t===Xf.BUFFER_APPEND_ERROR&&r.fragmentError++;let l=-1,{levels:h,loadLevel:d,minAutoLevel:u,maxAutoLevel:c}=i;i.autoLevelEnabled||(i.loadLevel=-1);let f=null==(s=e.frag)?void 0:s.type,p=(f===ag&&t===Xf.FRAG_PARSING_ERROR||"audio"===e.sourceBufferName&&(t===Xf.BUFFER_ADD_CODEC_ERROR||t===Xf.BUFFER_APPEND_ERROR))&&h.some((({audioCodec:e})=>r.audioCodec!==e)),m="video"===e.sourceBufferName&&(t===Xf.BUFFER_ADD_CODEC_ERROR||t===Xf.BUFFER_APPEND_ERROR)&&h.some((({codecSet:e,audioCodec:t})=>r.codecSet!==e&&r.audioCodec===t)),{type:g,groupId:v}=null!=(n=e.context)?n:{};for(let i=h.length;i--;){let s=(i+d)%h.length;if(s!==d&&s>=u&&s<=c&&0===h[s].loadError){var a,o;let i=h[s];if(t===Xf.FRAG_GAP&&f===ng&&e.frag){let t=h[s].details;if(t){let i=zg(e.frag,t.fragments,e.frag.start);if(null!=i&&i.gap)continue}}else{if(g===rg&&i.hasAudioGroup(v)||g===sg&&i.hasSubtitleGroup(v))continue;if(f===ag&&null!=(a=r.audioGroups)&&a.some((e=>i.hasAudioGroup(e)))||f===og&&null!=(o=r.subtitleGroups)&&o.some((e=>i.hasSubtitleGroup(e)))||p&&r.audioCodec===i.audioCodec||!p&&r.audioCodec!==i.audioCodec||m&&r.codecSet===i.codecSet)continue}l=s;break}}if(l>-1&&i.loadLevel!==l)return e.levelRetry=!0,this.playlistError=0,{action:Jg,flags:iv,nextAutoLevel:l}}return{action:Jg,flags:rv}}onErrorOut(e,t){var i;switch(null==(i=t.errorAction)?void 0:i.action){case Zg:break;case Jg:this.sendAlternateToPenaltyBox(t),t.errorAction.resolved||t.details===Xf.FRAG_GAP?/MediaSource readyState: ended/.test(t.error.message)&&(this.warn(`MediaSource ended after "${t.sourceBufferName}" sourceBuffer append error. Attempting to recover from media error.`),this.hls.recoverMediaError()):t.fatal=!0}t.fatal&&this.hls.stopLoad()}sendAlternateToPenaltyBox(e){let t=this.hls,i=e.errorAction;if(!i)return;let{flags:r,hdcpLevel:s,nextAutoLevel:n}=i;switch(r){case iv:this.switchLevel(e,n);break;case sv:s&&(t.maxHdcpLevel=kg[kg.indexOf(s)-1],i.resolved=!0),this.warn(`Restricting playback to HDCP-LEVEL of "${t.maxHdcpLevel}" or lower`)}i.resolved||this.switchLevel(e,n)}switchLevel(e,t){void 0!==t&&e.errorAction&&(this.warn(`switching to level ${t} after ${e.details}`),this.hls.nextAutoLevel=t,e.errorAction.resolved=!0,this.hls.nextLoadLevel=this.hls.nextAutoLevel)}},fpsController:class{constructor(e){this.hls=void 0,this.isVideoPlaybackQualityAvailable=!1,this.timer=void 0,this.media=null,this.lastTime=void 0,this.lastDroppedFrames=0,this.lastDecodedFrames=0,this.streamController=void 0,this.hls=e,this.registerListeners()}setStreamController(e){this.streamController=e}registerListeners(){this.hls.on(Yf.MEDIA_ATTACHING,this.onMediaAttaching,this)}unregisterListeners(){this.hls.off(Yf.MEDIA_ATTACHING,this.onMediaAttaching,this)}destroy(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null}onMediaAttaching(e,t){let i=this.hls.config;if(i.capLevelOnFPSDrop){let e=t.media instanceof self.HTMLVideoElement?t.media:null;this.media=e,e&&"function"==typeof e.getVideoPlaybackQuality&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),i.fpsDroppedMonitoringPeriod)}}checkFPS(e,t,i){let r=performance.now();if(t){if(this.lastTime){let e=r-this.lastTime,s=i-this.lastDroppedFrames,n=t-this.lastDecodedFrames,a=1e3*s/e,o=this.hls;if(o.trigger(Yf.FPS_DROP,{currentDropped:s,currentDecoded:n,totalDroppedFrames:i}),a>0&&s>o.config.fpsDroppedMonitoringThreshold*n){let e=o.currentLevel;tp.warn("drop FPS ratio greater than max allowed value for currentLevel: "+e),e>0&&(-1===o.autoLevelCapping||o.autoLevelCapping>=e)&&(e-=1,o.trigger(Yf.FPS_DROP_LEVEL_CAPPING,{level:e,droppedLevel:o.currentLevel}),o.autoLevelCapping=e,this.streamController.nextLevelSwitch())}}this.lastTime=r,this.lastDroppedFrames=i,this.lastDecodedFrames=t}}checkFPSInterval(){let e=this.media;if(e)if(this.isVideoPlaybackQualityAvailable){let t=e.getVideoPlaybackQuality();this.checkFPS(e,t.totalVideoFrames,t.droppedVideoFrames)}else this.checkFPS(e,e.webkitDecodedFrameCount,e.webkitDroppedFrameCount)}},stretchShortVideoTrack:!1,maxAudioFramesDrift:1,forceKeyFrameOnDiscontinuity:!0,abrEwmaFastLive:3,abrEwmaSlowLive:9,abrEwmaFastVoD:3,abrEwmaSlowVoD:9,abrEwmaDefaultEstimate:5e5,abrEwmaDefaultEstimateMax:5e6,abrBandWidthFactor:.95,abrBandWidthUpFactor:.7,abrMaxWithRealBitrate:!1,maxStarvationDelay:4,maxLoadingDelay:4,minAutoBitrate:0,emeEnabled:!1,widevineLicenseUrl:void 0,drmSystems:{},drmSystemOptions:{},requestMediaKeySystemAccessFunc:Mp,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableID3MetadataCues:!0,useMediaCapabilities:!0,certLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null}},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},{cueHandler:Xb,enableWebVTT:!0,enableIMSC1:!0,enableCEA708Captions:!0,captionsTextTrack1Label:"English",captionsTextTrack1LanguageCode:"en",captionsTextTrack2Label:"Spanish",captionsTextTrack2LanguageCode:"es",captionsTextTrack3Label:"Unknown CC",captionsTextTrack3LanguageCode:"",captionsTextTrack4Label:"Unknown CC",captionsTextTrack4LanguageCode:"",renderTextTracksNatively:!0}),{},{subtitleStreamController:class extends iE{constructor(e,t,i){super(e,t,i,"[subtitle-stream-controller]",og),this.currentTrackId=-1,this.tracksBuffered=[],this.mainDetails=null,this._registerListeners()}onHandlerDestroying(){this._unregisterListeners(),super.onHandlerDestroying(),this.mainDetails=null}_registerListeners(){let{hls:e}=this;e.on(Yf.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(Yf.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(Yf.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Yf.LEVEL_LOADED,this.onLevelLoaded,this),e.on(Yf.ERROR,this.onError,this),e.on(Yf.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(Yf.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(Yf.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(Yf.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.on(Yf.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(Yf.FRAG_BUFFERED,this.onFragBuffered,this)}_unregisterListeners(){let{hls:e}=this;e.off(Yf.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(Yf.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(Yf.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Yf.LEVEL_LOADED,this.onLevelLoaded,this),e.off(Yf.ERROR,this.onError,this),e.off(Yf.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(Yf.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(Yf.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(Yf.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.off(Yf.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(Yf.FRAG_BUFFERED,this.onFragBuffered,this)}startLoad(e){this.stopLoad(),this.state=Kv,this.setInterval(500),this.nextLoadPosition=this.startPosition=this.lastCurrentTime=e,this.tick()}onManifestLoading(){this.mainDetails=null,this.fragmentTracker.removeAllFragments()}onMediaDetaching(){this.tracksBuffered=[],super.onMediaDetaching()}onLevelLoaded(e,t){this.mainDetails=t.details}onSubtitleFragProcessed(e,t){let{frag:i,success:r}=t;if(this.fragPrevious=i,this.state=Kv,!r)return;let s=this.tracksBuffered[this.currentTrackId];if(!s)return;let n,a=i.start;for(let e=0;e<s.length;e++)if(a>=s[e].start&&a<=s[e].end){n=s[e];break}let o=i.start+i.duration;n?n.end=o:(n={start:a,end:o},s.push(n)),this.fragmentTracker.fragBuffered(i),this.fragBufferedComplete(i,null)}onBufferFlushing(e,t){let{startOffset:i,endOffset:r}=t;if(0===i&&r!==Number.POSITIVE_INFINITY){let e=r-1;if(e<=0)return;t.endOffsetSubtitles=Math.max(0,e),this.tracksBuffered.forEach((t=>{for(let i=0;i<t.length;)if(t[i].end<=e)t.shift();else{if(!(t[i].start<e))break;t[i].start=e,i++}})),this.fragmentTracker.removeFragmentsInRange(i,e,og)}}onFragBuffered(e,t){var i;this.loadedmetadata||t.frag.type!==ng||null!=(i=this.media)&&i.buffered.length&&(this.loadedmetadata=!0)}onError(e,t){let i=t.frag;i?.type===og&&(t.details===Xf.FRAG_GAP&&this.fragmentTracker.fragBuffered(i,!0),this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==Vv&&(this.state=Kv))}onSubtitleTracksUpdated(e,{subtitleTracks:t}){this.levels&&ly(this.levels,t)?this.levels=t.map((e=>new Mg(e))):(this.tracksBuffered=[],this.levels=t.map((e=>{let t=new Mg(e);return this.tracksBuffered[t.id]=[],t})),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,og),this.fragPrevious=null,this.mediaBuffer=null)}onSubtitleTrackSwitch(e,t){var i;if(this.currentTrackId=t.id,null==(i=this.levels)||!i.length||-1===this.currentTrackId)return void this.clearInterval();let r=this.levels[this.currentTrackId];null!=r&&r.details?this.mediaBuffer=this.mediaBufferTimeRanges:this.mediaBuffer=null,r&&this.setInterval(500)}onSubtitleTrackLoaded(e,t){var i;let{currentTrackId:r,levels:s}=this,{details:n,id:a}=t;if(!s)return void this.warn(`Subtitle tracks were reset while loading level ${a}`);let o=s[a];if(a>=s.length||!o)return;this.log(`Subtitle track ${a} loaded [${n.startSN},${n.endSN}]${n.lastPartSn?`[part-${n.lastPartSn}-${n.lastPartIndex}]`:""},duration:${n.totalduration}`),this.mediaBuffer=this.mediaBufferTimeRanges;let l=0;if(n.live||null!=(i=o.details)&&i.live){let e=this.mainDetails;if(n.deltaUpdateFailed||!e)return;let t=e.fragments[0];var h;if(o.details)l=this.alignPlaylists(n,o.details,null==(h=this.levelLastLoaded)?void 0:h.details),0===l&&t&&(l=t.start,Fg(n,l));else n.hasProgramDateTime&&e.hasProgramDateTime?(Mv(n,e),l=n.fragments[0].start):t&&(l=t.start,Fg(n,l))}o.details=n,this.levelLastLoaded=o,a===r&&(!this.startFragRequested&&(this.mainDetails||!n.live)&&this.setStartPosition(this.mainDetails||n,l),this.tick(),n.live&&!this.fragCurrent&&this.media&&this.state===Kv&&(zg(null,n.fragments,this.media.currentTime,0)||(this.warn("Subtitle playlist not aligned with playback"),o.details=void 0)))}_handleFragmentLoadComplete(e){let{frag:t,payload:i}=e,r=t.decryptdata,s=this.hls;if(!this.fragContextChanged(t)&&i&&i.byteLength>0&&null!=r&&r.key&&r.iv&&"AES-128"===r.method){let e=performance.now();this.decrypter.decrypt(new Uint8Array(i),r.key.buffer,r.iv.buffer).catch((e=>{throw s.trigger(Yf.ERROR,{type:zf.MEDIA_ERROR,details:Xf.FRAG_DECRYPT_ERROR,fatal:!1,error:e,reason:e.message,frag:t}),e})).then((i=>{let r=performance.now();s.trigger(Yf.FRAG_DECRYPTED,{frag:t,payload:i,stats:{tstart:e,tdecrypt:r}})})).catch((e=>{this.warn(`${e.name}: ${e.message}`),this.state=Kv}))}}doTick(){if(this.media){if(this.state===Kv){let{currentTrackId:e,levels:t}=this,i=t?.[e];if(!i||!t.length||!i.details)return;let{config:r}=this,s=this.getLoadPosition(),n=Lv.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],s,r.maxBufferHole),{end:a,len:o}=n,l=this.getFwdBufferInfo(this.media,ng),h=i.details;if(o>this.getMaxBufferLength(l?.len)+h.levelTargetDuration)return;let d=h.fragments,u=d.length,c=h.edge,f=null,p=this.fragPrevious;if(a<c){let e=r.maxFragLookUpTolerance,t=a>c-e?0:e;f=zg(p,d,Math.max(d[0].start,a),t),!f&&p&&p.start<d[0].start&&(f=d[0])}else f=d[u-1];if(!f)return;if(f=this.mapToInitFragWhenRequired(f),"initSegment"!==f.sn){let e=d[f.sn-h.startSN-1];e&&e.cc===f.cc&&this.fragmentTracker.getState(e)===yv&&(f=e)}this.fragmentTracker.getState(f)===yv&&this.loadFragment(f,i,a)}}else this.state=Kv}getMaxBufferLength(e){let t=super.getMaxBufferLength();return e?Math.max(t,e):t}loadFragment(e,t,i){this.fragCurrent=e,"initSegment"===e.sn?this._loadInitSegment(e,t):(this.startFragRequested=!0,super.loadFragment(e,t,i))}get mediaBufferTimeRanges(){return new uy(this.tracksBuffered[this.currentTrackId]||[])}},subtitleTrackController:class extends nv{constructor(e){super(e,"[subtitle-track-controller]"),this.media=null,this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.queuedDefaultTrack=-1,this.asyncPollTrackChange=()=>this.pollTrackChange(0),this.useTextTrackPolling=!1,this.subtitlePollingInterval=-1,this._subtitleDisplay=!0,this.onTextTracksChanged=()=>{if(this.useTextTrackPolling||self.clearInterval(this.subtitlePollingInterval),!this.media||!this.hls.config.renderTextTracksNatively)return;let e=null,t=mg(this.media.textTracks);for(let i=0;i<t.length;i++)if("hidden"===t[i].mode)e=t[i];else if("showing"===t[i].mode){e=t[i];break}let i=this.findTrackForTextTrack(e);this.subtitleTrack!==i&&this.setSubtitleTrack(i)},this.registerListeners()}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,this.onTextTracksChanged=this.asyncPollTrackChange=null,super.destroy()}get subtitleDisplay(){return this._subtitleDisplay}set subtitleDisplay(e){this._subtitleDisplay=e,this.trackId>-1&&this.toggleTrackModes()}registerListeners(){let{hls:e}=this;e.on(Yf.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(Yf.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(Yf.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Yf.MANIFEST_PARSED,this.onManifestParsed,this),e.on(Yf.LEVEL_LOADING,this.onLevelLoading,this),e.on(Yf.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(Yf.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(Yf.ERROR,this.onError,this)}unregisterListeners(){let{hls:e}=this;e.off(Yf.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(Yf.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(Yf.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Yf.MANIFEST_PARSED,this.onManifestParsed,this),e.off(Yf.LEVEL_LOADING,this.onLevelLoading,this),e.off(Yf.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(Yf.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(Yf.ERROR,this.onError,this)}onMediaAttached(e,t){this.media=t.media,this.media&&(this.queuedDefaultTrack>-1&&(this.subtitleTrack=this.queuedDefaultTrack,this.queuedDefaultTrack=-1),this.useTextTrackPolling=!(this.media.textTracks&&"onchange"in this.media.textTracks),this.useTextTrackPolling?this.pollTrackChange(500):this.media.textTracks.addEventListener("change",this.asyncPollTrackChange))}pollTrackChange(e){self.clearInterval(this.subtitlePollingInterval),this.subtitlePollingInterval=self.setInterval(this.onTextTracksChanged,e)}onMediaDetaching(){this.media&&(self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||this.media.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId),mg(this.media.textTracks).forEach((e=>{fg(e)})),this.subtitleTrack=-1,this.media=null)}onManifestLoading(){this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0}onManifestParsed(e,t){this.tracks=t.subtitleTracks}onSubtitleTrackLoaded(e,t){let{id:i,groupId:r,details:s}=t,n=this.tracksInGroup[i];if(!n||n.groupId!==r)return void this.warn(`Subtitle track with id:${i} and group:${r} not found in active group ${n?.groupId}`);let a=n.details;n.details=t.details,this.log(`Subtitle track ${i} "${n.name}" lang:${n.lang} group:${r} loaded [${s.startSN}-${s.endSN}]`),i===this.trackId&&this.playlistLoaded(i,t,a)}onLevelLoading(e,t){this.switchLevel(t.level)}onLevelSwitching(e,t){this.switchLevel(t.level)}switchLevel(e){let t=this.hls.levels[e];if(!t)return;let i=t.subtitleGroups||null,r=this.groupIds,s=this.currentTrack;if(!i||r?.length!==i?.length||null!=i&&i.some((e=>-1===r?.indexOf(e)))){this.groupIds=i,this.trackId=-1,this.currentTrack=null;let e=this.tracks.filter((e=>!i||-1!==i.indexOf(e.groupId)));if(e.length)this.selectDefaultTrack&&!e.some((e=>e.default))&&(this.selectDefaultTrack=!1),e.forEach(((e,t)=>{e.id=t}));else if(!s&&!this.tracksInGroup.length)return;this.tracksInGroup=e;let t=this.hls.config.subtitlePreference;if(!s&&t){this.selectDefaultTrack=!1;let i=pv(t,e);if(i>-1)s=e[i];else{let e=pv(t,this.tracks);s=this.tracks[e]}}let r=this.findTrackId(s);-1===r&&s&&(r=this.findTrackId(null));let n={subtitleTracks:e};this.log(`Updating subtitle tracks, ${e.length} track(s) found in "${i?.join(",")}" group-id`),this.hls.trigger(Yf.SUBTITLE_TRACKS_UPDATED,n),-1!==r&&-1===this.trackId&&this.setSubtitleTrack(r)}else this.shouldReloadPlaylist(s)&&this.setSubtitleTrack(this.trackId)}findTrackId(e){let t=this.tracksInGroup,i=this.selectDefaultTrack;for(let r=0;r<t.length;r++){let s=t[r];if((!i||s.default)&&(i||e)&&(!e||mv(s,e)))return r}if(e){for(let i=0;i<t.length;i++){let r=t[i];if(hy(e.attrs,r.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return i}for(let i=0;i<t.length;i++){let r=t[i];if(hy(e.attrs,r.attrs,["LANGUAGE"]))return i}}return-1}findTrackForTextTrack(e){if(e){let t=this.tracksInGroup;for(let i=0;i<t.length;i++){if(dy(t[i],e))return i}}return-1}onError(e,t){t.fatal||!t.context||t.context.type===sg&&t.context.id===this.trackId&&(!this.groupIds||-1!==this.groupIds.indexOf(t.context.groupId))&&this.checkRetry(t)}get allSubtitleTracks(){return this.tracks}get subtitleTracks(){return this.tracksInGroup}get subtitleTrack(){return this.trackId}set subtitleTrack(e){this.selectDefaultTrack=!1,this.setSubtitleTrack(e)}setSubtitleOption(e){if(this.hls.config.subtitlePreference=e,e){let t=this.allSubtitleTracks;if(this.selectDefaultTrack=!1,t.length){let i=this.currentTrack;if(i&&mv(e,i))return i;let r=pv(e,this.tracksInGroup);if(r>-1){let e=this.tracksInGroup[r];return this.setSubtitleTrack(r),e}if(i)return null;{let i=pv(e,t);if(i>-1)return t[i]}}}return null}loadPlaylist(e){super.loadPlaylist();let t=this.currentTrack;if(this.shouldLoadPlaylist(t)&&t){let i=t.id,r=t.groupId,s=t.url;if(e)try{s=e.addDirectives(s)}catch(e){this.warn(`Could not construct new URL with HLS Delivery Directives: ${e}`)}this.log(`Loading subtitle playlist for id ${i}`),this.hls.trigger(Yf.SUBTITLE_TRACK_LOADING,{url:s,id:i,groupId:r,deliveryDirectives:e||null})}}toggleTrackModes(){let{media:e}=this;if(!e)return;let t,i=mg(e.textTracks),r=this.currentTrack;if(r&&(t=i.filter((e=>dy(r,e)))[0],t||this.warn(`Unable to find subtitle TextTrack with name "${r.name}" and language "${r.lang}"`)),[].slice.call(i).forEach((e=>{"disabled"!==e.mode&&e!==t&&(e.mode="disabled")})),t){let e=this.subtitleDisplay?"showing":"hidden";t.mode!==e&&(t.mode=e)}}setSubtitleTrack(e){let t=this.tracksInGroup;if(!this.media)return void(this.queuedDefaultTrack=e);if(e<-1||e>=t.length||!Kf(e))return void this.warn(`Invalid subtitle track id: ${e}`);this.clearTimer(),this.selectDefaultTrack=!1;let i=this.currentTrack,r=t[e]||null;if(this.trackId=e,this.currentTrack=r,this.toggleTrackModes(),!r)return void this.hls.trigger(Yf.SUBTITLE_TRACK_SWITCH,{id:e});let s=!!r.details&&!r.details.live;if(e===this.trackId&&r===i&&s)return;this.log(`Switching to subtitle-track ${e}`+(r?` "${r.name}" lang:${r.lang} group:${r.groupId}`:""));let{id:n,groupId:a="",name:o,type:l,url:h}=r;this.hls.trigger(Yf.SUBTITLE_TRACK_SWITCH,{id:n,groupId:a,name:o,type:l,url:h});let d=this.switchParams(r.url,i?.details,r.details);this.loadPlaylist(d)}},timelineController:class{constructor(e){this.hls=void 0,this.media=null,this.config=void 0,this.enabled=!0,this.Cues=void 0,this.textTracks=[],this.tracks=[],this.initPTS=[],this.unparsedVttFrags=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.cea608Parser1=void 0,this.cea608Parser2=void 0,this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs={ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}},this.captionsProperties=void 0,this.hls=e,this.config=e.config,this.Cues=e.config.cueHandler,this.captionsProperties={textTrack1:{label:this.config.captionsTextTrack1Label,languageCode:this.config.captionsTextTrack1LanguageCode},textTrack2:{label:this.config.captionsTextTrack2Label,languageCode:this.config.captionsTextTrack2LanguageCode},textTrack3:{label:this.config.captionsTextTrack3Label,languageCode:this.config.captionsTextTrack3LanguageCode},textTrack4:{label:this.config.captionsTextTrack4Label,languageCode:this.config.captionsTextTrack4LanguageCode}},e.on(Yf.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(Yf.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(Yf.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Yf.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(Yf.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(Yf.FRAG_LOADING,this.onFragLoading,this),e.on(Yf.FRAG_LOADED,this.onFragLoaded,this),e.on(Yf.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.on(Yf.FRAG_DECRYPTED,this.onFragDecrypted,this),e.on(Yf.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(Yf.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.on(Yf.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){let{hls:e}=this;e.off(Yf.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(Yf.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(Yf.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Yf.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(Yf.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(Yf.FRAG_LOADING,this.onFragLoading,this),e.off(Yf.FRAG_LOADED,this.onFragLoaded,this),e.off(Yf.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.off(Yf.FRAG_DECRYPTED,this.onFragDecrypted,this),e.off(Yf.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(Yf.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.off(Yf.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=null,this.cea608Parser1=this.cea608Parser2=void 0}initCea608Parsers(){if(this.config.enableCEA708Captions&&(!this.cea608Parser1||!this.cea608Parser2)){let e=new Py(this,"textTrack1"),t=new Py(this,"textTrack2"),i=new Py(this,"textTrack3"),r=new Py(this,"textTrack4");this.cea608Parser1=new Dy(1,e,t),this.cea608Parser2=new Dy(3,i,r)}}addCues(e,t,i,r,s){let n=!1;for(let e=s.length;e--;){let r=s[e],a=hb(r[0],r[1],t,i);if(a>=0&&(r[0]=Math.min(r[0],t),r[1]=Math.max(r[1],i),n=!0,a/(i-t)>.5))return}if(n||s.push([t,i]),this.config.renderTextTracksNatively){let s=this.captionsTracks[e];this.Cues.newCue(s,t,i,r)}else{let s=this.Cues.newCue(null,t,i,r);this.hls.trigger(Yf.CUES_PARSED,{type:"captions",cues:s,track:e})}}onInitPtsFound(e,{frag:t,id:i,initPTS:r,timescale:s}){let{unparsedVttFrags:n}=this;"main"===i&&(this.initPTS[t.cc]={baseTime:r,timescale:s}),n.length&&(this.unparsedVttFrags=[],n.forEach((e=>{this.onFragLoaded(Yf.FRAG_LOADED,e)})))}getExistingTrack(e,t){let{media:i}=this;if(i)for(let r=0;r<i.textTracks.length;r++){let s=i.textTracks[r];if(lb(s,{name:e,lang:t}))return s}return null}createCaptionsTrack(e){this.config.renderTextTracksNatively?this.createNativeTrack(e):this.createNonNativeTrack(e)}createNativeTrack(e){if(this.captionsTracks[e])return;let{captionsProperties:t,captionsTracks:i,media:r}=this,{label:s,languageCode:n}=t[e],a=this.getExistingTrack(s,n);if(a)i[e]=a,fg(i[e]),ug(i[e],r);else{let t=this.createTextTrack("captions",s,n);t&&(t[e]=!0,i[e]=t)}}createNonNativeTrack(e){if(this.nonNativeCaptionsTracks[e])return;let t=this.captionsProperties[e];if(!t)return;let i={_id:e,label:t.label,kind:"captions",default:!!t.media&&!!t.media.default,closedCaptions:t.media};this.nonNativeCaptionsTracks[e]=i,this.hls.trigger(Yf.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[i]})}createTextTrack(e,t,i){let r=this.media;if(r)return r.addTextTrack(e,t,i)}onMediaAttaching(e,t){this.media=t.media,this._cleanTracks()}onMediaDetaching(){let{captionsTracks:e}=this;Object.keys(e).forEach((t=>{fg(e[t]),delete e[t]})),this.nonNativeCaptionsTracks={}}onManifestLoading(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs={ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}},this._cleanTracks(),this.tracks=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.textTracks=[],this.unparsedVttFrags=[],this.initPTS=[],this.cea608Parser1&&this.cea608Parser2&&(this.cea608Parser1.reset(),this.cea608Parser2.reset())}_cleanTracks(){let{media:e}=this;if(!e)return;let t=e.textTracks;if(t)for(let e=0;e<t.length;e++)fg(t[e])}onSubtitleTracksUpdated(e,t){let i=t.subtitleTracks||[],r=i.some((e=>e.textCodec===Xy));if(this.config.enableWebVTT||r&&this.config.enableIMSC1){if(ly(this.tracks,i))return void(this.tracks=i);if(this.textTracks=[],this.tracks=i,this.config.renderTextTracksNatively){let e=this.media,t=e?mg(e.textTracks):null;if(this.tracks.forEach(((e,i)=>{let r;if(t){let i=null;for(let r=0;r<t.length;r++)if(t[r]&&lb(t[r],e)){i=t[r],t[r]=null;break}i&&(r=i)}if(r)fg(r);else{let t=ob(e);r=this.createTextTrack(t,e.name,e.lang),r&&(r.mode="disabled")}r&&this.textTracks.push(r)})),null!=t&&t.length){let e=t.filter((e=>null!==e)).map((e=>e.label));e.length&&tp.warn(`Media element contains unused subtitle tracks: ${e.join(", ")}. Replace media element for each source to clear TextTracks and captions menu.`)}}else if(this.tracks.length){let e=this.tracks.map((e=>({label:e.name,kind:e.type.toLowerCase(),default:e.default,subtitleTrack:e})));this.hls.trigger(Yf.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:e})}}}onManifestLoaded(e,t){this.config.enableCEA708Captions&&t.captions&&t.captions.forEach((e=>{let t=/(?:CC|SERVICE)([1-4])/.exec(e.instreamId);if(!t)return;let i=`textTrack${t[1]}`,r=this.captionsProperties[i];r&&(r.label=e.name,e.lang&&(r.languageCode=e.lang),r.media=e)}))}closedCaptionsForLevel(e){let t=this.hls.levels[e.level];return t?.attrs["CLOSED-CAPTIONS"]}onFragLoading(e,t){if(this.enabled&&t.frag.type===ng){var i,r;let{cea608Parser1:e,cea608Parser2:s,lastSn:n}=this,{cc:a,sn:o}=t.frag,l=null!=(i=null==(r=t.part)?void 0:r.index)?i:-1;e&&s&&(o!==n+1||o===n&&l!==this.lastPartIndex+1||a!==this.lastCc)&&(e.reset(),s.reset()),this.lastCc=a,this.lastSn=o,this.lastPartIndex=l}}onFragLoaded(e,t){let{frag:i,payload:r}=t;if(i.type===og)if(r.byteLength){let e=i.decryptdata,s="stats"in t;if(null==e||!e.encrypted||s){let e=this.tracks[i.level],s=this.vttCCs;s[i.cc]||(s[i.cc]={start:i.start,prevCC:this.prevCC,new:!0},this.prevCC=i.cc),e&&e.textCodec===Xy?this._parseIMSC1(i,r):this._parseVTTs(t)}}else this.hls.trigger(Yf.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,error:new Error("Empty subtitle payload")})}_parseIMSC1(e,t){let i=this.hls;eb(t,this.initPTS[e.cc],(t=>{this._appendCues(t,e.level),i.trigger(Yf.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:e})}),(t=>{tp.log(`Failed to parse IMSC1: ${t}`),i.trigger(Yf.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e,error:t})}))}_parseVTTs(e){var t;let{frag:i,payload:r}=e,{initPTS:s,unparsedVttFrags:n}=this,a=s.length-1;if(!s[i.cc]&&-1===a)return void n.push(e);let o=this.hls;zy(null!=(t=i.initSegment)&&t.data?gm(i.initSegment.data,new Uint8Array(r)):r,this.initPTS[i.cc],this.vttCCs,i.cc,i.start,(e=>{this._appendCues(e,i.level),o.trigger(Yf.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:i})}),(t=>{let s="Missing initPTS for VTT MPEGTS"===t.message;s?n.push(e):this._fallbackToIMSC1(i,r),tp.log(`Failed to parse VTT cue: ${t}`),!(s&&a>i.cc)&&o.trigger(Yf.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,error:t})}))}_fallbackToIMSC1(e,t){let i=this.tracks[e.level];i.textCodec||eb(t,this.initPTS[e.cc],(()=>{i.textCodec=Xy,this._parseIMSC1(e,t)}),(()=>{i.textCodec="wvtt"}))}_appendCues(e,t){let i=this.hls;if(this.config.renderTextTracksNatively){let i=this.textTracks[t];if(!i||"disabled"===i.mode)return;e.forEach((e=>cg(i,e)))}else{let r=this.tracks[t];if(!r)return;let s=r.default?"default":"subtitles"+t;i.trigger(Yf.CUES_PARSED,{type:"subtitles",cues:e,track:s})}}onFragDecrypted(e,t){let{frag:i}=t;i.type===og&&this.onFragLoaded(Yf.FRAG_LOADED,t)}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(e,t){this.initCea608Parsers();let{cea608Parser1:i,cea608Parser2:r}=this;if(!this.enabled||!i||!r)return;let{frag:s,samples:n}=t;if(s.type!==ng||"NONE"!==this.closedCaptionsForLevel(s))for(let e=0;e<n.length;e++){let t=n[e].bytes;if(t){let s=this.extractCea608Data(t);i.addData(n[e].pts,s[0]),r.addData(n[e].pts,s[1])}}}onBufferFlushing(e,{startOffset:t,endOffset:i,endOffsetSubtitles:r,type:s}){let{media:n}=this;if(n&&!(n.currentTime<i)){if(!s||"video"===s){let{captionsTracks:e}=this;Object.keys(e).forEach((r=>pg(e[r],t,i)))}if(this.config.renderTextTracksNatively&&0===t&&void 0!==r){let{textTracks:e}=this;Object.keys(e).forEach((i=>pg(e[i],t,r)))}}}extractCea608Data(e){let t=[[],[]],i=31&e[0],r=2;for(let s=0;s<i;s++){let i=e[r++],s=127&e[r++],n=127&e[r++];if((0!==s||0!==n)&&4&i){let e=3&i;(0===e||1===e)&&(t[e].push(s),t[e].push(n))}}return t}},audioStreamController:class extends iE{constructor(e,t,i){super(e,t,i,"[audio-stream-controller]",ag),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.flushing=!1,this.bufferFlushed=!1,this.cachedTrackLoadedData=null,this._registerListeners()}onHandlerDestroying(){this._unregisterListeners(),super.onHandlerDestroying(),this.mainDetails=null,this.bufferedTrack=null,this.switchingTrack=null}_registerListeners(){let{hls:e}=this;e.on(Yf.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(Yf.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(Yf.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Yf.LEVEL_LOADED,this.onLevelLoaded,this),e.on(Yf.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.on(Yf.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(Yf.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(Yf.ERROR,this.onError,this),e.on(Yf.BUFFER_RESET,this.onBufferReset,this),e.on(Yf.BUFFER_CREATED,this.onBufferCreated,this),e.on(Yf.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(Yf.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(Yf.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(Yf.FRAG_BUFFERED,this.onFragBuffered,this)}_unregisterListeners(){let{hls:e}=this;e.off(Yf.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(Yf.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(Yf.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Yf.LEVEL_LOADED,this.onLevelLoaded,this),e.off(Yf.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.off(Yf.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(Yf.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(Yf.ERROR,this.onError,this),e.off(Yf.BUFFER_RESET,this.onBufferReset,this),e.off(Yf.BUFFER_CREATED,this.onBufferCreated,this),e.off(Yf.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(Yf.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(Yf.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(Yf.FRAG_BUFFERED,this.onFragBuffered,this)}onInitPtsFound(e,{frag:t,id:i,initPTS:r,timescale:s}){if("main"===i){let e=t.cc;this.initPTS[t.cc]={baseTime:r,timescale:s},this.log(`InitPTS for cc: ${e} found from main: ${r}`),this.videoTrackCC=e,this.state===eE&&this.tick()}}startLoad(e){if(!this.levels)return this.startPosition=e,void(this.state=Vv);let t=this.lastCurrentTime;this.stopLoad(),this.setInterval(100),t>0&&-1===e?(this.log(`Override startPosition with lastCurrentTime @${t.toFixed(3)}`),e=t,this.state=Kv):(this.loadedmetadata=!1,this.state=zv),this.nextLoadPosition=this.startPosition=this.lastCurrentTime=e,this.tick()}doTick(){switch(this.state){case Kv:this.doTickIdle();break;case zv:{var e;let{levels:t,trackId:i}=this,r=null==t||null==(e=t[i])?void 0:e.details;if(r){if(this.waitForCdnTuneIn(r))break;this.state=eE}break}case Yv:{var t;let e=performance.now(),i=this.retryDate;if(!i||e>=i||null!=(t=this.media)&&t.seeking){let{levels:e,trackId:t}=this;this.log("RetryDate reached, switch back to IDLE state"),this.resetStartWhenNotLoaded(e?.[t]||null),this.state=Kv}break}case eE:{let e=this.waitingData;if(e){let{frag:t,part:i,cache:r,complete:s}=e;if(void 0!==this.initPTS[t.cc]){this.waitingData=null,this.waitingVideoCC=-1,this.state=qv;let e={frag:t,part:i,payload:r.flush(),networkDetails:null};this._handleFragmentLoadProgress(e),s&&super._handleFragmentLoadComplete(e)}else if(this.videoTrackCC!==this.waitingVideoCC)this.log(`Waiting fragment cc (${t.cc}) cancelled because video is at cc ${this.videoTrackCC}`),this.clearWaitingFragment();else{let e=this.getLoadPosition(),i=Lv.bufferInfo(this.mediaBuffer,e,this.config.maxBufferHole);Xg(i.end,this.config.maxFragLookUpTolerance,t)<0&&(this.log(`Waiting fragment cc (${t.cc}) @ ${t.start} cancelled because another fragment at ${i.end} is needed`),this.clearWaitingFragment())}}else this.state=Kv}}this.onTickEnd()}clearWaitingFragment(){let e=this.waitingData;e&&(this.fragmentTracker.removeFragment(e.frag),this.waitingData=null,this.waitingVideoCC=-1,this.state=Kv)}resetLoadingState(){this.clearWaitingFragment(),super.resetLoadingState()}onTickEnd(){let{media:e}=this;null!=e&&e.readyState&&(this.lastCurrentTime=e.currentTime)}doTickIdle(){let{hls:e,levels:t,media:i,trackId:r}=this,s=e.config;if(!i&&(this.startFragRequested||!s.startFragPrefetch)||null==t||!t[r])return;let n=t[r],a=n.details;if(!a||a.live&&this.levelLastLoaded!==n||this.waitForCdnTuneIn(a))return void(this.state=zv);let o=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&o&&(this.bufferFlushed=!1,this.afterBufferFlushed(o,hp,ag));let l=this.getFwdBufferInfo(o,ag);if(null===l)return;let{bufferedTrack:h,switchingTrack:d}=this;if(!d&&this._streamEnded(l,a))return e.trigger(Yf.BUFFER_EOS,{type:"audio"}),void(this.state=Zv);let u=this.getFwdBufferInfo(this.videoBuffer?this.videoBuffer:this.media,ng),c=l.len,f=this.getMaxBufferLength(u?.len),p=a.fragments,m=p[0].start,g=this.flushing?this.getLoadPosition():l.end;if(d&&i){let e=this.getLoadPosition();h&&!hy(d.attrs,h.attrs)&&(g=e),a.PTSKnown&&e<m&&(l.end>m||l.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),i.currentTime=m+.05)}if(c>=f&&!d&&g<p[p.length-1].start)return;let v=this.getNextFragment(g,a),E=!1;if(v&&this.isLoopLoading(v,g)&&(E=!!v.gap,v=this.getNextFragmentLoopLoading(v,a,l,ng,f)),!v)return void(this.bufferFlushed=!0);let y=u&&v.start>u.end+a.targetduration;if(y||(null==u||!u.len)&&l.len){let e=this.getAppendedFrag(v.start,ng);if(null===e||(E||(E=!!e.gap||!!y&&0===u.len),y&&!E||E&&l.nextStart&&l.nextStart<e.end))return}this.loadFragment(v,n,g)}getMaxBufferLength(e){let t=super.getMaxBufferLength();return e?Math.min(Math.max(t,e),this.config.maxMaxBufferLength):t}onMediaDetaching(){this.videoBuffer=null,this.bufferFlushed=this.flushing=!1,super.onMediaDetaching()}onAudioTracksUpdated(e,{audioTracks:t}){this.resetTransmuxer(),this.levels=t.map((e=>new Mg(e)))}onAudioTrackSwitching(e,t){let i=!!t.url;this.trackId=t.id;let{fragCurrent:r}=this;r&&(r.abortRequests(),this.removeUnbufferedFrags(r.start)),this.resetLoadingState(),i?this.setInterval(100):this.resetTransmuxer(),i?(this.switchingTrack=t,this.state=Kv,this.flushAudioIfNeeded(t)):(this.switchingTrack=null,this.bufferedTrack=t,this.state=Vv),this.tick()}onManifestLoading(){this.fragmentTracker.removeAllFragments(),this.startPosition=this.lastCurrentTime=0,this.bufferFlushed=this.flushing=!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(e,t){this.mainDetails=t.details,null!==this.cachedTrackLoadedData&&(this.hls.trigger(Yf.AUDIO_TRACK_LOADED,this.cachedTrackLoadedData),this.cachedTrackLoadedData=null)}onAudioTrackLoaded(e,t){var i;if(null==this.mainDetails)return void(this.cachedTrackLoadedData=t);let{levels:r}=this,{details:s,id:n}=t;if(!r)return void this.warn(`Audio tracks were reset while loading level ${n}`);this.log(`Audio track ${n} loaded [${s.startSN},${s.endSN}]${s.lastPartSn?`[part-${s.lastPartSn}-${s.lastPartIndex}]`:""},duration:${s.totalduration}`);let a=r[n],o=0;if(s.live||null!=(i=a.details)&&i.live){this.checkLiveUpdate(s);let e=this.mainDetails;if(s.deltaUpdateFailed||!e)return;var l;if(!a.details&&s.hasProgramDateTime&&e.hasProgramDateTime)Mv(s,e),o=s.fragments[0].start;else o=this.alignPlaylists(s,a.details,null==(l=this.levelLastLoaded)?void 0:l.details)}a.details=s,this.levelLastLoaded=a,!this.startFragRequested&&(this.mainDetails||!s.live)&&this.setStartPosition(this.mainDetails||s,o),this.state===zv&&!this.waitForCdnTuneIn(s)&&(this.state=Kv),this.tick()}_handleFragmentLoadProgress(e){var t;let{frag:i,part:r,payload:s}=e,{config:n,trackId:a,levels:o}=this;if(!o)return void this.warn(`Audio tracks were reset while fragment load was in progress. Fragment ${i.sn} of level ${i.level} will not be buffered`);let l=o[a];if(!l)return void this.warn("Audio track is undefined on fragment load progress");let h=l.details;if(!h)return this.warn("Audio track details undefined on fragment load progress"),void this.removeUnbufferedFrags(i.start);let d=n.defaultAudioCodec||l.audioCodec||"mp4a.40.2",u=this.transmuxer;u||(u=this.transmuxer=new oy(this.hls,ag,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));let c=this.initPTS[i.cc],f=null==(t=i.initSegment)?void 0:t.data;if(void 0!==c){let e=r?r.index:-1,t=-1!==e,n=new Rv(i.level,i.sn,i.stats.chunkCount,s.byteLength,e,t);u.push(s,f,d,"",i,r,h.totalduration,!1,n,c)}else{this.log(`Unknown video PTS for cc ${i.cc}, waiting for video PTS before demuxing audio frag ${i.sn} of [${h.startSN} ,${h.endSN}],track ${a}`);let{cache:e}=this.waitingData=this.waitingData||{frag:i,part:r,cache:new rE,complete:!1};e.push(new Uint8Array(s)),this.waitingVideoCC=this.videoTrackCC,this.state=eE}}_handleFragmentLoadComplete(e){this.waitingData?this.waitingData.complete=!0:super._handleFragmentLoadComplete(e)}onBufferReset(){this.mediaBuffer=this.videoBuffer=null,this.loadedmetadata=!1}onBufferCreated(e,t){let i=t.tracks.audio;i&&(this.mediaBuffer=i.buffer||null),t.tracks.video&&(this.videoBuffer=t.tracks.video.buffer||null)}onFragBuffered(e,t){let{frag:i,part:r}=t;if(i.type===ag)if(this.fragContextChanged(i))this.warn(`Fragment ${i.sn}${r?" p: "+r.index:""} of level ${i.level} finished buffering, but was aborted. state: ${this.state}, audioSwitch: ${this.switchingTrack?this.switchingTrack.name:"false"}`);else{if("initSegment"!==i.sn){this.fragPrevious=i;let e=this.switchingTrack;e&&(this.bufferedTrack=e,this.switchingTrack=null,this.hls.trigger(Yf.AUDIO_TRACK_SWITCHED,Hf({},e)))}this.fragBufferedComplete(i,r)}else if(!this.loadedmetadata&&i.type===ng){let e=this.videoBuffer||this.media;e&&Lv.getBuffered(e).length&&(this.loadedmetadata=!0)}}onError(e,t){var i;if(t.fatal)this.state=Jv;else switch(t.details){case Xf.FRAG_GAP:case Xf.FRAG_PARSING_ERROR:case Xf.FRAG_DECRYPT_ERROR:case Xf.FRAG_LOAD_ERROR:case Xf.FRAG_LOAD_TIMEOUT:case Xf.KEY_LOAD_ERROR:case Xf.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(ag,t);break;case Xf.AUDIO_TRACK_LOAD_ERROR:case Xf.AUDIO_TRACK_LOAD_TIMEOUT:case Xf.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===zv&&(null==(i=t.context)?void 0:i.type)===rg&&(this.state=Kv);break;case Xf.BUFFER_APPEND_ERROR:case Xf.BUFFER_FULL_ERROR:if(!t.parent||"audio"!==t.parent)return;if(t.details===Xf.BUFFER_APPEND_ERROR)return void this.resetLoadingState();this.reduceLengthAndFlushBuffer(t)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case Xf.INTERNAL_EXCEPTION:this.recoverWorkerError(t)}}onBufferFlushing(e,{type:t}){t!==dp&&(this.flushing=!0)}onBufferFlushed(e,{type:t}){if(t!==dp){this.flushing=!1,this.bufferFlushed=!0,this.state===Zv&&(this.state=Kv);let e=this.mediaBuffer||this.media;e&&(this.afterBufferFlushed(e,t,ag),this.tick())}}_handleTransmuxComplete(e){var t;let i="audio",{hls:r}=this,{remuxResult:s,chunkMeta:n}=e,a=this.getCurrentContext(n);if(!a)return void this.resetWhenMissingContext(n);let{frag:o,part:l,level:h}=a,{details:d}=h,{audio:u,text:c,id3:f,initSegment:p}=s;if(!this.fragContextChanged(o)&&d){if(this.state=Xv,this.switchingTrack&&u&&this.completeAudioSwitch(this.switchingTrack),null!=p&&p.tracks){let e=o.initSegment||o;this._bufferInitSegment(h,p.tracks,e,n),r.trigger(Yf.FRAG_PARSING_INIT_SEGMENT,{frag:e,id:i,tracks:p.tracks})}if(u){let{startPTS:e,endPTS:t,startDTS:i,endDTS:r}=u;l&&(l.elementaryStreams[hp]={startPTS:e,endPTS:t,startDTS:i,endDTS:r}),o.setElementaryStreamInfo(hp,e,t,i,r),this.bufferFragmentData(u,o,l,n)}if(null!=f&&null!=(t=f.samples)&&t.length){let e=Vf({id:i,frag:o,details:d},f);r.trigger(Yf.FRAG_PARSING_METADATA,e)}if(c){let e=Vf({id:i,frag:o,details:d},c);r.trigger(Yf.FRAG_PARSING_USERDATA,e)}}else this.fragmentTracker.removeFragment(o)}_bufferInitSegment(e,t,i,r){if(this.state!==Xv)return;t.video&&delete t.video;let s=t.audio;if(!s)return;s.id="audio";let n=e.audioCodec;this.log(`Init audio buffer, container:${s.container}, codecs[level/parsed]=[${n}/${s.codec}]`),n&&1===n.split(",").length&&(s.levelCodec=n),this.hls.trigger(Yf.BUFFER_CODECS,t);let a=s.initSegment;if(null!=a&&a.byteLength){let e={type:"audio",frag:i,part:null,chunkMeta:r,parent:i.type,data:a};this.hls.trigger(Yf.BUFFER_APPENDING,e)}this.tickImmediate()}loadFragment(e,t,i){let r=this.fragmentTracker.getState(e);var s;if(this.fragCurrent=e,this.switchingTrack||r===yv||r===Tv)if("initSegment"===e.sn)this._loadInitSegment(e,t);else if(null!=(s=t.details)&&s.live&&!this.initPTS[e.cc]){this.log(`Waiting for video PTS in continuity counter ${e.cc} of live stream before loading audio fragment ${e.sn} of level ${this.trackId}`),this.state=eE;let i=this.mainDetails;i&&i.fragments[0].start!==t.details.fragments[0].start&&Mv(t.details,i)}else this.startFragRequested=!0,super.loadFragment(e,t,i);else this.clearTrackerIfNeeded(e)}flushAudioIfNeeded(e){let{media:t,bufferedTrack:i}=this,r=i?.attrs,s=e.attrs;t&&r&&(r.CHANNELS!==s.CHANNELS||i.name!==e.name||i.lang!==e.lang)&&(this.log("Switching audio track : flushing all audio"),super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"),this.bufferedTrack=null)}completeAudioSwitch(e){let{hls:t}=this;this.flushAudioIfNeeded(e),this.bufferedTrack=e,this.switchingTrack=null,t.trigger(Yf.AUDIO_TRACK_SWITCHED,Hf({},e))}},audioTrackController:class extends nv{constructor(e){super(e,"[audio-track-controller]"),this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.registerListeners()}registerListeners(){let{hls:e}=this;e.on(Yf.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Yf.MANIFEST_PARSED,this.onManifestParsed,this),e.on(Yf.LEVEL_LOADING,this.onLevelLoading,this),e.on(Yf.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(Yf.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(Yf.ERROR,this.onError,this)}unregisterListeners(){let{hls:e}=this;e.off(Yf.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Yf.MANIFEST_PARSED,this.onManifestParsed,this),e.off(Yf.LEVEL_LOADING,this.onLevelLoading,this),e.off(Yf.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(Yf.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(Yf.ERROR,this.onError,this)}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,super.destroy()}onManifestLoading(){this.tracks=[],this.tracksInGroup=[],this.groupIds=null,this.currentTrack=null,this.trackId=-1,this.selectDefaultTrack=!0}onManifestParsed(e,t){this.tracks=t.audioTracks||[]}onAudioTrackLoaded(e,t){let{id:i,groupId:r,details:s}=t,n=this.tracksInGroup[i];if(!n||n.groupId!==r)return void this.warn(`Audio track with id:${i} and group:${r} not found in active group ${n?.groupId}`);let a=n.details;n.details=t.details,this.log(`Audio track ${i} "${n.name}" lang:${n.lang} group:${r} loaded [${s.startSN}-${s.endSN}]`),i===this.trackId&&this.playlistLoaded(i,t,a)}onLevelLoading(e,t){this.switchLevel(t.level)}onLevelSwitching(e,t){this.switchLevel(t.level)}switchLevel(e){let t=this.hls.levels[e];if(!t)return;let i=t.audioGroups||null,r=this.groupIds,s=this.currentTrack;if(!i||r?.length!==i?.length||null!=i&&i.some((e=>-1===r?.indexOf(e)))){this.groupIds=i,this.trackId=-1,this.currentTrack=null;let e=this.tracks.filter((e=>!i||-1!==i.indexOf(e.groupId)));if(e.length)this.selectDefaultTrack&&!e.some((e=>e.default))&&(this.selectDefaultTrack=!1),e.forEach(((e,t)=>{e.id=t}));else if(!s&&!this.tracksInGroup.length)return;this.tracksInGroup=e;let t=this.hls.config.audioPreference;if(!s&&t){let i=pv(t,e,gv);if(i>-1)s=e[i];else{let e=pv(t,this.tracks);s=this.tracks[e]}}let r=this.findTrackId(s);-1===r&&s&&(r=this.findTrackId(null));let a={audioTracks:e};this.log(`Updating audio tracks, ${e.length} track(s) found in group(s): ${i?.join(",")}`),this.hls.trigger(Yf.AUDIO_TRACKS_UPDATED,a);let o=this.trackId;if(-1!==r&&-1===o)this.setAudioTrack(r);else if(e.length&&-1===o){var n;let t=new Error(`No audio track selected for current audio group-ID(s): ${null==(n=this.groupIds)?void 0:n.join(",")} track count: ${e.length}`);this.warn(t.message),this.hls.trigger(Yf.ERROR,{type:zf.MEDIA_ERROR,details:Xf.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:t})}}else this.shouldReloadPlaylist(s)&&this.setAudioTrack(this.trackId)}onError(e,t){t.fatal||!t.context||t.context.type===rg&&t.context.id===this.trackId&&(!this.groupIds||-1!==this.groupIds.indexOf(t.context.groupId))&&(this.requestScheduled=-1,this.checkRetry(t))}get allAudioTracks(){return this.tracks}get audioTracks(){return this.tracksInGroup}get audioTrack(){return this.trackId}set audioTrack(e){this.selectDefaultTrack=!1,this.setAudioTrack(e)}setAudioOption(e){let t=this.hls;if(t.config.audioPreference=e,e){let i=this.allAudioTracks;if(this.selectDefaultTrack=!1,i.length){let r=this.currentTrack;if(r&&mv(e,r,gv))return r;let s=pv(e,this.tracksInGroup,gv);if(s>-1){let e=this.tracksInGroup[s];return this.setAudioTrack(s),e}if(r){let r=t.loadLevel;-1===r&&(r=t.firstAutoLevel);let s=function(e,t,i,r,s){let n=t[r],a=t.reduce(((e,t,i)=>{let r=t.uri;return(e[r]||(e[r]=[])).push(i),e}),{})[n.uri];a.length>1&&(r=Math.max.apply(Math,a));let o=n.videoRange,l=n.frameRate,h=n.codecSet.substring(0,4),d=vv(t,r,(t=>{if(t.videoRange!==o||t.frameRate!==l||t.codecSet.substring(0,4)!==h)return!1;let r=t.audioGroups,n=i.filter((e=>!r||-1!==r.indexOf(e.groupId)));return pv(e,n,s)>-1}));return d>-1?d:vv(t,r,(t=>{let r=t.audioGroups,n=i.filter((e=>!r||-1!==r.indexOf(e.groupId)));return pv(e,n,s)>-1}))}(e,t.levels,i,r,gv);if(-1===s)return null;t.nextLoadLevel=s}if(e.channels||e.audioCodec){let t=pv(e,i);if(t>-1)return i[t]}}}return null}setAudioTrack(e){let t=this.tracksInGroup;if(e<0||e>=t.length)return void this.warn(`Invalid audio track id: ${e}`);this.clearTimer(),this.selectDefaultTrack=!1;let i=this.currentTrack,r=t[e],s=r.details&&!r.details.live;if(e===this.trackId&&r===i&&s||(this.log(`Switching to audio-track ${e} "${r.name}" lang:${r.lang} group:${r.groupId} channels:${r.channels}`),this.trackId=e,this.currentTrack=r,this.hls.trigger(Yf.AUDIO_TRACK_SWITCHING,Hf({},r)),s))return;let n=this.switchParams(r.url,i?.details,r.details);this.loadPlaylist(n)}findTrackId(e){let t=this.tracksInGroup;for(let i=0;i<t.length;i++){let r=t[i];if((!this.selectDefaultTrack||r.default)&&(!e||mv(e,r,gv)))return i}if(e){let{name:i,lang:r,assocLang:s,characteristics:n,audioCodec:a,channels:o}=e;for(let e=0;e<t.length;e++){if(mv({name:i,lang:r,assocLang:s,characteristics:n,audioCodec:a,channels:o},t[e],gv))return e}for(let i=0;i<t.length;i++){let r=t[i];if(hy(e.attrs,r.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return i}for(let i=0;i<t.length;i++){let r=t[i];if(hy(e.attrs,r.attrs,["LANGUAGE"]))return i}}return-1}loadPlaylist(e){let t=this.currentTrack;if(this.shouldLoadPlaylist(t)&&t){super.loadPlaylist();let i=t.id,r=t.groupId,s=t.url;if(e)try{s=e.addDirectives(s)}catch(e){this.warn(`Could not construct new URL with HLS Delivery Directives: ${e}`)}this.log(`loading audio-track playlist ${i} "${t.name}" lang:${t.lang} group:${r}`),this.clearTimer(),this.hls.trigger(Yf.AUDIO_TRACK_LOADING,{url:s,id:i,groupId:r,deliveryDirectives:e||null})}}},emeController:ub,cmcdController:class{constructor(e){this.hls=void 0,this.config=void 0,this.media=void 0,this.sid=void 0,this.cid=void 0,this.useHeaders=!1,this.includeKeys=void 0,this.initialized=!1,this.starved=!1,this.buffering=!0,this.audioBuffer=void 0,this.videoBuffer=void 0,this.onWaiting=()=>{this.initialized&&(this.starved=!0),this.buffering=!0},this.onPlaying=()=>{this.initialized||(this.initialized=!0),this.buffering=!1},this.applyPlaylistData=e=>{try{this.apply(e,{ot:cb.MANIFEST,su:!this.initialized})}catch(e){tp.warn("Could not generate manifest CMCD data.",e)}},this.applyFragmentData=e=>{try{let t=e.frag,i=this.hls.levels[t.level],r=this.getObjectType(t),s={d:1e3*t.duration,ot:r};(r===cb.VIDEO||r===cb.AUDIO||r==cb.MUXED)&&(s.br=i.bitrate/1e3,s.tb=this.getTopBandwidth(r)/1e3,s.bl=this.getBufferLength(r)),this.apply(e,s)}catch(e){tp.warn("Could not generate segment CMCD data.",e)}},this.hls=e;let t=this.config=e.config,{cmcd:i}=t;null!=i&&(t.pLoader=this.createPlaylistLoader(),t.fLoader=this.createFragmentLoader(),this.sid=i.sessionId||function(){try{return crypto.randomUUID()}catch{try{let e=URL.createObjectURL(new Blob),t=e.toString();return URL.revokeObjectURL(e),t.slice(t.lastIndexOf("/")+1)}catch{let e=(new Date).getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(t=>{let i=(e+16*Math.random())%16|0;return e=Math.floor(e/16),("x"==t?i:3&i|8).toString(16)}))}}}(),this.cid=i.contentId,this.useHeaders=!0===i.useHeaders,this.includeKeys=i.includeKeys,this.registerListeners())}registerListeners(){let e=this.hls;e.on(Yf.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(Yf.MEDIA_DETACHED,this.onMediaDetached,this),e.on(Yf.BUFFER_CREATED,this.onBufferCreated,this)}unregisterListeners(){let e=this.hls;e.off(Yf.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(Yf.MEDIA_DETACHED,this.onMediaDetached,this),e.off(Yf.BUFFER_CREATED,this.onBufferCreated,this)}destroy(){this.unregisterListeners(),this.onMediaDetached(),this.hls=this.config=this.audioBuffer=this.videoBuffer=null,this.onWaiting=this.onPlaying=null}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener("waiting",this.onWaiting),this.media.addEventListener("playing",this.onPlaying)}onMediaDetached(){this.media&&(this.media.removeEventListener("waiting",this.onWaiting),this.media.removeEventListener("playing",this.onPlaying),this.media=null)}onBufferCreated(e,t){var i,r;this.audioBuffer=null==(i=t.tracks.audio)?void 0:i.buffer,this.videoBuffer=null==(r=t.tracks.video)?void 0:r.buffer}createData(){var e;return{v:1,sf:fb.HLS,sid:this.sid,cid:this.cid,pr:null==(e=this.media)?void 0:e.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(e,t={}){Vf(t,this.createData());let i=t.ot===cb.INIT||t.ot===cb.VIDEO||t.ot===cb.MUXED;this.starved&&i&&(t.bs=!0,t.su=!0,this.starved=!1),null==t.su&&(t.su=this.buffering);let{includeKeys:r}=this;r&&(t=Object.keys(t).reduce(((e,i)=>(r.includes(i)&&(e[i]=t[i]),e)),{})),this.useHeaders?(e.headers||(e.headers={}),$b(e.headers,t)):e.url=Bb(e.url,t)}getObjectType(e){let{type:t}=e;return"subtitle"===t?cb.TIMED_TEXT:"initSegment"===e.sn?cb.INIT:"audio"===t?cb.AUDIO:"main"===t?this.hls.audioTracks.length?cb.VIDEO:cb.MUXED:void 0}getTopBandwidth(e){let t,i=0,r=this.hls;if(e===cb.AUDIO)t=r.audioTracks;else{let e=r.maxAutoLevel,i=e>-1?e+1:r.levels.length;t=r.levels.slice(0,i)}for(let e of t)e.bitrate>i&&(i=e.bitrate);return i>0?i:NaN}getBufferLength(e){let t=this.hls.media,i=e===cb.AUDIO?this.audioBuffer:this.videoBuffer;return i&&t?1e3*Lv.bufferInfo(i,t.currentTime,this.config.maxBufferHole).len:NaN}createPlaylistLoader(){let{pLoader:e}=this.config,t=this.applyPlaylistData,i=e||this.config.loader;return class{constructor(e){this.loader=void 0,this.loader=new i(e)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(e,i,r){t(e),this.loader.load(e,i,r)}}}createFragmentLoader(){let{fLoader:e}=this.config,t=this.applyFragmentData,i=e||this.config.loader;return class{constructor(e){this.loader=void 0,this.loader=new i(e)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(e,i,r){t(e),this.loader.load(e,i,r)}}}},contentSteeringController:class{constructor(e){this.hls=void 0,this.log=void 0,this.loader=null,this.uri=null,this.pathwayId=".",this.pathwayPriority=null,this.timeToLoad=300,this.reloadTimer=-1,this.updated=0,this.started=!1,this.enabled=!0,this.levels=null,this.audioTracks=null,this.subtitleTracks=null,this.penalizedPathways={},this.hls=e,this.log=tp.log.bind(tp,"[content-steering]:"),this.registerListeners()}registerListeners(){let e=this.hls;e.on(Yf.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Yf.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(Yf.MANIFEST_PARSED,this.onManifestParsed,this),e.on(Yf.ERROR,this.onError,this)}unregisterListeners(){let e=this.hls;e&&(e.off(Yf.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Yf.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(Yf.MANIFEST_PARSED,this.onManifestParsed,this),e.off(Yf.ERROR,this.onError,this))}startLoad(){if(this.started=!0,this.clearTimeout(),this.enabled&&this.uri){if(this.updated){let e=1e3*this.timeToLoad-(performance.now()-this.updated);if(e>0)return void this.scheduleRefresh(this.uri,e)}this.loadSteeringManifest(this.uri)}}stopLoad(){this.started=!1,this.loader&&(this.loader.destroy(),this.loader=null),this.clearTimeout()}clearTimeout(){-1!==this.reloadTimer&&(self.clearTimeout(this.reloadTimer),this.reloadTimer=-1)}destroy(){this.unregisterListeners(),this.stopLoad(),this.hls=null,this.levels=this.audioTracks=this.subtitleTracks=null}removeLevel(e){let t=this.levels;t&&(this.levels=t.filter((t=>t!==e)))}onManifestLoading(){this.stopLoad(),this.enabled=!0,this.timeToLoad=300,this.updated=0,this.uri=null,this.pathwayId=".",this.levels=this.audioTracks=this.subtitleTracks=null}onManifestLoaded(e,t){let{contentSteering:i}=t;null!==i&&(this.pathwayId=i.pathwayId,this.uri=i.uri,this.started&&this.startLoad())}onManifestParsed(e,t){this.audioTracks=t.audioTracks,this.subtitleTracks=t.subtitleTracks}onError(e,t){let{errorAction:i}=t;if(i?.action===Jg&&i.flags===rv){let e=this.levels,r=this.pathwayPriority,s=this.pathwayId;if(t.context){let{groupId:i,pathwayId:r,type:n}=t.context;i&&e?s=this.getPathwayForGroupId(i,n,s):r&&(s=r)}s in this.penalizedPathways||(this.penalizedPathways[s]=performance.now()),!r&&e&&(r=e.reduce(((e,t)=>(-1===e.indexOf(t.pathwayId)&&e.push(t.pathwayId),e)),[])),r&&r.length>1&&(this.updatePathwayPriority(r),i.resolved=this.pathwayId!==s),i.resolved||tp.warn(`Could not resolve ${t.details} ("${t.error.message}") with content-steering for Pathway: ${s} levels: ${e&&e.length} priorities: ${JSON.stringify(r)} penalized: ${JSON.stringify(this.penalizedPathways)}`)}}filterParsedLevels(e){this.levels=e;let t=this.getLevelsForPathway(this.pathwayId);if(0===t.length){let i=e[0].pathwayId;this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${i}"`),t=this.getLevelsForPathway(i),this.pathwayId=i}return t.length!==e.length?(this.log(`Found ${t.length}/${e.length} levels in Pathway "${this.pathwayId}"`),t):e}getLevelsForPathway(e){return null===this.levels?[]:this.levels.filter((t=>e===t.pathwayId))}updatePathwayPriority(e){this.pathwayPriority=e;let t,i=this.penalizedPathways,r=performance.now();Object.keys(i).forEach((e=>{r-i[e]>3e5&&delete i[e]}));for(let r=0;r<e.length;r++){let s=e[r];if(s in i)continue;if(s===this.pathwayId)return;let n=this.hls.nextLoadLevel,a=this.hls.levels[n];if(t=this.getLevelsForPathway(s),t.length>0){this.log(`Setting Pathway to "${s}"`),this.pathwayId=s,Gg(t),this.hls.trigger(Yf.LEVELS_UPDATED,{levels:t});let e=this.hls.levels[n];a&&e&&this.levels&&(e.attrs["STABLE-VARIANT-ID"]!==a.attrs["STABLE-VARIANT-ID"]&&e.bitrate!==a.bitrate&&this.log(`Unstable Pathways change from bitrate ${a.bitrate} to ${e.bitrate}`),this.hls.nextLoadLevel=n);break}}}getPathwayForGroupId(e,t,i){let r=this.getLevelsForPathway(i).concat(this.levels||[]);for(let i=0;i<r.length;i++)if(t===rg&&r[i].hasAudioGroup(e)||t===sg&&r[i].hasSubtitleGroup(e))return r[i].pathwayId;return i}clonePathways(e){let t=this.levels;if(!t)return;let i={},r={};e.forEach((e=>{let{ID:s,"BASE-ID":n,"URI-REPLACEMENT":a}=e;if(t.some((e=>e.pathwayId===s)))return;let o=this.getLevelsForPathway(n).map((e=>{let t=new sp(e.attrs);t["PATHWAY-ID"]=s;let n=t.AUDIO&&`${t.AUDIO}_clone_${s}`,o=t.SUBTITLES&&`${t.SUBTITLES}_clone_${s}`;n&&(i[t.AUDIO]=n,t.AUDIO=n),o&&(r[t.SUBTITLES]=o,t.SUBTITLES=o);let l=Gb(e.uri,t["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",a),h=new Mg({attrs:t,audioCodec:e.audioCodec,bitrate:e.bitrate,height:e.height,name:e.name,url:l,videoCodec:e.videoCodec,width:e.width});if(e.audioGroups)for(let t=1;t<e.audioGroups.length;t++)h.addGroupId("audio",`${e.audioGroups[t]}_clone_${s}`);if(e.subtitleGroups)for(let t=1;t<e.subtitleGroups.length;t++)h.addGroupId("text",`${e.subtitleGroups[t]}_clone_${s}`);return h}));t.push(...o),Hb(this.audioTracks,i,a,s),Hb(this.subtitleTracks,r,a,s)}))}loadSteeringManifest(e){let t,i=this.hls.config,r=i.loader;this.loader&&this.loader.destroy(),this.loader=new r(i);try{t=new self.URL(e)}catch{return this.enabled=!1,void this.log(`Failed to parse Steering Manifest URI: ${e}`)}if("data:"!==t.protocol){let e=0|(this.hls.bandwidthEstimate||i.abrEwmaDefaultEstimate);t.searchParams.set("_HLS_pathway",this.pathwayId),t.searchParams.set("_HLS_throughput",""+e)}let s={responseType:"json",url:t.href},n=i.steeringManifestLoadPolicy.default,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:(e,i,r,s)=>{this.log(`Loaded steering manifest: "${t}"`);let n=e.data;if(1!==n.VERSION)return void this.log(`Steering VERSION ${n.VERSION} not supported!`);this.updated=performance.now(),this.timeToLoad=n.TTL;let{"RELOAD-URI":a,"PATHWAY-CLONES":o,"PATHWAY-PRIORITY":l}=n;if(a)try{this.uri=new self.URL(a,t).href}catch{return this.enabled=!1,void this.log(`Failed to parse Steering Manifest RELOAD-URI: ${a}`)}this.scheduleRefresh(this.uri||r.url),o&&this.clonePathways(o);let h={steeringManifest:n,url:t.toString()};this.hls.trigger(Yf.STEERING_MANIFEST_LOADED,h),l&&this.updatePathwayPriority(l)},onError:(e,t,i,r)=>{if(this.log(`Error loading steering manifest: ${e.code} ${e.text} (${t.url})`),this.stopLoad(),410===e.code)return this.enabled=!1,void this.log(`Steering manifest ${t.url} no longer available`);let s=1e3*this.timeToLoad;if(429!==e.code)this.scheduleRefresh(this.uri||t.url,s);else{let e=this.loader;if("function"==typeof e?.getResponseHeader){let t=e.getResponseHeader("Retry-After");t&&(s=1e3*parseFloat(t))}this.log(`Steering manifest ${t.url} rate limited`)}},onTimeout:(e,t,i)=>{this.log(`Timeout loading steering manifest (${t.url})`),this.scheduleRefresh(this.uri||t.url)}};this.log(`Requesting steering manifest: ${t}`),this.loader.load(s,o,l)}scheduleRefresh(e,t=1e3*this.timeToLoad){this.clearTimeout(),this.reloadTimer=self.setTimeout((()=>{var t;let i=null==(t=this.hls)?void 0:t.media;!i||i.ended?this.scheduleRefresh(e,1e3*this.timeToLoad):this.loadSteeringManifest(e)}),t)}}});function Zb(e){return e&&"object"==typeof e?Array.isArray(e)?e.map(Zb):Object.keys(e).reduce(((t,i)=>(t[i]=Zb(e[i]),t)),{}):e}function Jb(e){let t=e.loader;t!==Wb&&t!==Vb?(tp.log("[config]: Custom loader detected, cannot enable progressive streaming"),e.progressive=!1):function(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch{}return!1}()&&(e.loader=Wb,e.progressive=!0,e.enableSoftwareAES=!0,tp.log("[config]: Progressive streaming enabled, using FetchLoader"))}var eT,tT=class extends nv{constructor(e,t){super(e,"[level-controller]"),this._levels=[],this._firstLevel=-1,this._maxAutoLevel=-1,this._startLevel=void 0,this.currentLevel=null,this.currentLevelIndex=-1,this.manualLevelIndex=-1,this.steering=void 0,this.onParsedComplete=void 0,this.steering=t,this._registerListeners()}_registerListeners(){let{hls:e}=this;e.on(Yf.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Yf.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(Yf.LEVEL_LOADED,this.onLevelLoaded,this),e.on(Yf.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(Yf.FRAG_BUFFERED,this.onFragBuffered,this),e.on(Yf.ERROR,this.onError,this)}_unregisterListeners(){let{hls:e}=this;e.off(Yf.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Yf.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(Yf.LEVEL_LOADED,this.onLevelLoaded,this),e.off(Yf.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(Yf.FRAG_BUFFERED,this.onFragBuffered,this),e.off(Yf.ERROR,this.onError,this)}destroy(){this._unregisterListeners(),this.steering=null,this.resetLevels(),super.destroy()}stopLoad(){this._levels.forEach((e=>{e.loadError=0,e.fragmentError=0})),super.stopLoad()}resetLevels(){this._startLevel=void 0,this.manualLevelIndex=-1,this.currentLevelIndex=-1,this.currentLevel=null,this._levels=[],this._maxAutoLevel=-1}onManifestLoading(e,t){this.resetLevels()}onManifestLoaded(e,t){let i=this.hls.config.preferManagedMediaSource,r=[],s={},n={},a=!1,o=!1,l=!1;t.levels.forEach((e=>{var t,h;let d=e.attrs,{audioCodec:u,videoCodec:c}=e;-1!==(null==(t=u)?void 0:t.indexOf("mp4a.40.34"))&&(eT||(eT=/chrome|firefox/i.test(navigator.userAgent)),eT&&(e.audioCodec=u=void 0)),u&&(e.audioCodec=u=Bm(u,i)),0===(null==(h=c)?void 0:h.indexOf("avc1"))&&(c=e.videoCodec=function(e){let t=e.split(",");for(let e=0;e<t.length;e++){let i=t[e].split(".");if(i.length>2){let r=i.shift()+".";r+=parseInt(i.shift()).toString(16),r+=("000"+parseInt(i.shift()).toString(16)).slice(-4),t[e]=r}}return t.join(",")}(c));let{width:f,height:p,unknownCodecs:m}=e;if(a||(a=!(!f||!p)),o||(o=!!c),l||(l=!!u),null!=m&&m.length||u&&!Mm(u,"audio",i)||c&&!Mm(c,"video",i))return;let{CODECS:g,"FRAME-RATE":v,"HDCP-LEVEL":E,"PATHWAY-ID":y,RESOLUTION:b,"VIDEO-RANGE":T}=d,S=`${y||"."}-${e.bitrate}-${b}-${v}-${g}-${T}-${E}`;if(s[S])if(s[S].uri===e.url||e.attrs["PATHWAY-ID"])s[S].addGroupId("audio",d.AUDIO),s[S].addGroupId("text",d.SUBTITLES);else{let t=n[S]+=1;e.attrs["PATHWAY-ID"]=new Array(t+1).join(".");let i=new Mg(e);s[S]=i,r.push(i)}else{let t=new Mg(e);s[S]=t,n[S]=1,r.push(t)}})),this.filterAndSortMediaOptions(r,t,a,o,l)}filterAndSortMediaOptions(e,t,i,r,s){let n=[],a=[],o=e;if((i||r)&&s&&(o=o.filter((({videoCodec:e,videoRange:t,width:i,height:r})=>(!!e||!(!i||!r))&&function(e){return!!e&&Lg.indexOf(e)>-1}(t)))),0===o.length)return void Promise.resolve().then((()=>{if(this.hls){t.levels.length&&this.warn(`One or more CODECS in variant not supported: ${JSON.stringify(t.levels[0].attrs)}`);let e=new Error("no level with compatible codecs found in manifest");this.hls.trigger(Yf.ERROR,{type:zf.MEDIA_ERROR,details:Xf.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:t.url,error:e,reason:e.message})}}));if(t.audioTracks){let{preferManagedMediaSource:e}=this.hls.config;n=t.audioTracks.filter((t=>!t.audioCodec||Mm(t.audioCodec,"audio",e))),iT(n)}t.subtitles&&(a=t.subtitles,iT(a));let l=o.slice(0);o.sort(((e,t)=>{if(e.attrs["HDCP-LEVEL"]!==t.attrs["HDCP-LEVEL"])return(e.attrs["HDCP-LEVEL"]||"")>(t.attrs["HDCP-LEVEL"]||"")?1:-1;if(i&&e.height!==t.height)return e.height-t.height;if(e.frameRate!==t.frameRate)return e.frameRate-t.frameRate;if(e.videoRange!==t.videoRange)return Lg.indexOf(e.videoRange)-Lg.indexOf(t.videoRange);if(e.videoCodec!==t.videoCodec){let i=Um(e.videoCodec),r=Um(t.videoCodec);if(i!==r)return r-i}if(e.uri===t.uri&&e.codecSet!==t.codecSet){let i=Nm(e.codecSet),r=Nm(t.codecSet);if(i!==r)return r-i}return e.averageBitrate!==t.averageBitrate?e.averageBitrate-t.averageBitrate:0}));let h=l[0];if(this.steering&&(o=this.steering.filterParsedLevels(o),o.length!==l.length))for(let e=0;e<l.length;e++)if(l[e].pathwayId===o[0].pathwayId){h=l[e];break}this._levels=o;for(let e=0;e<o.length;e++)if(o[e]===h){var d;this._firstLevel=e;let t=h.bitrate,i=this.hls.bandwidthEstimate;if(this.log(`manifest loaded, ${o.length} level(s) found, first bitrate: ${t}`),void 0===(null==(d=this.hls.userConfig)?void 0:d.abrEwmaDefaultEstimate)){let e=Math.min(t,this.hls.config.abrEwmaDefaultEstimateMax);e>i&&i===Qb.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=e)}break}let u=s&&!r,c={levels:o,audioTracks:n,subtitleTracks:a,sessionData:t.sessionData,sessionKeys:t.sessionKeys,firstLevel:this._firstLevel,stats:t.stats,audio:s,video:r,altAudio:!u&&n.some((e=>!!e.url))};this.hls.trigger(Yf.MANIFEST_PARSED,c),(this.hls.config.autoStartLoad||this.hls.forceStartLoad)&&this.hls.startLoad(this.hls.config.startPosition)}get levels(){return 0===this._levels.length?null:this._levels}get level(){return this.currentLevelIndex}set level(e){let t=this._levels;if(0===t.length)return;if(e<0||e>=t.length){let i=new Error("invalid level idx"),r=e<0;if(this.hls.trigger(Yf.ERROR,{type:zf.OTHER_ERROR,details:Xf.LEVEL_SWITCH_ERROR,level:e,fatal:r,error:i,reason:i.message}),r)return;e=Math.min(e,t.length-1)}let i=this.currentLevelIndex,r=this.currentLevel,s=r?r.attrs["PATHWAY-ID"]:void 0,n=t[e],a=n.attrs["PATHWAY-ID"];if(this.currentLevelIndex=e,this.currentLevel=n,i===e&&n.details&&r&&s===a)return;this.log(`Switching to level ${e} (${n.height?n.height+"p ":""}${n.videoRange?n.videoRange+" ":""}${n.codecSet?n.codecSet+" ":""}@${n.bitrate})${a?" with Pathway "+a:""} from level ${i}${s?" with Pathway "+s:""}`);let o={level:e,attrs:n.attrs,details:n.details,bitrate:n.bitrate,averageBitrate:n.averageBitrate,maxBitrate:n.maxBitrate,realBitrate:n.realBitrate,width:n.width,height:n.height,codecSet:n.codecSet,audioCodec:n.audioCodec,videoCodec:n.videoCodec,audioGroups:n.audioGroups,subtitleGroups:n.subtitleGroups,loaded:n.loaded,loadError:n.loadError,fragmentError:n.fragmentError,name:n.name,id:n.id,uri:n.uri,url:n.url,urlId:0,audioGroupIds:n.audioGroupIds,textGroupIds:n.textGroupIds};this.hls.trigger(Yf.LEVEL_SWITCHING,o);let l=n.details;if(!l||l.live){let e=this.switchParams(n.uri,r?.details,l);this.loadPlaylist(e)}}get manualLevel(){return this.manualLevelIndex}set manualLevel(e){this.manualLevelIndex=e,void 0===this._startLevel&&(this._startLevel=e),-1!==e&&(this.level=e)}get firstLevel(){return this._firstLevel}set firstLevel(e){this._firstLevel=e}get startLevel(){if(void 0===this._startLevel){let e=this.hls.config.startLevel;return void 0!==e?e:this.hls.firstAutoLevel}return this._startLevel}set startLevel(e){this._startLevel=e}onError(e,t){t.fatal||!t.context||t.context.type===ig&&t.context.level===this.level&&this.checkRetry(t)}onFragBuffered(e,{frag:t}){if(void 0!==t&&t.type===ng){let e=t.elementaryStreams;if(!Object.keys(e).some((t=>!!e[t])))return;let i=this._levels[t.level];null!=i&&i.loadError&&(this.log(`Resetting level error count of ${i.loadError} on frag buffered`),i.loadError=0)}}onLevelLoaded(e,t){var i;let{level:r,details:s}=t,n=this._levels[r];var a;if(!n)return this.warn(`Invalid level index ${r}`),void(null!=(a=t.deliveryDirectives)&&a.skip&&(s.deltaUpdateFailed=!0));r===this.currentLevelIndex?(0===n.fragmentError&&(n.loadError=0),this.playlistLoaded(r,t,n.details)):null!=(i=t.deliveryDirectives)&&i.skip&&(s.deltaUpdateFailed=!0)}loadPlaylist(e){super.loadPlaylist();let t=this.currentLevelIndex,i=this.currentLevel;if(i&&this.shouldLoadPlaylist(i)){let r=i.uri;if(e)try{r=e.addDirectives(r)}catch(e){this.warn(`Could not construct new URL with HLS Delivery Directives: ${e}`)}let s=i.attrs["PATHWAY-ID"];this.log(`Loading level index ${t}${void 0!==e?.msn?" at sn "+e.msn+" part "+e.part:""} with${s?" Pathway "+s:""} ${r}`),this.clearTimer(),this.hls.trigger(Yf.LEVEL_LOADING,{url:r,level:t,pathwayId:i.attrs["PATHWAY-ID"],id:0,deliveryDirectives:e||null})}}get nextLoadLevel(){return-1!==this.manualLevelIndex?this.manualLevelIndex:this.hls.nextAutoLevel}set nextLoadLevel(e){this.level=e,-1===this.manualLevelIndex&&(this.hls.nextAutoLevel=e)}removeLevel(e){var t;let i=this._levels.filter(((t,i)=>i!==e||(this.steering&&this.steering.removeLevel(t),t===this.currentLevel&&(this.currentLevel=null,this.currentLevelIndex=-1,t.details&&t.details.fragments.forEach((e=>e.level=-1))),!1)));Gg(i),this._levels=i,this.currentLevelIndex>-1&&null!=(t=this.currentLevel)&&t.details&&(this.currentLevelIndex=this.currentLevel.details.fragments[0].level),this.hls.trigger(Yf.LEVELS_UPDATED,{levels:i})}onLevelsUpdated(e,{levels:t}){this._levels=t}checkMaxAutoUpdated(){let{autoLevelCapping:e,maxAutoLevel:t,maxHdcpLevel:i}=this.hls;this._maxAutoLevel!==t&&(this._maxAutoLevel=t,this.hls.trigger(Yf.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:e,levels:this.levels,maxAutoLevel:t,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:i}))}};function iT(e){let t={};e.forEach((e=>{let i=e.groupId||"";e.id=t[i]=t[i]||0,t[i]++}))}var rT=class{constructor(e){this.config=void 0,this.keyUriToKeyInfo={},this.emeController=null,this.config=e}abort(e){for(let i in this.keyUriToKeyInfo){let r=this.keyUriToKeyInfo[i].loader;if(r){var t;if(e&&e!==(null==(t=r.context)?void 0:t.frag.type))return;r.abort()}}}detach(){for(let e in this.keyUriToKeyInfo){let t=this.keyUriToKeyInfo[e];(t.mediaKeySessionContext||t.decryptdata.isCommonEncryption)&&delete this.keyUriToKeyInfo[e]}}destroy(){this.detach();for(let e in this.keyUriToKeyInfo){let t=this.keyUriToKeyInfo[e].loader;t&&t.destroy()}this.keyUriToKeyInfo={}}createKeyLoadError(e,t=Xf.KEY_LOAD_ERROR,i,r,s){return new $v({type:zf.NETWORK_ERROR,details:t,fatal:!1,frag:e,response:s,error:i,networkDetails:r})}loadClear(e,t){if(this.emeController&&this.config.emeEnabled){let{sn:i,cc:r}=e;for(let e=0;e<t.length;e++){let s=t[e];if(r<=s.cc&&("initSegment"===i||"initSegment"===s.sn||i<s.sn)){this.emeController.selectKeySystemFormat(s).then((e=>{s.setKeyFormat(e)}));break}}}}load(e){return!e.decryptdata&&e.encrypted&&this.emeController?this.emeController.selectKeySystemFormat(e).then((t=>this.loadInternal(e,t))):this.loadInternal(e)}loadInternal(e,t){var i,r;t&&e.setKeyFormat(t);let s=e.decryptdata;if(!s){let i=new Error(t?`Expected frag.decryptdata to be defined after setting format ${t}`:"Missing decryption data on fragment in onKeyLoading");return Promise.reject(this.createKeyLoadError(e,Xf.KEY_LOAD_ERROR,i))}let n=s.uri;if(!n)return Promise.reject(this.createKeyLoadError(e,Xf.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${n}"`)));let a=this.keyUriToKeyInfo[n];if(null!=(i=a)&&i.decryptdata.key)return s.key=a.decryptdata.key,Promise.resolve({frag:e,keyInfo:a});var o;if(null!=(r=a)&&r.keyLoadPromise)switch(null==(o=a.mediaKeySessionContext)?void 0:o.keyStatus){case void 0:case"status-pending":case"usable":case"usable-in-future":return a.keyLoadPromise.then((t=>(s.key=t.keyInfo.decryptdata.key,{frag:e,keyInfo:a})))}switch(a=this.keyUriToKeyInfo[n]={decryptdata:s,keyLoadPromise:null,loader:null,mediaKeySessionContext:null},s.method){case"ISO-23001-7":case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return"identity"===s.keyFormat?this.loadKeyHTTP(a,e):this.loadKeyEME(a,e);case"AES-128":return this.loadKeyHTTP(a,e);default:return Promise.reject(this.createKeyLoadError(e,Xf.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${s.method}"`)))}}loadKeyEME(e,t){let i={frag:t,keyInfo:e};if(this.emeController&&this.config.emeEnabled){let t=this.emeController.loadKey(i);if(t)return(e.keyLoadPromise=t.then((t=>(e.mediaKeySessionContext=t,i)))).catch((t=>{throw e.keyLoadPromise=null,t}))}return Promise.resolve(i)}loadKeyHTTP(e,t){let i=this.config,r=new(0,i.loader)(i);return t.keyLoader=e.loader=r,e.keyLoadPromise=new Promise(((s,n)=>{let a={keyInfo:e,frag:t,responseType:"arraybuffer",url:e.decryptdata.uri},o=i.keyLoadPolicy.default,l={loadPolicy:o,timeout:o.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},h={onSuccess:(e,t,i,r)=>{let{frag:a,keyInfo:o,url:l}=i;if(!a.decryptdata||o!==this.keyUriToKeyInfo[l])return n(this.createKeyLoadError(a,Xf.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),r));o.decryptdata.key=a.decryptdata.key=new Uint8Array(e.data),a.keyLoader=null,o.loader=null,s({frag:a,keyInfo:o})},onError:(e,i,r,s)=>{this.resetLoader(i),n(this.createKeyLoadError(t,Xf.KEY_LOAD_ERROR,new Error(`HTTP Error ${e.code} loading key ${e.text}`),r,Hf({url:a.url,data:void 0},e)))},onTimeout:(e,i,r)=>{this.resetLoader(i),n(this.createKeyLoadError(t,Xf.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),r))},onAbort:(e,i,r)=>{this.resetLoader(i),n(this.createKeyLoadError(t,Xf.INTERNAL_ABORTED,new Error("key loading aborted"),r))}};r.load(a,l,h)}))}resetLoader(e){let{frag:t,keyInfo:i,url:r}=e,s=i.loader;t.keyLoader===s&&(t.keyLoader=null,i.loader=null),delete this.keyUriToKeyInfo[r],s&&s.destroy()}};function sT(){return self.SourceBuffer||self.WebKitSourceBuffer}function nT(){if(!Dm())return!1;let e=sT();return!e||e.prototype&&"function"==typeof e.prototype.appendBuffer&&"function"==typeof e.prototype.remove}var aT=class{constructor(e,t,i,r){this.config=void 0,this.media=null,this.fragmentTracker=void 0,this.hls=void 0,this.nudgeRetry=0,this.stallReported=!1,this.stalled=null,this.moved=!1,this.seeking=!1,this.config=e,this.media=t,this.fragmentTracker=i,this.hls=r}destroy(){this.media=null,this.hls=this.fragmentTracker=null}poll(e,t){let{config:i,media:r,stalled:s}=this;if(null===r)return;let{currentTime:n,seeking:a}=r,o=this.seeking&&!a,l=!this.seeking&&a;if(this.seeking=a,n!==e){if(this.moved=!0,a||(this.nudgeRetry=0),null!==s){if(this.stallReported){let e=self.performance.now()-s;tp.warn(`playback not stuck anymore @${n}, after ${Math.round(e)}ms`),this.stallReported=!1}this.stalled=null}return}if(l||o)return void(this.stalled=null);if(r.paused&&!a||r.ended||0===r.playbackRate||!Lv.getBuffered(r).length)return void(this.nudgeRetry=0);let h=Lv.bufferInfo(r,n,0),d=h.nextStart||0;if(a){let e=h.len>2,i=!d||t&&t.start<=n||d-n>2&&!this.fragmentTracker.getPartialFragment(n);if(e||i)return;this.moved=!1}if(!this.moved&&null!==this.stalled){var u;if(!(h.len>0||d))return;let e=Math.max(d,h.start||0)-n,t=this.hls.levels?this.hls.levels[this.hls.currentLevel]:null,i=(null==t||null==(u=t.details)?void 0:u.live)?2*t.details.targetduration:2,s=this.fragmentTracker.getPartialFragment(n);if(e>0&&(e<=i||s))return void(r.paused||this._trySkipBufferHole(s))}let c=self.performance.now();if(null===s)return void(this.stalled=c);let f=c-s;if(!a&&f>=250&&(this._reportStall(h),!this.media))return;let p=Lv.bufferInfo(r,n,i.maxBufferHole);this._tryFixBufferStall(p,f)}_tryFixBufferStall(e,t){let{config:i,fragmentTracker:r,media:s}=this;if(null===s)return;let n=s.currentTime,a=r.getPartialFragment(n);a&&(this._trySkipBufferHole(a)||!this.media)||(e.len>i.maxBufferHole||e.nextStart&&e.nextStart-n<i.maxBufferHole)&&t>1e3*i.highBufferWatchdogPeriod&&(tp.warn("Trying to nudge playhead over buffer-hole"),this.stalled=null,this._tryNudgeBuffer())}_reportStall(e){let{hls:t,media:i,stallReported:r}=this;if(!r&&i){this.stallReported=!0;let r=new Error(`Playback stalling at @${i.currentTime} due to low buffer (${JSON.stringify(e)})`);tp.warn(r.message),t.trigger(Yf.ERROR,{type:zf.MEDIA_ERROR,details:Xf.BUFFER_STALLED_ERROR,fatal:!1,error:r,buffer:e.len})}}_trySkipBufferHole(e){let{config:t,hls:i,media:r}=this;if(null===r)return 0;let s=r.currentTime,n=Lv.bufferInfo(r,s,0),a=s<n.start?n.start:n.nextStart;if(a){let o=n.len<=t.maxBufferHole,l=n.len>0&&n.len<1&&r.readyState<3,h=a-s;if(h>0&&(o||l)){if(h>t.maxBufferHole){let{fragmentTracker:t}=this,i=!1;if(0===s){let e=t.getAppendedFrag(0,ng);e&&a<e.end&&(i=!0)}if(!i){let i=e||t.getAppendedFrag(s,ng);if(i){let e=!1,r=i.end;for(;r<a;){let i=t.getPartialFragment(r);if(!i){e=!0;break}r+=i.duration}if(e)return 0}}}let n=Math.max(a+.05,s+.1);if(tp.warn(`skipping hole, adjusting currentTime from ${s} to ${n}`),this.moved=!0,this.stalled=null,r.currentTime=n,e&&!e.gap){let t=new Error(`fragment loaded with buffer holes, seeking from ${s} to ${n}`);i.trigger(Yf.ERROR,{type:zf.MEDIA_ERROR,details:Xf.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:t,reason:t.message,frag:e})}return n}}return 0}_tryNudgeBuffer(){let{config:e,hls:t,media:i,nudgeRetry:r}=this;if(null===i)return;let s=i.currentTime;if(this.nudgeRetry++,r<e.nudgeMaxRetry){let n=s+(r+1)*e.nudgeOffset,a=new Error(`Nudging 'currentTime' from ${s} to ${n}`);tp.warn(a.message),i.currentTime=n,t.trigger(Yf.ERROR,{type:zf.MEDIA_ERROR,details:Xf.BUFFER_NUDGE_ON_STALL,error:a,fatal:!1})}else{let i=new Error(`Playhead still not moving while enough data buffered @${s} after ${e.nudgeMaxRetry} nudges`);tp.error(i.message),t.trigger(Yf.ERROR,{type:zf.MEDIA_ERROR,details:Xf.BUFFER_STALLED_ERROR,error:i,fatal:!0})}}},oT=class extends iE{constructor(e,t,i){super(e,t,i,"[stream-controller]",ng),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(){let{hls:e}=this;e.on(Yf.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(Yf.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(Yf.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Yf.MANIFEST_PARSED,this.onManifestParsed,this),e.on(Yf.LEVEL_LOADING,this.onLevelLoading,this),e.on(Yf.LEVEL_LOADED,this.onLevelLoaded,this),e.on(Yf.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.on(Yf.ERROR,this.onError,this),e.on(Yf.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(Yf.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.on(Yf.BUFFER_CREATED,this.onBufferCreated,this),e.on(Yf.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(Yf.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(Yf.FRAG_BUFFERED,this.onFragBuffered,this)}_unregisterListeners(){let{hls:e}=this;e.off(Yf.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(Yf.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(Yf.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Yf.MANIFEST_PARSED,this.onManifestParsed,this),e.off(Yf.LEVEL_LOADED,this.onLevelLoaded,this),e.off(Yf.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.off(Yf.ERROR,this.onError,this),e.off(Yf.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(Yf.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.off(Yf.BUFFER_CREATED,this.onBufferCreated,this),e.off(Yf.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(Yf.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(Yf.FRAG_BUFFERED,this.onFragBuffered,this)}onHandlerDestroying(){this._unregisterListeners(),super.onHandlerDestroying()}startLoad(e){if(this.levels){let{lastCurrentTime:t,hls:i}=this;if(this.stopLoad(),this.setInterval(100),this.level=-1,!this.startFragRequested){let e=i.startLevel;-1===e&&(i.config.testBandwidth&&this.levels.length>1?(e=0,this.bitrateTest=!0):e=i.firstAutoLevel),i.nextLoadLevel=e,this.level=i.loadLevel,this.loadedmetadata=!1}t>0&&-1===e&&(this.log(`Override startPosition with lastCurrentTime @${t.toFixed(3)}`),e=t),this.state=Kv,this.nextLoadPosition=this.startPosition=this.lastCurrentTime=e,this.tick()}else this._forceStartLoad=!0,this.state=Vv}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case tE:{let{levels:e,level:t}=this,i=e?.[t],r=i?.details;if(r&&(!r.live||this.levelLastLoaded===i)){if(this.waitForCdnTuneIn(r))break;this.state=Kv;break}if(this.hls.nextLoadLevel!==this.level){this.state=Kv;break}break}case Yv:{var e;let t=self.performance.now(),i=this.retryDate;if(!i||t>=i||null!=(e=this.media)&&e.seeking){let{levels:e,level:t}=this,i=e?.[t];this.resetStartWhenNotLoaded(i||null),this.state=Kv}}}this.state===Kv&&this.doTickIdle(),this.onTickEnd()}onTickEnd(){super.onTickEnd(),this.checkBuffer(),this.checkFragmentChanged()}doTickIdle(){let{hls:e,levelLastLoaded:t,levels:i,media:r}=this;if(null===t||!r&&(this.startFragRequested||!e.config.startFragPrefetch)||this.altAudio&&this.audioOnly)return;let s=e.nextLoadLevel;if(null==i||!i[s])return;let n=i[s],a=this.getMainFwdBufferInfo();if(null===a)return;let o=this.getLevelDetails();if(o&&this._streamEnded(a,o)){let e={};return this.altAudio&&(e.type="video"),this.hls.trigger(Yf.BUFFER_EOS,e),void(this.state=Zv)}e.loadLevel!==s&&-1===e.manualLevel&&this.log(`Adapting to level ${s} from level ${this.level}`),this.level=e.nextLoadLevel=s;let l=n.details;if(!l||this.state===tE||l.live&&this.levelLastLoaded!==n)return this.level=s,void(this.state=tE);let h=a.len,d=this.getMaxBufferLength(n.maxBitrate);if(h>=d)return;this.backtrackFragment&&this.backtrackFragment.start>a.end&&(this.backtrackFragment=null);let u=this.backtrackFragment?this.backtrackFragment.start:a.end,c=this.getNextFragment(u,l);if(this.couldBacktrack&&!this.fragPrevious&&c&&"initSegment"!==c.sn&&this.fragmentTracker.getState(c)!==Sv){var f;let e=(null!=(f=this.backtrackFragment)?f:c).sn-l.startSN,t=l.fragments[e-1];t&&c.cc===t.cc&&(c=t,this.fragmentTracker.removeFragment(t))}else this.backtrackFragment&&a.len&&(this.backtrackFragment=null);if(c&&this.isLoopLoading(c,u)){if(!c.gap){let e=this.audioOnly&&!this.altAudio?hp:dp,t=(e===dp?this.videoBuffer:this.mediaBuffer)||this.media;t&&this.afterBufferFlushed(t,e,ng)}c=this.getNextFragmentLoopLoading(c,l,a,ng,d)}c&&(c.initSegment&&!c.initSegment.data&&!this.bitrateTest&&(c=c.initSegment),this.loadFragment(c,n,u))}loadFragment(e,t,i){let r=this.fragmentTracker.getState(e);this.fragCurrent=e,r===yv||r===Tv?"initSegment"===e.sn?this._loadInitSegment(e,t):this.bitrateTest?(this.log(`Fragment ${e.sn} of level ${e.level} is being downloaded to test bitrate and will not be buffered`),this._loadBitrateTestFrag(e,t)):(this.startFragRequested=!0,super.loadFragment(e,t,i)):this.clearTrackerIfNeeded(e)}getBufferedFrag(e){return this.fragmentTracker.getBufferedFrag(e,ng)}followingBufferedFrag(e){return e?this.getBufferedFrag(e.end+.5):null}immediateLevelSwitch(){this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY)}nextLevelSwitch(){let{levels:e,media:t}=this;if(null!=t&&t.readyState){let i,r=this.getAppendedFrag(t.currentTime);r&&r.start>1&&this.flushMainBuffer(0,r.start-1);let s=this.getLevelDetails();if(null!=s&&s.live){let e=this.getMainFwdBufferInfo();if(!e||e.len<2*s.targetduration)return}if(!t.paused&&e){let t=e[this.hls.nextLoadLevel],r=this.fragLastKbps;i=r&&this.fragCurrent?this.fragCurrent.duration*t.maxBitrate/(1e3*r)+1:0}else i=0;let n=this.getBufferedFrag(t.currentTime+i);if(n){let e=this.followingBufferedFrag(n);if(e){this.abortCurrentFrag();let t=e.maxStartPTS?e.maxStartPTS:e.start,i=e.duration,r=Math.max(n.end,t+Math.min(Math.max(i-this.config.maxFragLookUpTolerance,i*(this.couldBacktrack?.5:.125)),i*(this.couldBacktrack?.75:.25)));this.flushMainBuffer(r,Number.POSITIVE_INFINITY)}}}}abortCurrentFrag(){let e=this.fragCurrent;switch(this.fragCurrent=null,this.backtrackFragment=null,e&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.state){case Wv:case qv:case Yv:case Xv:case Qv:this.state=Kv}this.nextLoadPosition=this.getLoadPosition()}flushMainBuffer(e,t){super.flushMainBuffer(e,t,this.altAudio?"video":null)}onMediaAttached(e,t){super.onMediaAttached(e,t);let i=t.media;this.onvplaying=this.onMediaPlaying.bind(this),this.onvseeked=this.onMediaSeeked.bind(this),i.addEventListener("playing",this.onvplaying),i.addEventListener("seeked",this.onvseeked),this.gapController=new aT(this.config,i,this.fragmentTracker,this.hls)}onMediaDetaching(){let{media:e}=this;e&&this.onvplaying&&this.onvseeked&&(e.removeEventListener("playing",this.onvplaying),e.removeEventListener("seeked",this.onvseeked),this.onvplaying=this.onvseeked=null,this.videoBuffer=null),this.fragPlaying=null,this.gapController&&(this.gapController.destroy(),this.gapController=null),super.onMediaDetaching()}onMediaPlaying(){this.tick()}onMediaSeeked(){let e=this.media,t=e?e.currentTime:null;Kf(t)&&this.log(`Media seeked to ${t.toFixed(3)}`);let i=this.getMainFwdBufferInfo();null!==i&&0!==i.len?this.tick():this.warn(`Main forward buffer length on "seeked" event ${i?i.len:"empty"})`)}onManifestLoading(){this.log("Trigger BUFFER_RESET"),this.hls.trigger(Yf.BUFFER_RESET,void 0),this.fragmentTracker.removeAllFragments(),this.couldBacktrack=!1,this.startPosition=this.lastCurrentTime=this.fragLastKbps=0,this.levels=this.fragPlaying=this.backtrackFragment=this.levelLastLoaded=null,this.altAudio=this.audioOnly=this.startFragRequested=!1}onManifestParsed(e,t){let i=!1,r=!1;t.levels.forEach((e=>{let t=e.audioCodec;t&&(i=i||-1!==t.indexOf("mp4a.40.2"),r=r||-1!==t.indexOf("mp4a.40.5"))})),this.audioCodecSwitch=i&&r&&!function(){var e;let t=sT();return"function"==typeof(null==t||null==(e=t.prototype)?void 0:e.changeType)}(),this.audioCodecSwitch&&this.log("Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC"),this.levels=t.levels,this.startFragRequested=!1}onLevelLoading(e,t){let{levels:i}=this;if(!i||this.state!==Kv)return;let r=i[t.level];(!r.details||r.details.live&&this.levelLastLoaded!==r||this.waitForCdnTuneIn(r.details))&&(this.state=tE)}onLevelLoaded(e,t){var i;let{levels:r}=this,s=t.level,n=t.details,a=n.totalduration;if(!r)return void this.warn(`Levels were reset while loading level ${s}`);this.log(`Level ${s} loaded [${n.startSN},${n.endSN}]${n.lastPartSn?`[part-${n.lastPartSn}-${n.lastPartIndex}]`:""}, cc [${n.startCC}, ${n.endCC}] duration:${a}`);let o=r[s],l=this.fragCurrent;l&&(this.state===qv||this.state===Yv)&&l.level!==t.level&&l.loader&&this.abortCurrentFrag();let h=0;if(n.live||null!=(i=o.details)&&i.live){var d;if(this.checkLiveUpdate(n),n.deltaUpdateFailed)return;h=this.alignPlaylists(n,o.details,null==(d=this.levelLastLoaded)?void 0:d.details)}if(o.details=n,this.levelLastLoaded=o,this.hls.trigger(Yf.LEVEL_UPDATED,{details:n,level:s}),this.state===tE){if(this.waitForCdnTuneIn(n))return;this.state=Kv}this.startFragRequested?n.live&&this.synchronizeToLiveEdge(n):this.setStartPosition(n,h),this.tick()}_handleFragmentLoadProgress(e){var t;let{frag:i,part:r,payload:s}=e,{levels:n}=this;if(!n)return void this.warn(`Levels were reset while fragment load was in progress. Fragment ${i.sn} of level ${i.level} will not be buffered`);let a=n[i.level],o=a.details;if(!o)return this.warn(`Dropping fragment ${i.sn} of level ${i.level} after level details were reset`),void this.fragmentTracker.removeFragment(i);let l=a.videoCodec,h=o.PTSKnown||!o.live,d=null==(t=i.initSegment)?void 0:t.data,u=this._getAudioCodec(a),c=this.transmuxer=this.transmuxer||new oy(this.hls,ng,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),f=r?r.index:-1,p=-1!==f,m=new Rv(i.level,i.sn,i.stats.chunkCount,s.byteLength,f,p),g=this.initPTS[i.cc];c.push(s,d,u,l,i,r,o.totalduration,h,m,g)}onAudioTrackSwitching(e,t){let i=this.altAudio;if(!t.url){if(this.mediaBuffer!==this.media){this.log("Switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;let e=this.fragCurrent;e&&(this.log("Switching to main audio track, cancel main fragment load"),e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.resetTransmuxer(),this.resetLoadingState()}else this.audioOnly&&this.resetTransmuxer();let e=this.hls;i&&(e.trigger(Yf.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null}),this.fragmentTracker.removeAllFragments()),e.trigger(Yf.AUDIO_TRACK_SWITCHED,t)}}onAudioTrackSwitched(e,t){let i=t.id,r=!!this.hls.audioTracks[i].url;if(r){let e=this.videoBuffer;e&&this.mediaBuffer!==e&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=e)}this.altAudio=r,this.tick()}onBufferCreated(e,t){let i,r,s=t.tracks,n=!1;for(let e in s){let t=s[e];if("main"===t.id){if(r=e,i=t,"video"===e){let t=s[e];t&&(this.videoBuffer=t.buffer)}}else n=!0}n&&i?(this.log(`Alternate track found, use ${r}.buffered to schedule main fragment loading`),this.mediaBuffer=i.buffer):this.mediaBuffer=this.media}onFragBuffered(e,t){let{frag:i,part:r}=t;if(i&&i.type!==ng)return;if(this.fragContextChanged(i))return this.warn(`Fragment ${i.sn}${r?" p: "+r.index:""} of level ${i.level} finished buffering, but was aborted. state: ${this.state}`),void(this.state===Qv&&(this.state=Kv));let s=r?r.stats:i.stats;this.fragLastKbps=Math.round(8*s.total/(s.buffering.end-s.loading.first)),"initSegment"!==i.sn&&(this.fragPrevious=i),this.fragBufferedComplete(i,r)}onError(e,t){var i;if(t.fatal)this.state=Jv;else switch(t.details){case Xf.FRAG_GAP:case Xf.FRAG_PARSING_ERROR:case Xf.FRAG_DECRYPT_ERROR:case Xf.FRAG_LOAD_ERROR:case Xf.FRAG_LOAD_TIMEOUT:case Xf.KEY_LOAD_ERROR:case Xf.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(ng,t);break;case Xf.LEVEL_LOAD_ERROR:case Xf.LEVEL_LOAD_TIMEOUT:case Xf.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===tE&&(null==(i=t.context)?void 0:i.type)===ig&&(this.state=Kv);break;case Xf.BUFFER_APPEND_ERROR:case Xf.BUFFER_FULL_ERROR:if(!t.parent||"main"!==t.parent)return;if(t.details===Xf.BUFFER_APPEND_ERROR)return void this.resetLoadingState();this.reduceLengthAndFlushBuffer(t)&&this.flushMainBuffer(0,Number.POSITIVE_INFINITY);break;case Xf.INTERNAL_EXCEPTION:this.recoverWorkerError(t)}}checkBuffer(){let{media:e,gapController:t}=this;if(e&&t&&e.readyState){if(this.loadedmetadata||!Lv.getBuffered(e).length){let e=this.state!==Kv?this.fragCurrent:null;t.poll(this.lastCurrentTime,e)}this.lastCurrentTime=e.currentTime}}onFragLoadEmergencyAborted(){this.state=Kv,this.loadedmetadata||(this.startFragRequested=!1,this.nextLoadPosition=this.startPosition),this.tickImmediate()}onBufferFlushed(e,{type:t}){if(t!==hp||this.audioOnly&&!this.altAudio){let e=(t===dp?this.videoBuffer:this.mediaBuffer)||this.media;this.afterBufferFlushed(e,t,ng),this.tick()}}onLevelsUpdated(e,t){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level),this.levels=t.levels}swapAudioCodec(){this.audioCodecSwap=!this.audioCodecSwap}seekToStartPos(){let{media:e}=this;if(!e)return;let t=e.currentTime,i=this.startPosition;if(i>=0&&t<i){if(e.seeking)return void this.log(`could not seek to ${i}, already seeking at ${t}`);let r=Lv.getBuffered(e),s=(r.length?r.start(0):0)-i;s>0&&(s<this.config.maxBufferHole||s<this.config.maxFragLookUpTolerance)&&(this.log(`adjusting start position by ${s} to match buffer start`),i+=s,this.startPosition=i),this.log(`seek to target start position ${i} from current time ${t}`),e.currentTime=i}}_getAudioCodec(e){let t=this.config.defaultAudioCodec||e.audioCodec;return this.audioCodecSwap&&t&&(this.log("Swapping audio codec"),t=-1!==t.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5"),t}_loadBitrateTestFrag(e,t){e.bitrateTest=!0,this._doFragLoad(e,t).then((i=>{let{hls:r}=this;if(!i||this.fragContextChanged(e))return;t.fragmentError=0,this.state=Kv,this.startFragRequested=!1,this.bitrateTest=!1;let s=e.stats;s.parsing.start=s.parsing.end=s.buffering.start=s.buffering.end=self.performance.now(),r.trigger(Yf.FRAG_LOADED,i),e.bitrateTest=!1}))}_handleTransmuxComplete(e){var t;let i="main",{hls:r}=this,{remuxResult:s,chunkMeta:n}=e,a=this.getCurrentContext(n);if(!a)return void this.resetWhenMissingContext(n);let{frag:o,part:l,level:h}=a,{video:d,text:u,id3:c,initSegment:f}=s,{details:p}=h,m=this.altAudio?void 0:s.audio;if(this.fragContextChanged(o))this.fragmentTracker.removeFragment(o);else{if(this.state=Xv,f){if(null!=f&&f.tracks){let e=o.initSegment||o;this._bufferInitSegment(h,f.tracks,e,n),r.trigger(Yf.FRAG_PARSING_INIT_SEGMENT,{frag:e,id:i,tracks:f.tracks})}let e=f.initPTS,t=f.timescale;Kf(e)&&(this.initPTS[o.cc]={baseTime:e,timescale:t},r.trigger(Yf.INIT_PTS_FOUND,{frag:o,id:i,initPTS:e,timescale:t}))}if(d&&p&&"initSegment"!==o.sn){let e=p.fragments[o.sn-1-p.startSN],t=o.sn===p.startSN,i=!e||o.cc>e.cc;if(!1!==s.independent){let{startPTS:e,endPTS:r,startDTS:s,endDTS:a}=d;if(l)l.elementaryStreams[d.type]={startPTS:e,endPTS:r,startDTS:s,endDTS:a};else if(d.firstKeyFrame&&d.independent&&1===n.id&&!i&&(this.couldBacktrack=!0),d.dropped&&d.independent){let s=this.getMainFwdBufferInfo(),n=(s?s.end:this.getLoadPosition())+this.config.maxBufferHole,l=d.firstKeyFramePTS?d.firstKeyFramePTS:e;if(!t&&n<l-this.config.maxBufferHole&&!i)return void this.backtrack(o);i&&(o.gap=!0),o.setElementaryStreamInfo(d.type,o.start,r,o.start,a,!0)}else t&&e>2&&(o.gap=!0);o.setElementaryStreamInfo(d.type,e,r,s,a),this.backtrackFragment&&(this.backtrackFragment=o),this.bufferFragmentData(d,o,l,n,t||i)}else{if(!t&&!i)return void this.backtrack(o);o.gap=!0}}if(m){let{startPTS:e,endPTS:t,startDTS:i,endDTS:r}=m;l&&(l.elementaryStreams[hp]={startPTS:e,endPTS:t,startDTS:i,endDTS:r}),o.setElementaryStreamInfo(hp,e,t,i,r),this.bufferFragmentData(m,o,l,n)}if(p&&null!=c&&null!=(t=c.samples)&&t.length){let e={id:i,frag:o,details:p,samples:c.samples};r.trigger(Yf.FRAG_PARSING_METADATA,e)}if(p&&u){let e={id:i,frag:o,details:p,samples:u.samples};r.trigger(Yf.FRAG_PARSING_USERDATA,e)}}}_bufferInitSegment(e,t,i,r){if(this.state!==Xv)return;this.audioOnly=!!t.audio&&!t.video,this.altAudio&&!this.audioOnly&&delete t.audio;let{audio:s,video:n,audiovideo:a}=t;if(s){let t=e.audioCodec,i=navigator.userAgent.toLowerCase();if(this.audioCodecSwitch){t&&(t=-1!==t.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5");let e=s.metadata;e&&"channelCount"in e&&1!==(e.channelCount||1)&&-1===i.indexOf("firefox")&&(t="mp4a.40.5")}t&&-1!==t.indexOf("mp4a.40.5")&&-1!==i.indexOf("android")&&"audio/mpeg"!==s.container&&(t="mp4a.40.2",this.log(`Android: force audio codec to ${t}`)),e.audioCodec&&e.audioCodec!==t&&this.log(`Swapping manifest audio codec "${e.audioCodec}" for "${t}"`),s.levelCodec=t,s.id="main",this.log(`Init audio buffer, container:${s.container}, codecs[selected/level/parsed]=[${t||""}/${e.audioCodec||""}/${s.codec}]`)}n&&(n.levelCodec=e.videoCodec,n.id="main",this.log(`Init video buffer, container:${n.container}, codecs[level/parsed]=[${e.videoCodec||""}/${n.codec}]`)),a&&this.log(`Init audiovideo buffer, container:${a.container}, codecs[level/parsed]=[${e.codecs}/${a.codec}]`),this.hls.trigger(Yf.BUFFER_CODECS,t),Object.keys(t).forEach((e=>{let s=t[e].initSegment;null!=s&&s.byteLength&&this.hls.trigger(Yf.BUFFER_APPENDING,{type:e,data:s,frag:i,part:null,chunkMeta:r,parent:i.type})})),this.tickImmediate()}getMainFwdBufferInfo(){return this.getFwdBufferInfo(this.mediaBuffer?this.mediaBuffer:this.media,ng)}backtrack(e){this.couldBacktrack=!0,this.backtrackFragment=e,this.resetTransmuxer(),this.flushBufferGap(e),this.fragmentTracker.removeFragment(e),this.fragPrevious=null,this.nextLoadPosition=e.start,this.state=Kv}checkFragmentChanged(){let e=this.media,t=null;if(e&&e.readyState>1&&!1===e.seeking){let i=e.currentTime;if(Lv.isBuffered(e,i)?t=this.getAppendedFrag(i):Lv.isBuffered(e,i+.1)&&(t=this.getAppendedFrag(i+.1)),t){this.backtrackFragment=null;let e=this.fragPlaying,i=t.level;(!e||t.sn!==e.sn||e.level!==i)&&(this.fragPlaying=t,this.hls.trigger(Yf.FRAG_CHANGED,{frag:t}),(!e||e.level!==i)&&this.hls.trigger(Yf.LEVEL_SWITCHED,{level:i}))}}}get nextLevel(){let e=this.nextBufferedFrag;return e?e.level:-1}get currentFrag(){let e=this.media;return e?this.fragPlaying||this.getAppendedFrag(e.currentTime):null}get currentProgramDateTime(){let e=this.media;if(e){let t=e.currentTime,i=this.currentFrag;if(i&&Kf(t)&&Kf(i.programDateTime)){let e=i.programDateTime+1e3*(t-i.start);return new Date(e)}}return null}get currentLevel(){let e=this.currentFrag;return e?e.level:-1}get nextBufferedFrag(){let e=this.currentFrag;return e?this.followingBufferedFrag(e):null}get forceStartLoad(){return this._forceStartLoad}},lT=class e{static get version(){return"1.5.15"}static isMSESupported(){return nT()}static isSupported(){return function(){if(!nT())return!1;let e=Dm();return"function"==typeof e?.isTypeSupported&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some((t=>e.isTypeSupported(Om(t,"video"))))||["mp4a.40.2","fLaC"].some((t=>e.isTypeSupported(Om(t,"audio")))))}()}static getMediaSource(){return Dm()}static get Events(){return Yf}static get ErrorTypes(){return zf}static get ErrorDetails(){return Xf}static get DefaultConfig(){return e.defaultConfig?e.defaultConfig:Qb}static set DefaultConfig(t){e.defaultConfig=t}constructor(t={}){this.config=void 0,this.userConfig=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this.started=!1,this._emitter=new ay,this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.abrController=void 0,this.bufferController=void 0,this.capLevelController=void 0,this.latencyController=void 0,this.levelController=void 0,this.streamController=void 0,this.audioTrackController=void 0,this.subtitleTrackController=void 0,this.emeController=void 0,this.cmcdController=void 0,this._media=null,this.url=null,this.triggeringException=void 0,function(e,t){if("object"==typeof console&&!0===e||"object"==typeof e){ep(e,"debug","log","info","warn","error");try{Jf.log(`Debug logs enabled for "${t}" in hls.js version 1.5.15`)}catch{Jf=Zf}}else Jf=Zf}(t.debug||!1,"Hls instance");let i=this.config=function(e,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(void 0!==t.liveMaxLatencyDurationCount&&(void 0===t.liveSyncDurationCount||t.liveMaxLatencyDurationCount<=t.liveSyncDurationCount))throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(void 0!==t.liveMaxLatencyDuration&&(void 0===t.liveSyncDuration||t.liveMaxLatencyDuration<=t.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');let i=Zb(e),r=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return["manifest","level","frag"].forEach((e=>{let s=`${"level"===e?"playlist":e}LoadPolicy`,n=void 0===t[s],a=[];r.forEach((r=>{let o=`${e}Loading${r}`,l=t[o];if(void 0!==l&&n){a.push(o);let e=i[s].default;switch(t[s]={default:e},r){case"TimeOut":e.maxLoadTimeMs=l,e.maxTimeToFirstByteMs=l;break;case"MaxRetry":e.errorRetry.maxNumRetry=l,e.timeoutRetry.maxNumRetry=l;break;case"RetryDelay":e.errorRetry.retryDelayMs=l,e.timeoutRetry.retryDelayMs=l;break;case"MaxRetryTimeout":e.errorRetry.maxRetryDelayMs=l,e.timeoutRetry.maxRetryDelayMs=l}}})),a.length&&tp.warn(`hls.js config: "${a.join('", "')}" setting(s) are deprecated, use "${s}": ${JSON.stringify(t[s])}`)})),Hf(Hf({},i),t)}(e.DefaultConfig,t);this.userConfig=t,i.progressive&&Jb(i);let{abrController:r,bufferController:s,capLevelController:n,errorController:a,fpsController:o}=i,l=new a(this),h=this.abrController=new r(this),d=this.bufferController=new s(this),u=this.capLevelController=new n(this),c=new o(this),f=new dg(this),p=new _g(this),m=i.contentSteeringController,g=m?new m(this):null,v=this.levelController=new tT(this,g),E=new Av(this),y=new rT(this.config),b=this.streamController=new oT(this,E,y);u.setStreamController(b),c.setStreamController(b);let T=[f,v,b];g&&T.splice(1,0,g),this.networkControllers=T;let S=[h,d,u,c,p,E];this.audioTrackController=this.createController(i.audioTrackController,T);let A=i.audioStreamController;A&&T.push(new A(this,E,y)),this.subtitleTrackController=this.createController(i.subtitleTrackController,T);let _=i.subtitleStreamController;_&&T.push(new _(this,E,y)),this.createController(i.timelineController,S),y.emeController=this.emeController=this.createController(i.emeController,S),this.cmcdController=this.createController(i.cmcdController,S),this.latencyController=this.createController(wg,S),this.coreComponents=S,T.push(l);let w=l.onErrorOut;"function"==typeof w&&this.on(Yf.ERROR,w,l)}createController(e,t){if(e){let i=new e(this);return t&&t.push(i),i}return null}on(e,t,i=this){this._emitter.on(e,t,i)}once(e,t,i=this){this._emitter.once(e,t,i)}removeAllListeners(e){this._emitter.removeAllListeners(e)}off(e,t,i=this,r){this._emitter.off(e,t,i,r)}listeners(e){return this._emitter.listeners(e)}emit(e,t,i){return this._emitter.emit(e,t,i)}trigger(e,t){if(this.config.debug)return this.emit(e,e,t);try{return this.emit(e,e,t)}catch(t){if(tp.error("An internal error happened while handling event "+e+'. Error message: "'+t.message+'". Here is a stacktrace:',t),!this.triggeringException){this.triggeringException=!0;let i=e===Yf.ERROR;this.trigger(Yf.ERROR,{type:zf.OTHER_ERROR,details:Xf.INTERNAL_EXCEPTION,fatal:i,event:e,error:t}),this.triggeringException=!1}}return!1}listenerCount(e){return this._emitter.listenerCount(e)}destroy(){tp.log("destroy"),this.trigger(Yf.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;let e=this.config;e.xhrSetup=e.fetchSetup=void 0,this.userConfig=null}attachMedia(e){tp.log("attachMedia"),this._media=e,this.trigger(Yf.MEDIA_ATTACHING,{media:e})}detachMedia(){tp.log("detachMedia"),this.trigger(Yf.MEDIA_DETACHING,void 0),this._media=null}loadSource(e){this.stopLoad();let t=this.media,i=this.url,r=this.url=Ff.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,tp.log(`loadSource:${r}`),t&&i&&(i!==r||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(t)),this.trigger(Yf.MANIFEST_LOADING,{url:e})}startLoad(e=-1){tp.log(`startLoad(${e})`),this.started=!0,this.networkControllers.forEach((t=>{t.startLoad(e)}))}stopLoad(){tp.log("stopLoad"),this.started=!1,this.networkControllers.forEach((e=>{e.stopLoad()}))}resumeBuffering(){this.started&&this.networkControllers.forEach((e=>{"fragmentLoader"in e&&e.startLoad(-1)}))}pauseBuffering(){this.networkControllers.forEach((e=>{"fragmentLoader"in e&&e.stopLoad()}))}swapAudioCodec(){tp.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){tp.log("recoverMediaError");let e=this._media;this.detachMedia(),e&&this.attachMedia(e)}removeLevel(e){this.levelController.removeLevel(e)}get levels(){return this.levelController.levels||[]}get currentLevel(){return this.streamController.currentLevel}set currentLevel(e){tp.log(`set currentLevel:${e}`),this.levelController.manualLevel=e,this.streamController.immediateLevelSwitch()}get nextLevel(){return this.streamController.nextLevel}set nextLevel(e){tp.log(`set nextLevel:${e}`),this.levelController.manualLevel=e,this.streamController.nextLevelSwitch()}get loadLevel(){return this.levelController.level}set loadLevel(e){tp.log(`set loadLevel:${e}`),this.levelController.manualLevel=e}get nextLoadLevel(){return this.levelController.nextLoadLevel}set nextLoadLevel(e){this.levelController.nextLoadLevel=e}get firstLevel(){return Math.max(this.levelController.firstLevel,this.minAutoLevel)}set firstLevel(e){tp.log(`set firstLevel:${e}`),this.levelController.firstLevel=e}get startLevel(){let e=this.levelController.startLevel;return-1===e&&this.abrController.forcedAutoLevel>-1?this.abrController.forcedAutoLevel:e}set startLevel(e){tp.log(`set startLevel:${e}`),-1!==e&&(e=Math.max(e,this.minAutoLevel)),this.levelController.startLevel=e}get capLevelToPlayerSize(){return this.config.capLevelToPlayerSize}set capLevelToPlayerSize(e){let t=!!e;t!==this.config.capLevelToPlayerSize&&(t?this.capLevelController.startCapping():(this.capLevelController.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=t)}get autoLevelCapping(){return this._autoLevelCapping}get bandwidthEstimate(){let{bwEstimator:e}=this.abrController;return e?e.getEstimate():NaN}set bandwidthEstimate(e){this.abrController.resetEstimator(e)}get ttfbEstimate(){let{bwEstimator:e}=this.abrController;return e?e.getEstimateTTFB():NaN}set autoLevelCapping(e){this._autoLevelCapping!==e&&(tp.log(`set autoLevelCapping:${e}`),this._autoLevelCapping=e,this.levelController.checkMaxAutoUpdated())}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(e){(function(e){return kg.indexOf(e)>-1})(e)&&this._maxHdcpLevel!==e&&(this._maxHdcpLevel=e,this.levelController.checkMaxAutoUpdated())}get autoLevelEnabled(){return-1===this.levelController.manualLevel}get manualLevel(){return this.levelController.manualLevel}get minAutoLevel(){let{levels:e,config:{minAutoBitrate:t}}=this;if(!e)return 0;let i=e.length;for(let r=0;r<i;r++)if(e[r].maxBitrate>=t)return r;return 0}get maxAutoLevel(){let e,{levels:t,autoLevelCapping:i,maxHdcpLevel:r}=this;if(e=-1===i&&null!=t&&t.length?t.length-1:i,r)for(let i=e;i--;){let e=t[i].attrs["HDCP-LEVEL"];if(e&&e<=r)return i}return e}get firstAutoLevel(){return this.abrController.firstAutoLevel}get nextAutoLevel(){return this.abrController.nextAutoLevel}set nextAutoLevel(e){this.abrController.nextAutoLevel=e}get playingDate(){return this.streamController.currentProgramDateTime}get mainForwardBufferInfo(){return this.streamController.getMainFwdBufferInfo()}setAudioOption(e){var t;return null==(t=this.audioTrackController)?void 0:t.setAudioOption(e)}setSubtitleOption(e){var t;return null==(t=this.subtitleTrackController)||t.setSubtitleOption(e),null}get allAudioTracks(){let e=this.audioTrackController;return e?e.allAudioTracks:[]}get audioTracks(){let e=this.audioTrackController;return e?e.audioTracks:[]}get audioTrack(){let e=this.audioTrackController;return e?e.audioTrack:-1}set audioTrack(e){let t=this.audioTrackController;t&&(t.audioTrack=e)}get allSubtitleTracks(){let e=this.subtitleTrackController;return e?e.allSubtitleTracks:[]}get subtitleTracks(){let e=this.subtitleTrackController;return e?e.subtitleTracks:[]}get subtitleTrack(){let e=this.subtitleTrackController;return e?e.subtitleTrack:-1}get media(){return this._media}set subtitleTrack(e){let t=this.subtitleTrackController;t&&(t.subtitleTrack=e)}get subtitleDisplay(){let e=this.subtitleTrackController;return!!e&&e.subtitleDisplay}set subtitleDisplay(e){let t=this.subtitleTrackController;t&&(t.subtitleDisplay=e)}get lowLatencyMode(){return this.config.lowLatencyMode}set lowLatencyMode(e){this.config.lowLatencyMode=e}get liveSyncPosition(){return this.latencyController.liveSyncPosition}get latency(){return this.latencyController.latency}get maxLatency(){return this.latencyController.maxLatency}get targetLatency(){return this.latencyController.targetLatency}get drift(){return this.latencyController.drift}get forceStartLoad(){return this.streamController.forceStartLoad}};lT.defaultConfig=void 0;var hT,dT,uT,cT,fT,pT,mT,gT,vT,ET,yT,bT,TT,ST,AT,_T,wT,kT,LT=Symbol.for(""),RT=e=>{if(e?.r===LT)return e?._$litStatic$},IT=e=>({_$litStatic$:e,r:LT}),CT=new Map,DT=(e=>(t,...i)=>{let r,s,n,a=i.length,o=[],l=[],h=0,d=!1;for(;h<a;){for(n=t[h];h<a&&(s=i[h],void 0!==(r=RT(s)));)n+=r+t[++h],d=!0;h!==a&&l.push(s),o.push(n),h++}if(h===a&&o.push(t[a]),d){let e=o.join("$$lit$$");void 0===(t=CT.get(e))&&(o.raw=o,CT.set(e,t=o)),i=l}return e(t,...i)})(B),xT=class extends $n{constructor(){super(...arguments),At(this,hT),this._controls=["play","time","seek","volume","fullscreen","subtitles"],this.popped=!1,this._startedPlaying=!1,this._intersectionObserver=new cn(this,{callback:_t(this,hT,mT).bind(this)}),this.embedController=new On(this),this._intersected=!1,this._queue=[]}get embed(){return this._embedId}set embed(e){this._embedId!=e&&(this._embedId=e,this.embedController.embed=this.embed,this.updateStylePoster(),this.loadTheme())}get token(){return this._token}set token(e){this._token!=e&&(this._token=e,this.requestUpdate("token"),this.embedController.token=this._token)}set loop(e){this._loop=(""===e||"true"==e||1==e)??!1}get loop(){return this._loop}get controls(){return this._controls}set controls(e){this._controls="string"==typeof e?e.split(" "):e}get cache(){return this._cache}set cache(e){this._cache!=e&&(this._cache="string"==typeof e&&("true"===e||""===e),this.requestUpdate("caching"),this.embedController.caching=this._cache)}get quality(){return this._quality}set quality(e){this._quality!=e&&(this._quality=e)}get theme(){return this._theme||"default"}set theme(e){this._theme!=e&&(this._theme=e,this.requestUpdate("theme"),this.loadTheme())}get poster(){return this.embed&&this._embedObj?this._poster&&"custom"==this._poster?this.embedController.embedFile(_t(this,hT,cT).call(this,"custom_thumbnail")):!this._poster||Number.isNaN(parseFloat(this._poster))&&Number.isNaN(parseInt(this._poster))?this._poster?this._poster:this.embedController.embedFile(_t(this,hT,cT).call(this,"thumbnail")):this._embedObj.poster&&this._embedObj.poster.renditions&&this._embedObj.poster.renditions.find((e=>"custom_thumbnail"==e.type))?this.embedController.embedFile(_t(this,hT,cT).call(this,"custom_thumbnail")):`https://image.mave.io/${this.embedController.spaceId}${this.embedController.embedId}.jpg?time=${this._poster}`:""}set poster(e){e&&(this._poster=e,this.requestUpdate("poster"))}pop(){this.popped=!0}close(){this.popped=!1}set muted(e){let t=(""===e||"true"==e||1==e)??!1;this._videoElement?this._videoElement.muted=t:this._queue.push((()=>this._videoElement.muted=t))}get muted(){return this._videoElement?.muted||!1}set currentTime(e){this._videoElement?this._videoElement.currentTime=e:this._queue.push((()=>this._videoElement.currentTime=e))}get currentTime(){return this._videoElement?this._videoElement?.currentTime:0}get duration(){return new Promise(((e,t)=>{if(this._videoElement&&!isNaN(this._videoElement.duration))return e(this._videoElement.duration);let i=()=>{this._videoElement?.addEventListener("loadedmetadata",(()=>{this._videoElement&&e(this._videoElement.duration)})),this._videoElement?.addEventListener("error",(()=>{t(new Error("Failed to load video metadata."))}))};this._videoElement?i():this.addEventListener("mave:video_element_ready",(()=>{i()}))}))}get paused(){return!this._videoElement||this._videoElement.paused}play(){this._videoElement&&!this.embedController.loading?_t(this,hT,bT).call(this):this._queue.push((()=>_t(this,hT,bT).call(this)))}restart(){this._videoElement&&(this.pause(),this._videoElement.currentTime=0,this.play())}pause(){this._videoElement?this._videoElement.pause():this._queue.push((()=>this._videoElement?.pause()))}updateStylePoster(){this.style.setProperty("background",`center / contain no-repeat url(${this.poster})`)}connectedCallback(){super.connectedCallback(),this.loadTheme(),_t(this,hT,uT).call(this)}disconnectedCallback(){super.disconnectedCallback(),this._metricsInstance?.demonitor()}loadTheme(){this.embed&&this._themeLoaded!=this.theme&&(qn.get(this.theme,`${this.embedController.cdnRoot}/themes/player`),this._themeLoaded=this.theme)}updateEmbed(e){this._embedObj=e,this.updateStylePoster(),this.poster=this._embedObj.settings.poster,this.attributes.getNamedItem("color")||(this.color=this._embedObj.settings.color),this.attributes.getNamedItem("opacity")||(this.opacity=this._embedObj.settings.opacity?this._embedObj.settings.opacity:void 0),this.attributes.getNamedItem("aspect-ratio")||(this.aspect_ratio=this._embedObj.settings.aspect_ratio),this.attributes.getNamedItem("width")||(this.width=this._embedObj.settings.width),this.attributes.getNamedItem("height")||(this.height=this._embedObj.settings.height),this.attributes.getNamedItem("autoplay")||(this.autoplay="on_show"==this._embedObj.settings.autoplay?"lazy":this._embedObj.settings.autoplay),this.attributes.getNamedItem("controls")||(this.controls=this._embedObj.settings.controls),this.attributes.getNamedItem("loop")||(this.loop=this._embedObj.settings.loop)}get styles(){let e={};return(this.color||this._embedObj?.settings.color)&&(e["--primary-color"]=`${this.color||this._embedObj?.settings.color}${this.opacity||this._embedObj?.settings.opacity?this._embedObj?.settings.opacity:""}`),"auto"==this.aspect_ratio||"auto"==this._embedObj?.settings.aspect_ratio&&!this.aspect_ratio?e["--aspect-ratio"]=this._embedObj?.video.aspect_ratio:e["--aspect-ratio"]=this.aspect_ratio||this._embedObj?.settings.aspect_ratio,(this.width||this._embedObj?.settings.width)&&(e["--width"]=this.width||this._embedObj?.settings.width),(this.height||this._embedObj?.settings.height)&&(e["--height"]=this.height||this._embedObj?.settings.height),!this.controls.includes("full")&&!this.controls.includes("big")&&!this.controls.includes("none")&&(e["--play-display"]=this.controls.includes("play")?"flex":"none",e["--time-display"]=this.controls.includes("time")?"flex":"none",e["--seek-bar-visibility"]=this.controls.includes("seek")?"visible":"hidden",e["--volume-display"]=this.controls.includes("volume")?"flex":"none",e["--fullscreen-display"]=this.controls.includes("fullscreen")?"flex":"none",e["--captions-display"]=this.controls.includes("subtitles")?"flex":"none"),e["--playbackrate-display"]=this.controls.includes("rate")?"flex":"none",(("none"==this.subtitles||"off"==this.subtitles||0==this._embedObj?.subtitles.length)&&!this.active_subtitle||this._embedObj?.created_at<1740674988&&!this.subtitles&&!this.active_subtitle)&&(e["--captions-display"]="none"),this.controls.includes("full")||"full"==this._embedObj?.settings.controls&&!this.controls.includes("big")&&!this.controls.includes("none")?e["--media-control-bar-display"]="flex":e["--media-control-bar-display"]="none",this.controls.includes("big")||"big"==this._embedObj?.settings.controls&&!this.controls.includes("full")&&!this.controls.includes("none")?e["--big-button-display"]="flex":e["--big-button-display"]="none",!1===this._embedObj?.video.audio?e["--media-volume-display"]="none":e["--media-volume-display"]="inline-flex",et(e)}render(){if(!this.embed)return;let e=this.querySelector('[slot="start-screen"]');return B`
      <slot
        name="video"
        style=${et({display:e&&!this._startedPlaying?"none":"block"})}
      >
        ${this.embedController.render({complete:e=>{if(this._embed||(this._embedObj=e,this.updateEmbed(this._embedObj)),e)return DT`<theme-${IT(this.theme)} style=${this.styles}>
                <video
                  @click=${_t(this,hT,bT)}
                  playsinline
                  ?loop=${this.loop||this._embedObj.settings.loop}
                  poster=${this.poster}
                  ${Dn(_t(this,hT,pT))}
                  slot="media"
                  crossorigin="anonymous"
                >
                  ${St(this,hT,kT)}
                  ${St(this,hT,wT)}
                </video>
            </theme-${IT(this.theme)}>`}})}
      </slot>
      <slot name="start-screen"></slot>
      <slot name="end-screen"></slot>
      <slot name="hover-screen"></slot>
    `}};hT=new WeakSet,dT=function(e,t){let i=new URL(t);if(this.token&&!i.searchParams.get("token")){let e=new URLSearchParams;e.append("token",this.token),i.search=e.toString()}e.open("GET",i.toString())},uT=function(){navigator.userAgent.includes("Mobi")||(this.style.setProperty("--subtitle-transform","translateY(100em)"),this.style.setProperty("--subtitle-display","none"),this.style.setProperty("--subtitle-opacity","0"),this._videoElement?.style.setProperty("--subtitle-transform","translateY(100em)"),this._videoElement?.style.setProperty("--subtitle-display","none"),this._videoElement?.style.setProperty("--subtitle-opacity","0")),this._videoElement?.addEventListener("webkitbeginfullscreen",(()=>{this.style.setProperty("--subtitle-transform","translateY(-1em)")})),this._videoElement?.addEventListener("webkitendfullscreen",(()=>{this.style.setProperty("--subtitle-transform","translateY(100em)")}))},cT=function(e){let t=(()=>this._embedObj.poster&&this._embedObj.poster.renditions&&this._embedObj.poster.renditions.find((t=>"jpg"===t.container&&t.type===e)))(),i="custom_thumbnail"==e?"thumbnail":e;return t?`${i}.jpg${t&&t.date?`?e=${t.date}`:""}`:`${i}.jpg`},fT=function(){let e=[{name:"sd",width:640},{name:"hd",width:1280},{name:"fhd",width:1920},{name:"qhd",width:2560},{name:"uhd",width:3840}],t=e.find((e=>e.name==this.quality));return t?e.indexOf(t):2},pT=function(e){if(e&&"VIDEO"==e.tagName&&(St(this,hT,AT)||St(this,hT,_T))){this._videoElement=e,this.dispatchEvent(new CustomEvent("mave:video_element_ready",{detail:this._videoElement,bubbles:!0,composed:!0})),this._intersectionObserver.observe(this._videoElement),xn.forEach((e=>{this._videoElement?.addEventListener(e,(t=>{if("play"==e&&_t(this,hT,gT).call(this),"ended"==e&&_t(this,hT,vT).call(this),"timeupdate"==e&&this._videoElement&&this._videoElement.duration-this._videoElement.currentTime<5){let e=this.querySelector('[slot="end-screen"]');if(e&&"near_end"==e.getAttribute("x-mave-end-shows")){_t(this,hT,vT).call(this);let t=this.querySelector("[name='mave-time-remaining']");if(t){let e=Math.floor(this._videoElement.duration-this._videoElement.currentTime);t.innerHTML=e<=0?"0":e.toString()}if(this._videoElement?.duration-this._videoElement?.currentTime<=0&&"true"==e.getAttribute("x-mave-list-trigger-next")){let e=[...document.querySelectorAll("mave-list")].find((e=>e.containsEmbed(this.embed)));if(e){let t=e.getNextForEmbed(this.embed);t&&this.emit(this.EVENT_TYPES.CLICK,{embedId:t.id})}}let i=this.querySelector("[name='mave-list-next-image']");if(i){let e=[...document.querySelectorAll("mave-list")].find((e=>e.containsEmbed(this.embed)));if(e){let t=e.getNextForEmbed(this.embed);if(t){let e=document.createElement("mave-img");e.setAttribute("embed",t.id),e.addEventListener("click",(()=>{this.emit(this.EVENT_TYPES.CLICK,{embedId:t.id}),i.innerHTML=""})),i.appendChild(e)}else i.innerHTML=""}}}}this.dispatchEvent(new CustomEvent(e,{detail:t,bubbles:!0,composed:!0}))}))})),Nf.Metrics.config={socketPath:E.metrics.socket,apiKey:this._embedObj.metrics_key};let t={component:"player",video_id:this._embedObj.video.id,space_id:this._embedObj.space_id},i=/iPhone|iPad/.test(navigator.userAgent);lT.isSupported()&&St(this,hT,AT)&&!i?(this.hls=new lT({startLevel:_t(this,hT,fT).call(this),capLevelToPlayerSize:!0,xhrSetup:_t(this,hT,dT).bind(this),maxBufferLength:20,maxBufferSize:20,backBufferLength:60}),this.hls?.loadSource(St(this,hT,AT)),this.hls?.attachMedia(this._videoElement),E.metrics.enabled&&(this._metricsInstance=new Nf.Metrics(this.hls,this.embed,t))):this._videoElement.canPlayType("application/vnd.apple.mpegurl")&&St(this,hT,AT)?(this._videoElement.src=St(this,hT,AT),E.metrics.enabled&&(this._metricsInstance=new Nf.Metrics(this._videoElement,this.embed,t))):(this._videoElement.src=St(this,hT,_T),E.metrics.enabled&&(this._metricsInstance=new Nf.Metrics(this._videoElement,this.embed,t))),this._queue.length&&(this._queue.forEach((e=>e())),this._queue=[]),_t(this,hT,yT).call(this),_t(this,hT,ET).call(this)}},mT=function(e){for(let{isIntersecting:t}of e)e.length&&("VIDEO"==e[0].target.tagName||"MAVE-PLAYER"==e[0].target.tagName)&&(this._intersected=t,_t(this,hT,yT).call(this))},gT=function(){if(this.active_subtitle&&!this._startedPlaying){let e;if("original"==this.active_subtitle||"original"==this.subtitles){let t=this._embedObj.video.language;e=this._videoElement?.querySelector(`track[srclang="${t}"]`)}else e=this._videoElement?.querySelector(`track[srclang="${this.active_subtitle}"]`);e&&(e.track.mode="showing")}this._startedPlaying=!0,_t(this,hT,ET).call(this),this._previousControls&&(this.controls=this._previousControls,this._previousControls=void 0);let e=this.querySelector('[slot="start-screen"]');e&&((this.shadowRoot?.querySelector("slot[name='video']")).removeAttribute("style"),this.startScreenElement.style.display="none",e.style.display="none")},vT=function(){let e=this.querySelector('[slot="end-screen"]');if(e){if("TEMPLATE"===e.tagName){let t=e,i=t.parentElement,r=document.createElement("div");for(let e of t.attributes)r.setAttribute(e.name,e.value);r.style.display="block",r.innerHTML=t.innerHTML,i?.replaceChild(r,t)}this.endScreenElement.style.display="block",e.style.display="block",this._previousControls||(this._previousControls=this.controls),this.controls="none"}},ET=function(){let e=this.querySelector('[slot="end-screen"]');e&&(this.endScreenElement.style.display="none",e.style.display="none"),this._previousControls&&(this.controls=this._previousControls,this._previousControls=void 0)},yT=function(){this._embedObj&&"always"==this.autoplay&&this._videoElement?.paused&&(this._metricsInstance?.monitor(),this._videoElement.muted=!0,this._videoElement?.play()),this._embedObj&&("lazy"===this.autoplay||"true"===this.autoplay||"on_show"==this._embedObj.settings.autoplay)&&(this._intersected?this._videoElement?.paused&&(this._metricsInstance?.monitor(),this._videoElement.muted=!0,this._videoElement?.play()):this._videoElement&&!this._videoElement.paused&&this._videoElement.readyState>2&&this._videoElement?.pause())},bT=function(){this._videoElement?.paused?(this._metricsInstance?.monitor(),this._videoElement?.play()):this._videoElement?.pause()},TT=function(e){let t=e.target.track,i=t.activeCues;if("showing"==t.mode&&(this._currentTrackLanguage=t.language),!navigator.userAgent.includes("Mobi")){if(!this._subtitlesText){let e=this.shadowRoot?.querySelector(`theme-${this.theme}`)?.shadowRoot?.querySelector("#subtitles_text");e&&(this._subtitlesText=e)}if(this._currentTrackLanguage!=t.language)return;if(i.length){let e=i[0];this._subtitlesText.style.opacity="1",this._subtitlesText.innerHTML=e.text}else this._subtitlesText.style.opacity="0"}},ST=function(e){let t=this._embedObj.video.renditions.filter((t=>t.container==e)),i=["sd","hd","fhd","qhd","uhd"];return t&&t.length?t.reduce(((e,t)=>i.indexOf(t.size)>i.indexOf(e.size)?t:e)):void 0},AT=function(){let e=_t(this,hT,ST).call(this,"hls");if(e){let t=new URLSearchParams;return t.append("quality",e.size),this.embedController.embedFile("playlist.m3u8",t)}},_T=function(){let e=_t(this,hT,ST).call(this,"mp4");return e?this.embedController.embedFile(`h264_${e?.size}.mp4`):this._embedObj.video.original},wT=function(){if(this._embedObj.subtitles.length>0){let e=this.shadowRoot?.querySelector(`theme-${this.theme}`)?.shadowRoot?.querySelector("media-captions-selectmenu")?.shadowRoot?.querySelector("media-captions-listbox")?.shadowRoot?.querySelector('media-chrome-option[part="option option-selected"]');return e&&new MutationObserver((t=>{t.forEach((()=>{this._subtitlesText&&"off"===e.getAttribute("value")&&(this._subtitlesText.style.opacity="0")}))})).observe(e,{attributes:!0}),this._embedObj.subtitles.map((e=>{if(this.subtitles&&this.subtitles.includes(e.language)||this.active_subtitle&&this.active_subtitle==e.language||"all"==this.subtitles||("original"==this.subtitles||"original"==this.active_subtitle)&&this._embedObj.video.language==e.language||!this.subtitles)return B`
            <track mode="hidden" @cuechange=${_t(this,hT,TT)} label=${e.label} kind="subtitles" srclang=${e.language} src=${e.path}></track>
          `}))}},kT=function(){return B`<track
      label="thumbnails"
      default
      kind="metadata"
      src=${this.embedController.embedFile("storyboard.vtt")}></track>`},xT.styles=oe`
    :host {
      display: block;
      position: relative;
    }

    video::cue {
      font-family: Inter, Roboto, 'Helvetica Neue', 'Arial Nova', 'Nimbus Sans', Arial,
        sans-serif;
      font-weight: 500;
      display: var(--subtitle-display, initial);
      opacity: var(--subtitle-opacity, 1);
    }

    video::-webkit-media-text-track-display {
      transform: var(--subtitle-transform, initial);
    }

    video:focus-visible {
      outline: 0;
    }

    :host,
    media-controller,
    theme-default,
    video {
      width: 100%;
      max-height: 100vh;
    }

    slot[name='start-screen'],
    slot[name='end-screen'] {
      position: absolute;
      width: 100%;
      height: 100%;
      z-index: 99;
      top: 0;
      left: 0;
    }

    slot[name='end-screen'] {
      display: none;
    }
  `,bt([rt()],xT.prototype,"embed",1),bt([rt()],xT.prototype,"token",1),bt([rt({attribute:"aspect-ratio"})],xT.prototype,"aspect_ratio",2),bt([rt()],xT.prototype,"width",2),bt([rt()],xT.prototype,"subtitles",2),bt([rt({attribute:"active-subtitle"})],xT.prototype,"active_subtitle",2),bt([rt()],xT.prototype,"height",2),bt([rt()],xT.prototype,"autoplay",2),bt([rt()],xT.prototype,"color",2),bt([rt()],xT.prototype,"opacity",2),bt([rt()],xT.prototype,"loop",1),bt([rt()],xT.prototype,"controls",1),bt([rt()],xT.prototype,"cache",1),bt([rt()],xT.prototype,"quality",1),bt([rt()],xT.prototype,"theme",1),bt([rt()],xT.prototype,"poster",1),bt([st()],xT.prototype,"popped",2),bt([at("slot[name='end-screen']")],xT.prototype,"endScreenElement",2),bt([at("slot[name='start-screen']")],xT.prototype,"startScreenElement",2),bt([st()],xT.prototype,"_embedObj",2),bt([rt()],xT.prototype,"muted",1),window&&window.customElements&&(window.customElements.get("mave-player")||window.customElements.define("mave-player",xT));var MT=class extends _e{get backdrop(){return this._backdropColor||"black"}set backdrop(e){this._backdropColor!=e&&(this._backdropColor=e)}get backdropFilter(){return this._backdropFilter}set backdropFilter(e){this._backdropFilter!=e&&(this._backdropFilter=e)}get styles(){let e={"--backdrop":this.backdrop,"--backdrop-filter":this.backdropFilter};return et(e)}open(e){if(this._player=e,e.aspect_ratio){let[t,i]=e.aspect_ratio.split("/");this.style.setProperty("--frame-ratio-w",t),this.style.setProperty("--frame-ratio-h",i)}this.style.display="block";let t=t=>{this._frame.appendChild(e),setTimeout((()=>{this._dialog.showModal()}),25),this._dialog.addEventListener("close",(e=>{e.preventDefault(),this.close()}),{once:!0}),t(this)};return new Promise((e=>{if(this._dialog)t(e);else{let i=setInterval((()=>{this._dialog&&(t(e),clearInterval(i))}),100)}}))}possibleClose(e){e.target!=this._player&&this.close()}close(){this._dialog.close(),this._backdrop.addEventListener("transitionend",(()=>{this._frame.innerHTML="",this.dispatchEvent(new Event("closed",{bubbles:!0}))}),{once:!0})}render(){return B`
      <dialog style=${this.styles}>
        <div class="backdrop"></div>
        <div class="content" @click=${this.possibleClose}>
          <div class="wrapper">
            <slot style="display: none;"></slot>
            <div class="frame"></div>
          </div>
        </div>
        <div class="button-close" @click=${this.close}>
          <svg
            width="24px"
            height="24px"
            stroke-width="1"
            viewBox="0 0 24 24"
            fill="none"
            xmlns="http://www.w3.org/2000/svg"
            color="currentColor"
          >
            <path
              d="M6 12h6m6 0h-6m0 0V6m0 6v6"
              stroke="currentColor"
              stroke-width="1"
              stroke-linecap="round"
              stroke-linejoin="round"
            ></path>
          </svg>
        </div>
      </dialog>
    `}};function PT(e){let t={};if(!e)return t;for(let i=0;i<e.attributes.length;i++){let r=e.attributes[i];t[r.name]=r.value}return t}MT.styles=oe`
    :host {
      all: initial;
      --backdrop: black;
      --frame-max-height: 100vh;
      --frame-ratio-w: 16;
      --frame-ratio-h: 9;
      --backdrop-filter: blur(0);
    }

    slot {
      all: initial;
      position: fixed;
    }

    dialog {
      display: block;
      margin: 0;
      padding: 0;
      border: 0;
      pointer-events: none;
      background: transparent;
    }

    dialog .content {
      position: fixed;
      width: 100vw;
      height: 100vh;
      top: 0;
      left: 0;
      opacity: 0;
      display: flex;
      justify-content: center;
      align-items: center;
      transform: scale(0.96);
      transition-property: transform, opacity;
      transition-duration: 200ms;
      transition-timing-function: ease-out;
    }

    .backdrop {
      position: fixed;
      background: var(--backdrop);
      backdrop-filter: var(--backdrop-filter);
      opacity: 0;
      top: 0;
      left: 0;
      width: 100vw;
      height: 100vh;
      transition-property: opacity;
      transition-duration: 200ms;
      transition-timing-function: ease-out;
    }

    dialog[open] .backdrop {
      opacity: 1;
    }

    dialog::backdrop {
      background: none;
    }

    dialog[open] {
      pointer-events: auto;
    }

    dialog[open] .content {
      opacity: 1;
      transform: scale(1);
    }

    dialog[open] .button-close {
      display: block;
    }

    .button-close {
      display: none;
      position: fixed;
      top: 0.8rem;
      right: 0.6rem;
      width: 2.75rem;
      height: 2.75rem;
      transition-property: transform;
      transition-duration: 100ms;
      transition-timing-function: ease-out;
    }

    .button-close:hover {
      cursor: pointer;
      transform: scale(1.3);
    }

    .button-close svg {
      color: white;
      width: 2.75rem;
      height: 2.75rem;
      transform: rotate(45deg);
    }

    .wrapper {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 100%;
      height: 100%;
      max-width: 100vw;
      max-height: var(--frame-max-height);
    }

    .frame {
      --ratio: calc(var(--frame-ratio-h, 1) / var(--frame-ratio-w, 1) * 100%);
      --frame-height: min(var(--ratio), var(--frame-max-height));
      position: relative;
      padding-bottom: var(--frame-height);
      width: min(
        calc(var(--frame-height, 0) * (var(--frame-ratio-w) / var(--frame-ratio-h))),
        100%
      );
      height: 0;
      overflow: hidden;
      background-size: contain;
      background-position: center center;
      background-repeat: no-repeat;
    }
  `,bt([at("dialog")],MT.prototype,"_dialog",2),bt([at(".content")],MT.prototype,"_content",2),bt([at(".frame")],MT.prototype,"_frame",2),bt([at(".backdrop")],MT.prototype,"_backdrop",2),bt([rt()],MT.prototype,"backdrop",1),bt([rt({attribute:"backdrop-filter"})],MT.prototype,"backdropFilter",1),window&&window.customElements&&(window.customElements.get("mave-pop")||window.customElements.define("mave-pop",MT));var OT=e=>{function t(e,t){let i=new xT;if(t)for(let e in t)i.setAttribute(e,t[e]);return i.embed=e,i}function i(e){e.querySelectorAll("[x-mave-pop]").forEach((e=>{let i=e.getAttribute("x-mave-pop")||e.getAttribute("embed");if(!i)return;let{pop:r,attributes:s}=function(e){let t,i,r=document.querySelector(`mave-pop[embed="${e}"]`);if(r)return i=PT(r.querySelector("mave-player")),t=r,{pop:t,attributes:i};let s=document.querySelector("mave-pop:not([embed])");return s?(i=PT(s.querySelector("mave-player")),t=s,{pop:t,attributes:i}):(t=new MT,document.body.appendChild(t),{pop:t})}(i);t(i,s),e.addEventListener("click",(e=>{e.preventDefault();let n=document.querySelectorAll("mave-player");if(!Array.from(n).find((e=>e.popped))){let e=t(i,s);r.open(e).then((()=>{e.play()})),r.addEventListener("closed",(()=>{e.pause()}))}}))}))}i(e),new MutationObserver((e=>{for(let t of e)"childList"===t.type&&t.addedNodes.forEach((e=>{e instanceof HTMLElement&&i(e)}))})).observe(document.body,{childList:!0,subtree:!0})};"loading"===document.readyState?document.addEventListener("DOMContentLoaded",(()=>{OT(document)})):setTimeout((()=>OT(document)),500);var UT,NT,$T,FT,BT=class extends $n{constructor(){super(...arguments),At(this,UT),this.order="newest",this.embedController=new On(this,0)}connectedCallback(){super.connectedCallback(),this.embedController.token=this.token}requestUpdate(e,t){super.requestUpdate(e,t),"embed"===e&&(this.embedController.token=this.token)}get _slottedChildren(){return this.shadowRoot?.querySelector("slot")?.assignedElements({flatten:!0})||[]}updated(){this.shadowRoot&&OT(this.shadowRoot)}refresh(){return this.embedController.refresh()}containsEmbed(e){return this._collection?.videos?.some((t=>t.id===e))}getNextForEmbed(e){let t=_t(this,UT,NT).call(this),i=t.findIndex((t=>t.id===e));if(-1!==i)return t[i+1]}render(){return B`
      ${this.embedController.render({pending:this.renderPending,error:e=>B`<p>${e instanceof Error?e.message:G}</p>`,complete:e=>{if(this._collection=e,!e)return this.renderPending();if(e.error)return console.warn(e.error);let t=this._slottedChildren.map((e=>{function t(){let t;return t="TEMPLATE"===e.nodeName?e.content.cloneNode(!0):e.cloneNode(!0),t}if("list-title"==e.getAttribute("name")){let e=t();return e.textContent=this._collection?.name,B`${e}`}if("mave-list-root"==e.getAttribute("name")&&this.embedController.embed){let e=t(),i=e.querySelector('[slot="root-link"]');return i&&(i.addEventListener("click",(e=>{e.preventDefault(),this.emit(this.EVENT_TYPES.CLICK,{action:"back",embedId:""}),this.embedController.embed=""})),i.removeAttribute("slot")),B`${e}`}if("mave-list-folder"==e.getAttribute("name")){let i=this._collection.collections?.map((i=>{let r=t(),s=r.querySelector('[slot="folder-link"]');return[e,s].forEach((e=>{e&&(e.addEventListener("click",(e=>{e.preventDefault(),this.emit(this.EVENT_TYPES.CLICK,{action:"show_collection",collectionId:i.id}),this.embedController.embed=i.id})),e.removeAttribute("slot"))})),_t(this,UT,FT).call(this,r,'[slot="folder-title"]',i.name),"number"==typeof i.video_count&&_t(this,UT,FT).call(this,r,'[slot="folder-count"]',i.video_count.toString()),B`${r}`}));return B`${i}`}if("mave-list-item"==e.getAttribute("name")||!["mave-list-folder","mave-list-item","mave-list-root","list-title"].includes(e.hasAttribute("name")?e.getAttribute("name"):"")&&"TEMPLATE"==e.nodeName){let e=_t(this,UT,NT).call(this).map(((e,i)=>{let r=t(),s=i+1;return _t(this,UT,FT).call(this,r,'[slot="item-title"]',e.name),_t(this,UT,FT).call(this,r,'[slot="item-position"]',s.toString()),_t(this,UT,FT).call(this,r,'[slot="item-duration"]',this.durationToTime(e.duration)),_t(this,UT,$T).call(this,r,"mave-clip",e.id),_t(this,UT,$T).call(this,r,"mave-player",e.id),_t(this,UT,$T).call(this,r,"mave-img",e.id),[r.querySelector("mave-clip"),r.querySelector('[slot="item-title"]'),r.querySelector("mave-img"),r].forEach((t=>{t?.addEventListener("click",(t=>{this.emit(this.EVENT_TYPES.CLICK,{action:"show_embed",embedId:e.id,position:s})}))})),B`${r}`}));return B`${e}`}})).filter((e=>e));return B`${this._stylesheets} ${t}`}})}
    `}renderPending(){return B`<slot style="display: none"></slot>`}};UT=new WeakSet,NT=function(){if(!this._collection)return[];let e=this._collection.videos;return"newest"==this.order&&(e=this._collection.videos?.sort(((e,t)=>t.created-e.created))),"oldest"==this.order&&(e=this._collection.videos?.sort(((e,t)=>e.created-t.created))),"az"==this.order&&(e=this._collection.videos?.sort(((e,t)=>e.name.localeCompare(t.name)))),"za"==this.order&&(e=this._collection.videos?.sort(((e,t)=>t.name.localeCompare(e.name)))),e},$T=function(e,t,i){let r=e.querySelector(t);r&&(r.setAttribute("embed",i),r.removeAttribute("slot"))},FT=function(e,t,i){let r=e.querySelector(t);r&&(r.textContent=i,r.removeAttribute("slot"))},BT.styles=oe`
    :host {
      display: block;
    }
  `,bt([rt()],BT.prototype,"token",2),bt([rt()],BT.prototype,"order",2),window&&window.customElements&&(window.customElements.get("mave-list")||window.customElements.define("mave-list",BT));export{Nn as Clip,Vn as Files,Kn as Image,BT as List,xT as Player,MT as Pop,wt as Text,dn as Upload,y as setConfig};export default null;
//# sourceMappingURL=/sm/ea99d214344a941f7212c21ff0fad0caab12b6a5a1737b744dddbc850cbc11b2.map